Motor Control using Raspberry Pi 4

I finally got a raspberry pi 4 and started playing around with it. My first project was to automate the lights in my room. Then I thought of building myself a series of robots. I started with trying to build a line following robot but got stuck trying to run the motor with rasapberry pi 4. There were too less tutorials for a newbie like me to understaand fully how to make all the connections. So I thought of writing my blog to make life of others like me who have just bought a raspberry pi easier.

In this tutorial, I will show how to run 2 DC gear motors with raspberry pi.

Materials Required:

(I have posted the links for items I got.)

  1. Raspberry pi 4 (any model is okay).
  2. IC L293D
  3. breadboard
  4. DC Gear Motor (2)

Here are the L293D pins and raspberry pi4 pins for reference

Lets first look at how the connections look once everything is completed.

I know the wires look extremely confusing. So now let's understand what is going on here.

The L293D has 16 pins and its numbering starts from the left side of the curve. We connect it to the center of the breadboard as you can see in the picture. Now lets start connecting the motors. On OUTPUT 1 and OUTPUT 2 (pin 3 and 6) of the L293D we will connect 1 motor and on OUTPUT 3 and OUTPUT 4 (pin 11 and 14) we will connect the other motor. Now let’s connect the INPUT pins with the raspberry pi GPIO pin.

  1. INPUT 1 -> GPIO 2
  2. INPUT 2 -> GPIO 3
  3. INPUT 3 -> GPIO 4
  4. INPUT 4 -> GPIO 14

Now connect the ground of both the sides and then join the ground of both the sides. We will now connect the ground with -ve part of the breadboard. Now to connect it to raspberry pi. Lets connect the Vs pin (i.e. pin 8) to the positive part of the breadboard and then connect the positive part of breadboard to 5V pin (pin 2) of raspberry pi. Now connect the -ve terminal of the breadboard to the GND of raspberry pi (pin 6). Lets connect batteries connected in series with the -ve (black wire) and +ve (red wire) part of the breadboard respectively. Now!!! for the last step, let’s connect the Vss pin with the +ve supply of battery.

Now that our setup is ready 🥳, Lets code !

While coding, I came across a library , “gpiozero” [It is present by default in raspbian image]. This makes our life very easy.

from gpiozero import OutputDevice
motor1 = Outputdevice(2)
motor1 = Outputdevice(4)
# this will run the first motor
# this will run the second motor

Now to run both these together

from gpiozero import Motor
forwardMotor1 = 4
backwardMotor1 = 14
forwardMotor2 = 2
backwardMotor2 = 3
motor1 = Motor(forwardMotor1, backwardMotor1)
motor2 = Motor(forwardMotor2, backwardMotor2)
# now to move it forward
#to reverse it

TADA!!!!!….. And you are good to go…….

Hi, I am Ankita. I write about Machine Learning and how I try to navigate the puzzle called life!