I'm trying to execute this piece of code to run 2 motors on my robot. The code is really simple it's just repetitive.
For some reason that I can't figure out, the motors run unevenly. Here is the code for the testing file:
import RPi.GPIO as GPIO
import motor2
print("directions: ")
print("f = go forward\n")
print("b = go backward\n")
print("l = go left\n")
print("r = go right\n")
print("s = stop\n")
print("q = to exit program\n")
try:
while True:
direction = input("Please enter the direction you want to go, e.g: f ")
print('You entered', direction)
if direction == 'q':
quit()
t = int(input("Please enter the power the wheels\n"))
if direction == 'f':
motor2.forward(t)
elif direction == 'b':
motor2.backward(t)
elif direction == 'r':
motor2.turnright(t)
elif direction == 'l':
motor2.turnleft(t)
elif direction == 's':
motor2.stopMotor(t)
except KeyboardInterrupt:
print('key board interrupted!')
finally:
GPIO.cleanup()
This is motor2.py: the file that it refers to:
def init():
GPIO.setmode(GPIO.BCM)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(3,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(20,GPIO.OUT)
GPIO.setup(27,GPIO.OUT)
GPIO.setup(21,GPIO.OUT)
def forward(tf):
init()
p1 = GPIO.PWM(20,50)
p2 = GPIO.PWM(16,50)
p1.start(30)
p2.start(30)
GPIO.output(20, True)
GPIO.output(27, True)
GPIO.output(21, False)
GPIO.output(13, False)
GPIO.output(3, True)
GPIO.output(16, True)
time.sleep(tf)
GPIO.cleanup()
def backward(tf):
init()
p1 = GPIO.PWM(20,50)
p2 = GPIO.PWM(16,50)
p1.start(30)
p2.start(30)
GPIO.output(20, False)
GPIO.output(27, True)
GPIO.output(21, True)
GPIO.output(13, True)
GPIO.output(3, True)
GPIO.output(16, False)
time.sleep(tf)
GPIO.cleanup()
def turnright (tf):
init()
p1 = GPIO.PWM(21,50)
p2 = GPIO.PWM(16,50)
p1.start(50)
p2.start(50)
GPIO.output(20, False)
GPIO.output(27, True)
GPIO.output(21, True)
GPIO.output(13, False)
GPIO.output(3, True)
GPIO.output(16, True)
time.sleep(tf)
GPIO.cleanup()
def turnleft(tf):
init()
p1 = GPIO.PWM(21,50)
p2 = GPIO.PWM(16,50)
p1.start(50)
p2.start(50)
GPIO.output(20, True)
GPIO.output(27, True)
GPIO.output(21, True)
GPIO.output(13, True)
GPIO.output(3, True)
GPIO.output(16, False)
time.sleep(tf)
GPIO.cleanup()
def stopMotor(tf):
init()
GPIO.output(16, False)
GPIO.output(20, False)
time.sleep(tf)
The pin numbers have been entered correctly and the wiring has been checked. Any and everytime I run this the right motor gets more power than the left. Any help would be greatly appreciated!