Skip to main content

H-bridge motor drivers

A DC motor turns one way with current one way round, and the other way with it reversed. An H-bridge driver switches that for you: two GPIO pins set each motor's direction, and a PWM pin sets its speed. The motors take their current from their own supply, never from the Pi.

This page builds a line follower on a TB6612FNG, a small driver for two motors. Two infrared sensors at the front look down at a line of black tape, and the car steers to keep the line between them.

What you need​

  • A Raspberry Pi 3 B+, Zero 2 W or 4. The car in the clip runs on a Zero 2 W. A Zero 2 W's 40-pin header comes unsoldered, unless it's a Zero 2 WH.
  • Adafruit's Mini Round Robot chassis, with its two motors, two wheels and ball caster.
  • A TB6612FNG driver board, with its two 8-pin headers soldered on, pins up, so jumper wires push onto them.
  • Two infrared line sensors with a digital output (DO) and a screw to set how dark counts as "line".
  • A USB power bank for the Pi, strapped to the top deck.
  • Power for the motors, 3 to 6 V. A 4×AA holder with a switch gives 6 V, and the switch is the car's off switch.
  • About 18 female-to-female jumper wires, one for every connection.
  • Black electrical tape on a light floor or table, in a loop with curves no tighter than a 20 cm radius to start.

Mount both sensors at the front, pointing straight down about 5 mm above the floor, about 3 cm apart center to center, so the tape fits between them with a little floor under each. The front is the end the car drives toward, and "left" and "right" are the car's own.

Wiring​

Pins are the 40-pin header's positions. Pin 1 is the corner pin nearest the SD card, and the odd pins are on the inside row.

Pi pinGPIOGoes toWhat it does
13.3 Vleft sensor VCCPowers it. Never 5 V: the sensor's output goes straight to a GPIO.
9groundleft sensor GND
74left sensor DOLine or floor. Leave AO unconnected.
173.3 Vright sensor VCCPowers it. Never 5 V.
14groundright sensor GND
1117right sensor DOLine or floor. Leave AO unconnected.
3616driver VCCPowers the driver's logic, 1 to 2 mA. The motors can't turn until a program sets it high.
34grounda driver GNDJoins the Pi's ground to the driver's. Its GND pins are all connected.
3212driver PWMALeft wheel speed
295driver AIN1Left wheel direction
316driver AIN2Left wheel direction
3313driver PWMBRight wheel speed
3820driver BIN1Right wheel direction
4021driver BIN2Right wheel direction
3726driver STBYHigh wakes the driver

On the driver's other side, VM goes to the motor power's +, another GND to its −, A01 and A02 to the left motor, and B01 and B02 to the right motor.

  • The speed pins are GPIO 12 and 13. PWM runs on GPIO 12, 13, 18 and 19, and 12 and 18 share one channel, so the two wheels take one pin from each pair.
  • The motors' current comes in on VM. Don't feed VM from the Pi's 5 V pin: a wheel starting or stalling pulls up to 1.5 A and can reset the Pi.

1. Check the sensors​

Run checkSensors: in IntelliJ, click the run icon beside entrypoint checkSensors(). For 30 seconds it prints what each sensor sees, five times a second:

left line right floor

Slide the tape under one sensor at a time, and turn that sensor's screw until it says line over the tape and floor off it. If it names the wrong side, swap LEFT_SENSOR and RIGHT_SENSOR. If both read backwards, set LINE_READS_HIGH = false.

2. Check the wheels​

Lift the car off the table and run checkWheels. Each wheel turns forward for a second, then backward. Forward rolls the car forward, sensors first. If a wheel turns the wrong way, turn its plug around on the driver; if the wrong wheel turns, swap the two plugs.

3. Follow the line​

Put the car on the tape, with the tape between its sensors, and run follow, the default. The Pi's green light blinks three times, then the car goes. When one sensor sees the tape, the car turns firmly toward it. When neither does, it drifts gently toward the side that saw the tape last.

The car stops itself. Pick it up, and both sensors read line, since nothing reflects; let it lose the line, and neither does. Either way, about a second and a half later it stops both wheels, and the program ends. On V0 a run's end doesn't stop its PWM pins, so let the car stop itself this way. If the wheels are ever still turning when no program is running, run halt, or switch the motor power off.

The program​

The wheels and sensors are the Pi's own pins: DigitalOutput and DigitalInput for on and off, Pwm for speed.

namespace demo.linefollower

import grandtheorem.rpi.Pi
import grandtheorem.devices.DigitalInput
import grandtheorem.devices.DigitalOutput
import grandtheorem.devices.Pull
import grandtheorem.devices.Pwm
import namespace nylon.time

Everything you might tune is a let at the top.

# How fast the wheels turn, 0 to 100. FAST is the outside wheel of a turn. SLOW is the inside wheel when a sensor sees
# the line, a firm turn. DRIFT is the inside wheel while neither does, a gentle one. Keep SLOW < DRIFT < FAST. If the
# car loses the line on a curve, lower SLOW; if it weaves too much on a straight, raise DRIFT.
let FAST = 40
let SLOW = 25
let DRIFT = 30

# Which GPIO each sensor's OUT is on. If `checkSensors` has them the wrong way round, swap the numbers.
let LEFT_SENSOR = 4
let RIGHT_SENSOR = 17

# The GPIO that powers the driver's logic, its VCC pin, and the one on its STBY pin. The motors can't turn until a
# program sets both high.
let DRIVER_POWER = 16
let STANDBY = 26

