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()