0
votes

I am new to Raspberry pi. Currently I am doing a project and I am using raspberry pi 3 model B. My servos are SG90 micro servos. I want to run two servos simultaneously. And also in a way that they are synchronize. Up to now I have managed to run the two servo using 11 and 13 pins. Here is my current code

import RPi.GPIO as GPIO
import time

l = 0
r = 0

lServoPin = 11
rServoPin = 13
GPIO.setmode(GPIO.BOARD)

GPIO.setup(lServoPin, GPIO.OUT)
GPIO.setup(rServoPin, GPIO.OUT)

lPwm = GPIO.PWM(lServoPin, 50)
rPwm = GPIO.PWM(rServoPin, 50)
lPwm.start(5)
rPwm.start(5)

while(l < 5):
    for i in range(45, 135):
        position = 1./18.*(i)+2
        lPwm.ChangeDutyCycle(position)
        time.sleep(0.005)

    for i in range(135, 45, -1):
        position = 1./18.*(i)+2
        lPwm.ChangeDutyCycle(position)
        time.sleep(0.005)
    l = l + 1
lPwm.stop()

while(r < 5):
    for i in range(135, 45, -1):
        position = 1./18.*(i)+2
        rPwm.ChangeDutyCycle(position)
        time.sleep(0.005)

    for i in range(45, 135):
        position = 1./18.*(i)+2
        rPwm.ChangeDutyCycle(position)
        time.sleep(0.005)
    r = r + 1
rPwm.stop()
GPIO.cleanup()

Above code only run servos one after the other. What am I doing wrong here?? Could someone suggest me a way to run two synchronized servos simultaneously.

Thank you very much in advance!!!

1

1 Answers

0
votes

What you're doing is, you're running 2 loops. 1 for left motor and 1 for right motor. If you want to run them together, you need to put both these motors in one loop.

Try this code:

x=0    
while(x<5):
    for i in range(45, 135):
        positionl = 1./18.*(i)+2
        positionr = 1./18.*(180-i)+2
        lPwm.ChangeDutyCycle(positionl)
        rPwm.ChangeDutyCycle(positionr)
        time.sleep(0.005)
    for i in range(135, 45, -1):
        positionl = 1./18.*(i)+2
        positionr = 1./18.*(180-i)+2
        lPwm.ChangeDutyCycle(positionl)
        rPwm.ChangeDutyCycle(positionr)
        time.sleep(0.005)
    x = x + 1

lPwm.stop()
rPwm.stop()
GPIO.cleanup()

Hope this helps