Dc motor with Raspberrypi

In blog, we will interface the L298N H-bridge with raspeberry pi and run a script on the pi to move the robot. This will be divided into 2 sections.

  • Hardware Integration
  • Software Program and testing

Let’s go.

Hardware Integration First, let’s talk about L298N.

https://miro.medium.com/v2/resize:fit:828/format:webp/1*3yYHE5bNTGZ0iBc1veo4kg.png

General diagram of driver ports

https://miro.medium.com/v2/resize:fit:640/format:webp/1*cjka6xCrfWP9RiK6oYh1jw.png

We have 4 6V DC motors, and we have only two motor outputs, therefore, 2 motors will use the same motor output from the H-bridge. Hence, 2 motors connect to Motor A output, the other 2 motors connect to the Motor B output.

Before we connect the motor driver to the pi, let’s take care of the battery pack which would power the motors. The +ve of the batter pack gets connected to the power supply connection from the image and the -ve of the battery pack gets connected to the GND.

Connections

https://miro.medium.com/v2/resize:fit:828/format:webp/1*YpuOuUpKVDQAGNMuyRM9GQ.png

Once the battery pack (Power supply) is connected properly to the H-bridge, a red light will start glowing.

https://miro.medium.com/v2/resize:fit:750/format:webp/1*abmbzAck2g5JTw58dH5NZQ.png

Now, let’s connect the H-bridge with raspberry pi. There can be many combinations for connecting L298N to pi. This is one of them:

Raspberry pi connection

L298N — H bridge Connects to:
IN1 RPi GPIO 21
IN2 RPi GPIO 20
IN3 RPi GPIO 16
IN4 RPi GPIO 12
  1. Software Program and testing

Now that the hardware of H-Bridge has been interfaced with the Pi, let’s write a python program to run this hardware and see some action ;p.

import RPi.GPIO as gpio
import time
def init():    
    gpio.setmode(gpio.BCM)
    gpio.setup(21, gpio.OUT)
    gpio.setup(20, gpio.OUT)
    gpio.setup(16, gpio.OUT)
    gpio.setup(12, gpio.OUT)
def forward(sec):
    init()
    gpio.output(21, False)
    gpio.output(20, True)
    gpio.output(16, True)
    gpio.output(12, False)
    time.sleep(sec)
    gpio.cleanup() 
def reverse(sec):
    init()
    gpio.output(21, True)
    gpio.output(20, False)
    gpio.output(16, False)
    gpio.output(12, True)
    time.sleep(sec)
    gpio.cleanup()
def left_turn(sec):
    init()
    gpio.output(21, True)
    gpio.output(20, False)
    gpio.output(16, True)
    gpio.output(12, False)
    time.sleep(sec)
    gpio.cleanup()
def right_turn(sec):
    init()
    gpio.output(21, False)
    gpio.output(20, True)
    gpio.output(16, False)
    gpio.output(12, True)
    time.sleep(sec)
    gpio.cleanup()
seconds = 1
time.sleep(seconds)
print("forward")
forward(seconds)
time.sleep(seconds-0.5)
print("right")
right_turn(seconds)
time.sleep(seconds-0.5)
time.sleep(seconds)

Code is available at https://github.com/AbelBekele/RaspberryPi-home