There are not any examples that I could find that properly show how to get a simple DC motor working with RaspberryPI.

This is a simple tutorial for "How to make a motor turn." Robots, wheels, conveyors, and all sorts of stuff can be made to move using simple Raspberry Code and really inexpensive RC-racer like motors. The parts for this can be purchased on eBay for about $10 (certainly under $20). This project assumes you have access to wires, old power supplies (scavenged from old electronic devices), and misc other items.

I would think this to be a fundamental must have in the journals of how-tos. After figuring it out from a confluence of different sources and some hacking. We have for you the simple steps for getting a standard DC motor to turn with a python code snippet on a raspberry pi.

Here's a youtube using an Arduino, not quite the same thing:

What is an "H-Bridge" and how does a DC motor change direction?

When you hook a dc motor up to {+} wire on one lead and {-} wire on the other lead, the motor turns a certain direction. When you switch the wires to other leads, the motor turns the other direction. But how do we "electronically" switch the electric polarity using circuits. ANSWER: H-Bridge.

The circuits for H-Bridges are non-trivial for the beginner. The L298N module is a simple ready to rock and roll "dual" H-bridge circuit board. That means you have the ability to control TWO motors in either direction.

You need to get the module board for this.


5 PCS Dual H Bridge DC Stepper Motor Drive Controller Board Module Arduino L298N http://www.ebay.com/itm/231454411738

Double H bridge drive Chip: L298N Logical voltage: 5V Drive voltage: 5V-35V Logical current: 0mA-36mA Drive current: 2A(MAX single bridge) Storage temperature: -20 to +135 Max power: 25W

CHEAP DC MOTOR w/ GEAR BOX Car Gear Motor TT Motor Robot


100% brand new and high quality Operating voltage: 3V~12VDC (recommended operating voltage of about 6 to 8V) Maximum torque: 800gf cm min (3V) No-load speed: 1:48 (3V time) The load current: 70mA (250mA MAX) (3V) This motor with EMC, anti-interference ability. The microcontroller without interference. Size: 7x2.2x1.8cm(approx)


Another instruction on doing pretty much same thing!

Step 1: Extra DC Power Supply Dedicated for Motor

Note the sample image has two power supplies, one for the Raspberry PI (see elsewhere for details.)

The motor needs a DC power supply in the Voltage range of the motor. I used a left over 5V old power supply. Make sure the power supply has enough amperage or power to make the motor turn what ever you're looking to drive.

OLD POWER SUPPLIES (power chargers)

Do you have an old toy, used electronics, broken something around the house that isn't used anymore. These old chargers and DC power plugs are awesome, cause they are old or connector is ruined or damaged, you can still use them for hacking and building stuff. Learn to read about DC power, (See the picture of the old cell phone charger these are mostly 5V, as this one is and current drive is pretty low like only 400mA).


The sizing of the power supply is outside of this scope. In my case, we are just getting the motor to turn one direction or the other.


You can use the power from batteries to run your motors too. Purchase 6V DC batteries, (NOTE: batteries are already DC power) to drive your motors. (see picture sample above).

NEVER USE RASPBERRY PI built in power to DRIVE motors.


The power to your motor needs to match. The motors we have are 6V DC hobby motors. If you're building something for real rather than just a quick learning tutorial like this one. Make sure you match you power drive to the motor requirements. Every motor needs different drive voltages. If you have less voltage than the motor needs then the motor will be under powered and may not turn what you want or might burn your power supply out, or worst start melting stuff. If your power supply is too high like for example you put 9 or 12 volts into a 6 volt motor, then the motor will turn really fast and hard. You see people hack their kids toy race cars with bigger batteries, the cars go fast and have a ton more power than the default design. These tricks always come at a costs for safety, reliability, and component breaking (melting, fires etc).

In our simple getting a motor to turn tutorial, a 5vDC old phone charger will suffice to drive a 6v motor, it's not optimum but it will work for a free spinning motor.

If the motor has torque or load in excessive the electrical power capabilities of the power supply the motor will likely stall. Go read about motor sizing, stalling, and hacking motors as your next learning adventure after this basic introduction.

Sample how to using chip instead of the controller:

Alternative reference how-to using the CHIPs on bread board instead of controller board.

Step 2: Connector Wires for Driving the Direction on the Motor.

The "GPIO" pins on the Raspberry PI will be used to "trigger" the l298n direction.

There are TWO pins per motor. One pin drives the power, {+} to one lead when the pin is activated.

If you have a PI2 or the newer B+ then there is a different pin layout for that. I did this one with the older base model B.

I like the pin outs that show the actual unit so you can rotate it to match the one on your desk next to your machine and get the correct pins. I'm always spatially screwing up, so I'll end up hooking up the wrong pins and on the raspberry pi, the two wrong pins together could cause the poor thing to burn out or atleast only crash and reboot (this has happened to me many times, so far lucky not the burn the PI up yet).

I'll talk more about the GPIO numbers versus the physical pin numbering nomenclature when we get to the code review. Suffice to say, if your code is not controlling the motors on/off directions, then likely you have the physical wires connected to the wrong pins or your code is referencing GPIO vs physical pin or visa-versa.



Check your physical pins with a volt meter or LED glow to make sure they are putting output when your code indicates the pin should be "HIGH" or energized.

Step 3: BREAD BOARD for Simplifying Wire Connections.

