# Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

## Overview

This lesson describes how to control both the speed and direction of a DC motor using Python and a L293D chip. &nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/003/643/medium800/learn_raspberry_pi_overview.jpg?1396799328)

In Lesson 8, we used the Pi to generate pulses to control the position of a servo motor. In this lesson we use pulses to control the speed of a regular DC motor and the L293D motor control chip to reverse the direction of the current through the motor and hence the direction in which it turns.

# Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

## Parts

To build this project, you will need the following parts.

# Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

## PWM

Pulse Width Modulation (or PWM) is a technique for controlling power. We use it here to control the amount of power going to the motor and hence how fast it spins.

The diagram below shows the signal from the PWM pin of the Raspberry Pi. &nbsp;

![](https://cdn-learn.adafruit.com/assets/assets/000/003/652/medium800/learn_raspberry_pi_how_pwm_works.jpg?1396799428)

Every 1/500 of a second, the PWM output will produce a pulse. The length of this pulse controls the amount of energy that the motor gets. No pulse at all and the motor will not turn, a short pulse and it will turn slowly. If the pulse is active for half the time, then the motor will receive half the power it would if the pulse stayed high until the next pulse came along.

# Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

## The PWM Kernel Module

Adafruit and Sean Cross have created a kernal module that is included with the [Occidentalis](http://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0-dot-2 "Link: http://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0-dot-2") distribution. For details of creating an Occidentalis [follow this link](http://learn.adafruit.com/adafruit-raspberry-pi-lesson-1-preparing-and-sd-card-for-your-raspberry-pi). If you want to use the module with Raspbian or some other distribution, then there is help on installing the kernel module into your environment [here](http://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0-dot-2).

You used the PWM and Servo Kernel Module in Lesson 8, to control a Servo. This time, you will use the same module to control the speed of the motor.

The modules interface uses a file type of interface, where you control what the output pin and therefore the servo is doing, by reading and writing to special files. This makes it really easy to interface with in Python or other languages.

The files involved in using the module to drive a servo are listed below. All the files can be found in the directory /sys/class/rpi-pwm/pwm0/

# Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

## L293D

This is a very useful chip. It can actually control two motors independently. We are just using half the chip in this lesson, most of the pins on the right hand side of the chip are for controlling a second motor, but with the Raspberry Pi, we only have one PWM output.

![](https://cdn-learn.adafruit.com/assets/assets/000/003/653/medium800/learn_raspberry_pi_L293D.jpg?1396799434)

The L293D has two +V pins (8 and 16). The pin '+Vmotor (8) provides the power for the motors, and +V (16) for the chip's logic. We have connected pin 16 to the 5V pin of the Pi and pin 8 to a battery pack. &nbsp;

# Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

## Hardware

There are two reasons why we need to use a L293D chip in this project. The first is that the output of the Raspberry Pi is nowhere near strong enough to drive a motor directly and to try this may damage your Raspberry Pi.

Secondly, in this lesson, we want to control the direction of the motor as well as its speed. This is only possible by reversing the direction of the current through the motor, something that the L293D is designed to do, with the help of two control pins.

![](https://cdn-learn.adafruit.com/assets/assets/000/003/654/medium800/learn_raspberry_pi_breadboard.png?1396799472)

The project fits nicely on a half-sized breadboard.

# Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

## Software

Since we need to control pins (connected to pin 4 and 17 of the GPIO) we also need to use the GPIO library. For details of this, see [Lesson 4](http://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup "Link: http://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup").

There are lots of ways to get the sketch from the listing below onto your Raspberry Pi. Perhaps the easiest is to connect to your Pi using SSH (See [Lesson 6](http://learn.adafruit.com/adafruits-raspberry-pi-lesson-6-using-ssh)) opening an editor using the command below:

```
nano motor.py
```

and then pasting in the code below, before saving the files using CTRL-x.

![](https://cdn-learn.adafruit.com/assets/assets/000/003/655/medium800/learn_raspberry_pi_ssh_edit.png?1396799500)

Here is the code:

```
import RPi.GPIO as io
io.setmode(io.BCM)

in1_pin = 4
in2_pin = 17

io.setup(in1_pin, io.OUT)
io.setup(in2_pin, io.OUT)

def set(property, value):
    try:
        f = open("/sys/class/rpi-pwm/pwm0/" + property, 'w')
        f.write(value)
        f.close()	
    except:
        print("Error writing to: " + property + " value: " + value)
 
set("delayed", "0")
set("mode", "pwm")
set("frequency", "500")
set("active", "1")

def clockwise():
    io.output(in1_pin, True)    
    io.output(in2_pin, False)

def counter_clockwise():
    io.output(in1_pin, False)
    io.output(in2_pin, True)

clockwise()

while True:
    cmd = raw_input("Command, f/r 0..9, E.g. f5 :")
    direction = cmd[0]
    if direction == "f":
        clockwise()
    else: 
        counter_clockwise()
    speed = int(cmd[1]) * 11
    set("duty", str(speed))
```

The Python program first sets-up the two GPIO pins to be outputs. It then defines the same convenience function (“set”) that we used in Lesson 8, to write to the PWM Kernel Module. This is then used to set the parameters for PWM.

There are two other functions defined, “clockwise” and “counter\_clockwise”, that control the direction of the motor by changing the two input pins.

If both control pins are HIGH, or both LOW then the motor will be stopped. But if IN1 is HIGH and IN2 LOW it rotates in one direction, reversing in direction if the values of IN1 and IN2 are reversed.

The main loop of the program waits for you to enter commands in the format of a letter (“f” or “r”) and a digit between 0 and 9. The letter sets the direction of the motor and the digit the speed, by multiplying the digit by 11 to give a value between 0 and 99 that the PWM library expects.

# Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

## Test & Configure

To run the program, you will need to run it as super user to get access to the GPIO pins, so type:

```
sudo python motor.py
```

You will then get a prompt for you to enter a command. Try entering a few 2 letter commands as shown below.

```
$sudo python motor.py
Command, f/r 0..9, E.g. f5 :f9
Command, f/r 0..9, E.g. f5 :r4
Command, f/r 0..9, E.g. f5 :
```


## Featured Products

### Budget Pack for Raspberry Pi 1 Model B (Doesn't include RasPi)

[Budget Pack for Raspberry Pi 1 Model B (Doesn't include RasPi)](https://www.adafruit.com/product/965)
An optimized collection of parts and pieces to experiment with Raspberry Pi at home, school or work. Great for students and those that want to get their feet wet, no soldering required! **THIS PACK DOES NOT INCLUDE A RASPBERRY PI 1 MODEL B and is NOT compatible with Model B+ or Raspberry Pi...**

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/965)
[Related Guides to the Product](https://learn.adafruit.com/products/965/guides)
### Adafruit Assembled Pi Cobbler Breakout + Cable for Raspberry Pi

[Adafruit Assembled Pi Cobbler Breakout + Cable for Raspberry Pi](https://www.adafruit.com/product/914)
Now that you've finally got your hands on a [Raspberry Pi® Model B](http://www.raspberrypi.org/), you're probably itching to make some fun embedded computer projects with it. What you need is an add on prototyping Pi Cobbler from Adafruit, which can break out all those...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/914)
[Related Guides to the Product](https://learn.adafruit.com/products/914/guides)
### Premium Male/Male Jumper Wires - 40 x 6" (150mm)

[Premium Male/Male Jumper Wires - 40 x 6" (150mm)](https://www.adafruit.com/product/758)
Handy for making wire harnesses or jumpering between headers on PCB's. These premium jumper wires are 6" (150mm) long and come in a 'strip' of 40 (4 pieces of each of ten rainbow colors). They have 0.1" male header contacts on either end and fit cleanly next to each other...

In Stock
[Buy Now](https://www.adafruit.com/product/758)
[Related Guides to the Product](https://learn.adafruit.com/products/758/guides)
### Dual H-Bridge Motor Driver for DC or Steppers - 600mA - L293D

[Dual H-Bridge Motor Driver for DC or Steppers - 600mA - L293D](https://www.adafruit.com/product/807)
Run four solenoids, two DC motors, or one bi-polar or uni-polar stepper with up to 600mA per channel using the L293D. These are perhaps better known as "the drivers in our Adafruit Motorshield". If you accidentally damaged the drivers in a shield, you can use one of these puppies to...

In Stock
[Buy Now](https://www.adafruit.com/product/807)
[Related Guides to the Product](https://learn.adafruit.com/products/807/guides)
### DC Toy / Hobby Motor - 130 Size

[DC Toy / Hobby Motor - 130 Size](https://www.adafruit.com/product/711)
These are standard '130 size' DC hobby motors. They come with a wider operating range than most toy motors: from 4.5 to 9VDC instead of 1.5-4.5V. This range makes them perfect for controlling with an Adafruit Motor Shield, or with an Arduino where you are more likely to have 5 or 9V...

In Stock
[Buy Now](https://www.adafruit.com/product/711)
[Related Guides to the Product](https://learn.adafruit.com/products/711/guides)
### Half Sized Premium Breadboard - 400 Tie Points

[Half Sized Premium Breadboard - 400 Tie Points](https://www.adafruit.com/product/64)
This is a cute, half-size breadboard with&nbsp;400 tie points, good for small projects. It's 3.25" x 2.2" / 8.3cm&nbsp;x 5.5cm&nbsp;with a standard double-strip in the middle and two power rails on both sides.&nbsp;You can pull the power rails off easily to make the breadboard as...

Out of Stock
[Buy Now](https://www.adafruit.com/product/64)
[Related Guides to the Product](https://learn.adafruit.com/products/64/guides)
### Programming the Raspberry Pi: Getting Started with Python

[Programming the Raspberry Pi: Getting Started with Python](https://www.adafruit.com/product/1089)
 **Program your own Raspberry Pi projects!**

An updated guide to programming your own Raspberry Pi projects. Learn to create inventive programs and fun games on your powerful Raspberry Pi--with no programming experience required. **This practical book has been revised...**

In Stock
[Buy Now](https://www.adafruit.com/product/1089)
[Related Guides to the Product](https://learn.adafruit.com/products/1089/guides)

## Related Guides

- [Arduino Lesson 15. DC Motor Reversing](https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing.md)
- [Running Minecraft on a Raspberry Pi](https://learn.adafruit.com/running-minecraft-on-a-raspberry-pi.md)
- [Bonjour (Zeroconf) Networking for Windows and Linux](https://learn.adafruit.com/bonjour-zeroconf-networking-for-windows-and-linux.md)
- [Adafruit Pi Cobbler Kit](https://learn.adafruit.com/adafruit-pi-cobbler-kit.md)
- [Circuit Playground Sound-Controlled Robot](https://learn.adafruit.com/circuit-playground-sound-controlled-robot.md)
- [Using an IR Remote with a Raspberry Pi Media Center](https://learn.adafruit.com/using-an-ir-remote-with-a-raspberry-pi-media-center.md)
- [Introducing the Raspberry Pi Model B+](https://learn.adafruit.com/introducing-the-raspberry-pi-model-b-plus-plus-differences-vs-model-b.md)
- [Bluefruit LE Python Library](https://learn.adafruit.com/bluefruit-le-python-library.md)
- [Adafruit 2.4" PiTFT HAT with Resistive Touchscreen Mini Kit](https://learn.adafruit.com/adafruit-2-4-pitft-hat-with-resistive-touchscreen-mini-kit.md)
- [HalloWing Flapping Bat](https://learn.adafruit.com/hallowing-flapping-bat.md)
- [Raspberry Pi as a Media Center](https://learn.adafruit.com/raspberry-pi-as-a-media-center.md)
- [micro:bit Crickit Robot](https://learn.adafruit.com/microbit-crickit-robot.md)
- [Super Game Pi](https://learn.adafruit.com/super-game-pi.md)
- [Raspberry Pi RGB LED Matrix Webapp](https://learn.adafruit.com/raspberry-pi-rgb-led-matrix-webapp.md)
- [PiGRRL - Raspberry Pi Gameboy](https://learn.adafruit.com/pigrrl-raspberry-pi-gameboy.md)
