# Adafruit's Raspberry Pi Lesson 8. Using a Servo Motor

## Overview

This lesson describes how to control a single servo motor using Python. &nbsp;

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

Servo motors are controlled by pulses of varying lengths. This requires fairly accurate timing. The&nbsp;Raspberry Pi has one pin that generates pulses in hardware, without having to rely on the operating system.

# Adafruit's Raspberry Pi Lesson 8. Using a Servo Motor

## Parts

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

# Adafruit's Raspberry Pi Lesson 8. Using a Servo Motor

## Servo Motors

The position of the servo motor is set by the length of a pulse. The servo expects to receive a pulse roughly every 20 milliseconds. If that pulse is high for 1 millisecond, then the servo angle will be zero, if it is 1.5 milliseconds, then it will be at its centre position and if it is 2 milliseconds it will be at 180 degrees.

![](https://cdn-learn.adafruit.com/assets/assets/000/003/496/medium800/learn_raspberry_pi_servos.png?1396797327)

The end points of the servo can vary and many servos only turn through about 170 degrees. You can also buy 'continuous' servos that can rotate through the full 360 degrees.

# Adafruit's Raspberry Pi Lesson 8. Using a Servo Motor

## Hardware

There is only one pin on the Pi that is capable of producing pulses in this way (GPIO pin 18). This will be connected to the control pin of the servo. The power to the servo is provided by an external battery as powering the servo from the Pi itself is likely to cause it to crash as the Servo draws too much current as it starts to move. Servos require 4.8-6V DC power to the motor, but the signal level (pulse output) can be 3.3V, which is how its OK to just connect the signal line directly to the GPIO output of the Pi.

![](https://cdn-learn.adafruit.com/assets/assets/000/003/498/medium800/learn_raspberry_pi_fritzing.png?1396797393)

The Pi Cobbler is used to link the Raspberry Pi to the breadboard. If you have not used the Cobbler before take a look at [Lesson 4](http://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup) in this series.  
  
Servo motors generally come with three pin sockets attached. The red and brown sockets supply power (positive to red) and the third yellow or orange socket is for the control signal. To link the socket to the breadboard, use the male-to-male jumper wires.

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

# Adafruit's Raspberry Pi Lesson 8. Using a Servo Motor

## Software

We'll be using the great **wiringPi** tool **gpio** to control the servo. Begin by installing **gpio** with

`sudo apt-get install -y wiringpi`

![](https://cdn-learn.adafruit.com/assets/assets/000/036/880/medium800/learn_raspberry_pi_servo.png?1477713561)

Set pin #18 to be a PWM output

```auto
gpio -g mode 18 pwm
```

Pin #18 has PWM output, but you have to set it to be the right _frequency_ output. Servo's want 50 Hz frequency output

For the Raspberry Pi PWM module, the `PWM Frequency in Hz = 19,200,000 Hz / pwmClock / pwmRange`

If pwmClock is 192 and pwmRange is 2000 we'll get the PWM frequency = 50 Hz ([thx to kev for the numbers!](http://raspberrypi.stackexchange.com/questions/4906/control-hardware-pwm-frequency))

Now you can tell **gpio** to set the PWM clock to those numbers:

```auto
gpio pwm-ms
gpio pwmc 192
gpio pwmr 2000
```

Now you can set the servo to all the way to the left (1.0 milliseconds) with

```auto
gpio -g pwm 18 100
```

Set the servo to the middle (1.5 ms) with

```auto
gpio -g pwm 18 150
```

And all the way to the right (2.0ms) with

```auto
gpio -g pwm 18 200
```

Servos often 'respond' to a wider range than 1.0-2.0 milliseconds so try it with ranges of 50 (0.5ms) to 250 (2.5ms)

Of course you can try any number between 50 and 250! so you get a range of about 200 positions

Note that the Raspberry Pi PWM is not necessarily a 'stable' output, and there might be some jitter! [For a steady PWM signal, you'll want to check out a dedicated Servo HAT.](https://www.adafruit.com/products/2327)

# Python Example!

You can also use wiringPi in python! Run

`sudo apt-get install -y python-pip`

`sudo pip install wiringpi`

The Python program to make the servo sweep back and forth is listed below:

```auto
# Servo Control
import time
import wiringpi

# use 'GPIO naming'
wiringpi.wiringPiSetupGpio()

# set #18 to be a PWM output
wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT)

# set the PWM mode to milliseconds stype
wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)

# divide down clock
wiringpi.pwmSetClock(192)
wiringpi.pwmSetRange(2000)

delay_period = 0.01

while True:
        for pulse in range(50, 250, 1):
                wiringpi.pwmWrite(18, pulse)
                time.sleep(delay_period)
        for pulse in range(250, 50, -1):
                wiringpi.pwmWrite(18, pulse)
                time.sleep(delay_period)
```

We're basically using the wiringpi functions but _within_ python, so its easy to practice with the **gpio** utility and then use the matching commands in python

A variable (delay\_period) is used to contain the time in seconds between each step of the servo.

The while loop will just continue forever or until the program is interrupted by pressing CTRL-C. Within the loop there are two near identical 'for' loops. The first counts the pulse width up from 5.0ms to 2.5ms and the second sets the pulse with starting with 2.5m and counts down to 0.5ms, moving the servo arm back and forth.

To install the software, connect to your Pi using SSH and then type the command:

```auto
$ nano servo.py
```

Paste the code above into the editor and then do CTRL-X and Y to save the file.

![](https://cdn-learn.adafruit.com/assets/assets/000/003/497/medium800/learn_raspberry_pi_install.png?1396797360)

To run the servo program just type the following command into your SSH window:

```auto
$ sudo python servo.py
```

The servo should start to move straight away. &nbsp;

# Adafruit's Raspberry Pi Lesson 8. Using a Servo Motor

## Test & Configure

If you want to make the servo move faster, try changing delay\_period to a smaller value, say 0.001. Then to slow it down try increasing it to 0.1.

If you want to control more than one servo, then the easiest way to do this is to use something like the [Adafruit I2C 16 channel servo / pwm&nbsp;controller](http://www.adafruit.com/products/815). [This tutorial](http://learn.adafruit.com/adafruit-16-channel-servo-driver-with-raspberry-pi/overview) explains how to use it.


## 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...

Out of Stock
[Buy Now](https://www.adafruit.com/product/758)
[Related Guides to the Product](https://learn.adafruit.com/products/758/guides)
### Standard servo - TowerPro SG-5010

[Standard servo - TowerPro SG-5010](https://www.adafruit.com/product/155)
This high-torque standard servo can rotate approximately 180 degrees (90 in each direction). You can use any servo code, hardware, or library to control these servos. Good for beginners who want to make stuff move without building a motor controller with feedback & gearbox. Comes with 3...

In Stock
[Buy Now](https://www.adafruit.com/product/155)
[Related Guides to the Product](https://learn.adafruit.com/products/155/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...

In Stock
[Buy Now](https://www.adafruit.com/product/64)
[Related Guides to the Product](https://learn.adafruit.com/products/64/guides)
### 4 x AA Battery Holder with On/Off Switch

[4 x AA Battery Holder with On/Off Switch](https://www.adafruit.com/product/830)
Make a nice portable power pack with this 4 x AA battery holder. It fits any alkaline or rechargeable AA batteries in series. There's a snap on cover and an on/off switch which can be handy when wiring to something without a switch.

**New**! We now have 0.1" headers...

In Stock
[Buy Now](https://www.adafruit.com/product/830)
[Related Guides to the Product](https://learn.adafruit.com/products/830/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

- [Introducing the Raspberry Pi 2 - Model B](https://learn.adafruit.com/introducing-the-raspberry-pi-2-model-b.md)
- [Current Limiting Stepper Driver with DRV8871](https://learn.adafruit.com/current-limiting-stepper-driver-with-drv8871.md)
- [Arm-based IoT Kit for Cloud IoT Core - Getting Started](https://learn.adafruit.com/raspberry-pi-3-and-sensor-kit-for-google-cloud-iot-core.md)
- [10" Raspberry Pi Desktop](https://learn.adafruit.com/10-raspberry-pi-desktop.md)
- [CRICKIT WobblyBot](https://learn.adafruit.com/crickit-wobblybot.md)
- [Adafruit's Raspberry Pi Lesson 7. Remote Control with VNC](https://learn.adafruit.com/adafruit-raspberry-pi-lesson-7-remote-control-with-vnc.md)
- [Pi Video Output Using pygame](https://learn.adafruit.com/pi-video-output-using-pygame.md)
- [NeoPixels on Raspberry Pi](https://learn.adafruit.com/neopixels-on-raspberry-pi.md)
- [Trellis Python Library](https://learn.adafruit.com/trellis-python-library.md)
- [Adafruit's Raspberry Pi Lesson 12. Sensing Movement](https://learn.adafruit.com/adafruits-raspberry-pi-lesson-12-sensing-movement.md)
- [Echo 2-XL](https://learn.adafruit.com/echo-2-xl.md)
- [Improve the Low Speed of Brushed DC Motors](https://learn.adafruit.com/improve-low-speed-performance-of-brushed-dc-motors.md)
- [Adafruit GPS Hat in Windows IoT Core](https://learn.adafruit.com/adafruit-gps-hat-in-windows-iot-core.md)
- [Cupcade: the Raspberry Pi Micro Arcade Cabinet](https://learn.adafruit.com/cupcade-raspberry-pi-micro-mini-arcade-game-cabinet.md)
- [Unicorn Hat with Moving Ears](https://learn.adafruit.com/unicorn-hat-with-moving-ears.md)