# What a sensor reads over the black line. Most boards read high there, with their small light off. If
# `checkSensors` says "line" over the floor, change this to false.
let LINE_READS_HIGH = true

# How many looks in a row, about 200 a second, before the car decides it's lost, or been picked up, and stops.
let LOST_LOOKS = 300

# PWM pulses a second for the wheels. 20,000 is above hearing, so the motors don't whine.
let PULSES = 20000

follow looks at both sensors 200 times a second. One sensor on the line: the car has drifted, so it turns toward that sensor. Both: it's across the line, or at a crossing, so it goes straight on. Neither: the line is between them, or the car overshot it, so it drifts toward the side that saw it last. One sensor can't tell which side of the line it's on. Two can, so an overshoot is never a wrong turn.

# Follows the line until it loses it, or it's picked up.
entrypoint.default follow() {
Pi.gpioOutput(DRIVER_POWER, true)
let standby = Pi.gpioOutput(STANDBY, true)
let left = leftWheel()
let right = rightWheel()
let leftEye = leftSensor()
let rightEye = rightSensor()
Pi.statusLed().blink(3)
println("following")

var lineWasLeft = true
var neither = 0
var both = 0
while (neither < LOST_LOOKS and both < LOST_LOOKS) {
let onLeft = seesLine(leftEye)
let onRight = seesLine(rightEye)
if (onLeft and onRight) {
left.drive(FAST)
right.drive(FAST)
both = both + 1
neither = 0
} else if (onLeft) {
left.drive(SLOW)
right.drive(FAST)
lineWasLeft = true
both = 0
neither = 0
} else if (onRight) {
left.drive(FAST)
right.drive(SLOW)
lineWasLeft = false
both = 0
neither = 0
} else {
if (lineWasLeft) {
left.drive(DRIFT)
right.drive(FAST)
} else {
left.drive(FAST)
right.drive(DRIFT)
}
both = 0
neither = neither + 1
}
sleep(5.milliseconds())
}

left.stop()
right.stop()
standby.write(false)
if (both >= LOST_LOOKS) {
println("both sensors saw the line, so it was picked up: stopped")
} else {
println("lost the line, so stopped: put the car back with the line between its sensors and press Run")
}
}

A Wheel is one motor on the driver: two direction pins and a speed pin.

# One wheel's motor on the driver: two pins that set its direction, and a PWM pin that sets its speed.
class Wheel(let forward: DigitalOutput, let backward: DigitalOutput, let speed: Pwm) {
# Turns the wheel at `percent` of full speed: forward for 1 to 100, backward for -1 to -100.
let drive(percent: i32) {
if (percent < 0) {
forward.write(false)
backward.write(true)
speed.write(-percent, 100)
} else {
forward.write(true)
backward.write(false)
speed.write(percent, 100)
}
}

# Stops the wheel, braking it.
let stop() {
speed.write(0, 100)
}
}

# The left wheel, on the driver's A side: PWMA on GPIO 12, AIN1 on GPIO 5 and AIN2 on GPIO 6.
let leftWheel(): Wheel = Wheel(Pi.gpioOutput(5), Pi.gpioOutput(6), Pi.gpioPwm(12, PULSES))

# The right wheel, on the driver's B side: PWMB on GPIO 13, BIN1 on GPIO 20 and BIN2 on GPIO 21.
let rightWheel(): Wheel = Wheel(Pi.gpioOutput(20), Pi.gpioOutput(21), Pi.gpioPwm(13, PULSES))

The sensors' pins are pulled up, so an unplugged sensor reads the same every time instead of floating.

# The left line sensor's OUT.
let leftSensor(): DigitalInput = Pi.gpioInput(LEFT_SENSOR, Pull.Up)

# The right line sensor's OUT.
let rightSensor(): DigitalInput = Pi.gpioInput(RIGHT_SENSOR, Pull.Up)

# Whether a sensor sees the line.
let seesLine(sensor: DigitalInput): boolean = sensor.read() == LINE_READS_HIGH

# What a sensor sees, to print.
let reading(sensor: DigitalInput): string {
if (seesLine(sensor)) {
return "line"
}
return "floor"
}

checkSensors and checkWheels are the two checks above, and halt stops both wheels from outside a run.

# Says what both sensors see, five times a second for 30 seconds. Move the tape under each one while you turn the
# little screw on its board, until each says "line" over the tape and "floor" off it.
entrypoint checkSensors() {
let leftEye = leftSensor()
let rightEye = rightSensor()
for (150 times) {
println("left ${reading(leftEye)} right ${reading(rightEye)}")
sleep(200.milliseconds())
}
}

# Turns each wheel forward for a second, then backward. Forward should roll the car forward, sensors first.
entrypoint checkWheels() {
Pi.gpioOutput(DRIVER_POWER, true)
let standby = Pi.gpioOutput(STANDBY, true)
let left = leftWheel()
let right = rightWheel()
println("left wheel forward")
left.drive(40)
sleep(1.seconds())
println("left wheel backward")
left.drive(-40)
sleep(1.seconds())
left.stop()
println("right wheel forward")
right.drive(40)
sleep(1.seconds())
println("right wheel backward")
right.drive(-40)
sleep(1.seconds())
right.stop()
standby.write(false)
}

# Stops both wheels and puts the driver to sleep, for wheels still turning when no program is running.
entrypoint halt() {
Pi.gpioOutput(STANDBY, false)
Pi.gpioPwm(12, PULSES).stop()
Pi.gpioPwm(13, PULSES).stop()
}

Boards: Raspberry Pi 3 B+, Raspberry Pi Zero 2 W and Raspberry Pi 4.