0

As a newbie I'm testing my Pi2B with a Micro Servo SG90 attached. Im running the code below. It works quitte fine, but it doesn't hold the left and right position steadily, there are small vibrations. My Pi has a bluetooth mouse, and when I use it, the servo starts shaking heavily. How can I prevent this behaviour?

I use an external powersupply for the servo, but removing it and having the servo powered by the Pi doesn't solve it. Neither does using another usb charger for the Pi. Removing the bluetooth adapter from the Pi doesn't stop the small vibrations.

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)

p = GPIO.PWM(17, 50)
p.start(6.55)

for i in range(1000):

    p.ChangeDutyCycle(6.55)
    time.sleep(3)
    p.ChangeDutyCycle(6.85)
    time.sleep(3)

p.stop()
GPIO.cleanup()
Pang
  • 9,564
  • 146
  • 81
  • 122
Willem-Jan
  • 67
  • 8

1 Answers1

0

You need to use hardware timed PWM for servos.

Try using PiGPIO

Example copied and modified from: https://raspberrypiwonderland.wordpress.com/2014/02/19/servo-test/

import time
import pigpio

servos = 4 #GPIO number

pigpio.start()
#pulsewidth can only set between 500-2500
try:
    while True:
        pigpio.set_servo_pulsewidth(servos, 500) #0 degree
        print("Servo {} {} micro pulses".format(servos, 1000))
        time.sleep(1)
        pigpio.set_servo_pulsewidth(servos, 1500) #90 degree
        print("Servo {} {} micro pulses".format(servos, 1500))
        time.sleep(1)
        pigpio.set_servo_pulsewidth(servos, 2500) #180 degree
        print("Servo {} {} micro pulses".format(servos, 2000))
        time.sleep(1)
        pigpio.set_servo_pulsewidth(servos, 1500)
        print("Servo {} {} micro pulses".format(servos, 1500))
        time.sleep(1)

# switch all servos off
except KeyboardInterrupt:
    pigpio.set_servo_pulsewidth(servos, 0);

pigpio.stop()

Here's the guide for this library http://abyz.co.uk/rpi/pigpio/python.html#set_servo_pulsewidth

You may need to either move your servo signal connection or change the GPIO pin setting according to your setup.

Paul S
  • 3
  • 2