Monday, December 31, 2012

RaspberryPi: 2 bit H bridge

4 bit H Bridge

two modes, motor turning in different directions
A typical H bridge is what is required to drive a regular DC motor in both directions. The diagram above clearly shows how to accomplish this with 4 switches. But manipulating 4 switches is a pain, so we control this with transistors (in my case, 4 very common 2N2222 NPN transistors). However, although there appear to be only two modes, with 4 switches, or 4 bits, there are a lot more variations:

From the wikipedia article:

S1 S2 S3 S4 Result
1 0 0 1 Motor moves right
0 1 1 0 Motor moves left
0 0 0 0 Motor free runs
0 1 0 1 Motor brakes
1 0 1 0 Motor brakes
1 1 0 0 Shoot-through
0 0 1 1 Shoot-through
1 1 1 1 Shoot-through

The last 3 are to be avoided, since they short the power supply. This would be controlled by 4 GPIO pins. But there is a better solution (even though the name might not be appealing...):

2 bit H Bridge

For the PyHack workshop at the beginning of december, we controlled some gearhead motors (and a bunch other stuff) with the Raspberry Pi:


The main thing with these motors is that they are regular DC motors and can be run from two wires. But to reverse them, we need an H bridge. But why use up 4 GPIO, if all we want is to have the motor turn right, turn left or free run?

All we have to do is connect S1 to S4 and S2 to S3, and use 2 GPIOs to drive S1 and S2. On a breadboard, it looks like this:

closeup of the h bridge, right in the middle

4 different circuits: darlington array, direct, single and H Bridge



We are using pins 4 and 23 to control S1 and S2.

 The code

#!/usr/bin/env python

import RPi.GPIO as gpio
from time import sleep

# set the mapping mode for the GPIO numbering
gpio.setmode(gpio.BCM)

# DC Motor connected to pin 4
MOTORA = 4
MOTORB = 23

gpio.setup(MOTORA, gpio.OUT)
gpio.setup(MOTORB, gpio.OUT)

print("Ready...set...go!")

# Bring it to 3V3 (HIGH)
gpio.output(MOTORA, gpio.LOW)
gpio.output(MOTORB, gpio.HIGH)

print("it is on")
sleep(10)
gpio.output(MOTORB, gpio.LOW)
gpio.output(MOTORA, gpio.HIGH)

print("it is reversed")
sleep(10)
print("done")
gpio.cleanup() 

Diagram

I'm working on a way to publish diagrams and breadboard layouts, I should publish it along with a bill of material in a few days.

Update!: see the followup "Fritzing with Brython"

No comments:

Post a Comment