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()
3
  • 1
    Well, one trick is make the steps very small. Another is instead use a stepping motor with microstepping control.
    – tlfong01
    Jun 14, 2021 at 13:42
  • I expect joan's answer to help, but just for for the sake of completeness: is your servo able to move smoothly at all? Did you try to control it with an Arduino or a signal generator? Jun 14, 2021 at 14:55
  • I think this question is impossible to answer without knowing what you mean by "erratic" exactly. A short video could help. There's several reasons why the motion of a servo can be irregular. Some of the reasons have already been mentioned in the comments and an answer but a lack of current can also cause this problem.
    – Opifex
    Jun 15, 2021 at 10:35

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.