Controlling Two Motors Using Raspberry Pi And Python
This is a continuation to my first lesson on how we can control a DC motor using a Raspberry Pi and Python. If you would like to follow along with this lesson, and have not yet seen the first one, please read the first article found here.
In this lesson, we are going to add a second motor and implement functionality that allows us to control both motors at the same time.
Adding A Second Motor
Recall from the first lesson that a motor is defined by a class. We derived an object from that class in order to control 1 motor. However, since we took an abstracted approach when designing the program, we can simply create a second Motor
object to control two motors at the same time
In the main.py
file, we will have the following:
import motor # imports our motor.py class
import time
# Instantiates a motor using pins 7, 11
motor1 = motor.motor(7, 11)
# Instantiates a second motor using pins 8, 10
motor2 = motor.motor(8, 10)
Thats it! With just one more line of code, we can control two motors using a Raspberry Pi, Python, and a L298N chip. Let’s add some functions that will help us clean our code a bit. In the same file, I’m going to define 5 functions that will allow us to control both motors together.
import motor # imports our motor.py class
import time
# Sets both motors to forward
def forwards(m1, m2):
m1.forward()
m2.forward()
# Sets both motors to backward
def backwards(m1, m2):
m1.backward()
m2.backward()
# Stops both motors
def off(m1, m2):
m1.stop()
m2.stop()
# Turns on only right motor
def right(m1, m2):
m1.stop()
m2.forward()
# Turns on only left motor
def left(m1, m2):
m1.forward()
m2.stop()
# Instantiates 2 motors, assuming motor 1 is left and motor 2 right
motor1 = motor.motor(7, 11)
motor2 = motor.motor(8, 10)
# Moves motors up for 1 second
# Moves motors right for 1 second
# Moves motors backwards for 1 second
# Moves motors left for 1 second
forwards(motor1, motor2)
time.sleep(1)
off(motor1, motor2)
right(motor1, motor2)
time.sleep(1)
off(motor1, motor2)
backwards(motor1, motor2)
time.sleep(1)
off(motor1, motor2)
left(motor1, motor2)
time.sleep(1)
off(motor1, motor2)
If your motors do not move in the intended directions, check your wiring and/or the code and make adjustments as needed.