2

I am having some trouble with controlling the motion of the servo motor. When I run my code, the servo motor moves in the specified range but the motion seems a bit erratic. I would be really grateful if I could get any suggestions on how the motion can be smoother, whether it requires any modifications to the code or some other means. Please find attached the code below.

Thank you for your time.

import RPi.GPIO as GPIO
import time
from decimal import *
def moveServo(fromLocation,toLocation,p):
    distance = Decimal(toLocation)-Decimal(fromLocation)
    steps = int(abs(distance)*10)
    for i in range(steps):
        print(Decimal(fromLocation)+distance/steps * i)
        p.ChangeDutyCycle(Decimal(fromLocation)+distance/steps*i)
        time.sleep(0.1)

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

p = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM with 50Hz p.start(2.5) # Initialization try: while True: moveServo(2.5,4.0,p) time.sleep(2) moveServo(4.0,2.5,p) time.sleep(2) #p.ChangeDutyCycle(4.0) #time.sleep(5)

except KeyboardInterrupt: p.stop() GPIO.cleanup()

Usman
  • 21
  • 3

1 Answers1

7

The most likely reason is be because you are using software timed servo pulses. Any variation in timing accuracy leads to jitter (servo trembling).

I suggest you use hardware timed pulses to drive servos.

Look at pigpio or servoblaster.

joan
  • 71,852
  • 5
  • 76
  • 108