Pi Servo Control

A servo allows precise control of the angular position of its shaft. Standard servos accept 4.6 to 6 volts.

Colour Description
Yellow/White Control signal
Red Positive power lead
Black/Brown Negative power lead

Control signal

This needs to be a pulse width modulation (PWM) square wave. The square wave needs to be 50 herts (so a pulse of every 0.2 seconds) The angle of the servo is controlled by the length of the positive pulse (duty cycle) The longer the pulse/period of the wave/duty cycle the larger the angle the servo will turn to and try hold itself at.

These values vary by servo but for the small cheap SG-90’s the degrees can be calculated as:

1
2
2% duty cycle = 0 degrees
12% duty cycle = 180 degrees

Servo Duty

Translating this to python code using the RPi.GPIO library

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import RPi.GPIO as GPIO
import time

# Set GPIO numbering mode
GPIO.setmode(GPIO.BOARD)
# There is another mode called `GPIO.BCM` for BCM pin numbering, not sure what this is?

# Set pin 11 as an output, and set servo1 as pin 11 as PWM
GPIO.setup(11,GPIO.OUT)

# Note 11 is the pi's pin, 50Hz pulse (analog servo), 300 would be for digital
servo = GPIO.PWM(11,50)

# Start PWM running, but with value of 0 (pulse off)
servo.start(0)

# duty is a percentage from 0 to 100 which allows for decimals like 3.33
# 2% = 0 degrees
# 7% = 90 degrees
# 12% = 180 degrees
# setting it then back to 0 stops the servo from jittering, just set `time.sleep(0.5)` before so you give the servo time to move to the position
duty = 2
servo.ChangeDutyCycle(duty)
servo.ChangeDutyCycle(0)

# Clean up
servo.stop()
GPIO.cleanup()

References