Adafruit will not be shipping orders Monday January 16, 2017. Any orders placed after 11am EST Friday January 13 will go out Tuesday January 17.


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

sudo apt-get install -y wiringpi

Set pin #18 to be a PWM output

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!)

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

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

gpio -g pwm 18 100

Set the servo to the middle (1.5 ms) with

gpio -g pwm 18 150

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

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.

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:

# Servo Control
import time
import wiringpi

# use 'GPIO naming'

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

# set the PWM mode to milliseconds stype

# divide down clock

delay_period = 0.01

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

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:

$ nano

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

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

$ sudo python

The servo should start to move straight away.  

Last updated on 2016-10-29 at 12.56.59 AM Published on 2013-01-09 at 09.22.53 AM