I used a bread board to make the wire connections easier.

Trust me on this for your first time, get yourself a cheap bread board or just buy or find a friend with a full Maker Kit.

Even a cheap prototyping green or brown board are good for hacking wires together. Plus they boards hold them in place from moving around and possibly shorting out.

1> hook your Raspberry USB micro charger up to your standard PI input.

2> hook your 2nd power supply for your DC motor up to the + - on the bread board.

There's a few WHY and HOW to use electronic bread boards here on Instructables.


Link to instructable "breadboard" how -to use.

Step 4: Code Snippet Python Sample Make Motor Turn One Way Then Other

Code snippets for python.

This page assume you have enough knowledge of python to know it's a programming language that's human readable and typed into a text file. Some experience with copy and paste will be required. Read the error messages and happy hacking your python motor codes.

GPIO vs Physical Pin Nomenclature:

There are virtual "GPIO" names for certain pins that are digital output pins, these overlay on top of or in lieu of the actual PIN numbering from the board layout. When writing your code you'll need to indicate which one of the pin numbering systems that you're using. The board pin number or the GPIO.



Here's the basic python code snippet for turning pins on/ off:

<p>import RPi.GPIO as GPIO
# Use GPIO numbers not pin numbers
# set up the GPIO channels - one input and one output
GPIO.setup(7, GPIO.IN)
GPIO.setup(8, GPIO.OUT)
# input from GPIO7
input_value = GPIO.input(7)
# output to GPIO8
GPIO.output(8, True)</p>


# Import required libraries
import sys import time import RPi.GPIO as GPIO

# Use BCM GPIO references # instead of physical pin numbers #GPIO.setmode(GPIO.BCM) mode=GPIO.getmode() print " mode ="+str(mode) GPIO.cleanup()

# Define GPIO signals to use # Physical pins 11,15,16,18 # GPIO17,GPIO22,GPIO23,GPIO24

StepPinForward=16 StepPinBackward=18 sleeptime=1

GPIO.setmode(GPIO.BOARD) GPIO.setup(StepPinForward, GPIO.OUT) GPIO.setup(StepPinBackward, GPIO.OUT)

def forward(x): GPIO.output(StepPinForward, GPIO.HIGH) print "forwarding running motor " time.sleep(x) GPIO.output(StepPinForward, GPIO.LOW)

def reverse(x): GPIO.output(StepPinBackward, GPIO.HIGH) print "backwarding running motor" time.sleep(x) GPIO.output(StepPinBackward, GPIO.LOW)

print "forward motor " forward(5) print "reverse motor" reverse(5)

print "Stopping motor" GPIO.cleanup()

Run the motor from the raspberry pi command line like this:

sudo python motor.py

TROUBLESHOOTING add print statement to gauge progress.

print "Turning motor on"

Step 5: Troubleshooting.

Tools & Tricks:

  • VOLT Meter is requisite for troubleshooting.
  • Code snippets are helpful too.

Debugging Items:

  • Does the motor work if you put power directly to it from the 2nd power supply?
  • Does the 2nd power supply have a voltage near or about the rated level of the motor when read with meter?
  • Are the screws properly tighten on the wires?
  • Did you connect {-} or "ground" between the controller module and Raspberry PI?
  • Are the Raspberry PI GPIO pins properly connected to the controller board?
  • Are the Raspberry PI GPIO pins correct?
  • Is the Code referencing the right pin numbers for HIGH & LOW (GPIO vs actual nomenclature?)
  • Do you have the controller wires connected to the right set of pins left side are left 2, right side are right 2? (Idiot question I know, but stupider things have failed the space shuttle.)
  • Did you use the "sudo" command before typing your python motor.py ?
  • Did you spell any of the the commands with capital letters or mix case? Linux is case specific.
  • How far in the code does the print "code got this far before error" lines occur to debug your code?
<p>i only have one question: when i command the l298N to start powering the motor i notice that the light on the board gets dimmer but the pi is running without giving me any power warning should i be concerned about the light dimming ?</p>
<p>There is a video on Youtube that explains it very nice with a two wheeled robot: https://www.youtube.com/watch?v=AZSiqj0NZgU but I'm interested in how to control 4 motors. I guess I need 2 H Bridge Dual controller chips. Any tips on how to control that? Now that I think about it, as long as I can connect 2 L298N I guess I should be able to control them both through the GPIO.</p>
<p>No, you dont need 2, simply connect 2 motors to each side of the H-Bridge. Just stick the 2 red wires in one and 2 black in the other! Works for me!</p>
<p>I can bet my motors to spin on a small robot chassis, but only when the wheels are not touching the ground. Otherwise the wheels turn too slowly. I'm using 6V for the L298, external battery pack for the RPi. Any suggestions?</p>
<p>i use 9v they work fine :)</p>
<p>Thanks Sir i really had a tough time to find tutorial on this! </p>
Hi. nice ible. I'm using them for steppers. Do you know if it's possible to use two boards parallel? I fried a board because my stepper is using to much current. By parallel I mean stacking one on top of another and connect all terminal pins parallel and also the jumper pins. will the current equal divide? The max is 2A amps. I need 4A. Thanks.
<p>Great info on H-Bridges! Thanks for sharing! </p>

About This Instructable




More by kenm5:Raspberry PI L298N Dual H Bridge DC Motor 
Add instructable to: