# CircuitPython Servo

In order to use servos, we take advantage of pulseio. Now, in theory, you could just use the raw pulseio calls to set the frequency to 50 Hz and then set the pulse widths. But we would rather make it a little more elegant and easy!

So, instead we will use simpleio which manages servos for you quite nicely! simpleio is a library so be sure to grab it from the library bundle if you have not yet!

If you are using a non-Express (Gemma, Trinket, Adalogger...) you must be running CircuitPython 2.1+ to get PWM support

# Wiring

Servos will only work on PWM-capable pins! Check your board details to verify which pins have PWM/Timer outputs

Connect the servo's brown or black ground wire to ground on the CircuitPython board.

Connect the servo's red power wire to 5V power, USB power is good for a servo or two. For more than that, you'll need an external battery back. Do not use 3.3V for powering a servo!

Connect the servo's yellow or white signal wire to the control/data pin, in this case D2 but you can pin any PWM-capable pin.

Here's an example that will sweep a servo connected to pin D2 from 0 degrees to 180 degrees and back

import time
import board
import simpleio

servo = simpleio.Servo(board.D2)

# sweep back and forth!
while True:
for angle in range (0, 180, 5): # 0-180 degrees, 5 degrees at a time
servo.angle = angle
time.sleep(0.05)
for angle in range (180, 0, -5): # 180-0 degrees, 5 degrees at a time
servo.angle = angle
time.sleep(0.05)

Pretty simple!

Note that we assume that 0 degrees is 0.5ms and 180 degrees is a pulse width of 2.5ms. That's a bit wider than the official 1-2ms pulse widths. If you have a servo that has a different range you can just initialize the Servo object with a different min/max pulse:

servo = simpleio.Servo(board.D2, min_pulse = 0.5, max_pulse = 2.5):

You can have a servo on each pin that has a timer. Note that the timer gets set to 50 Hz so if you want a PWM with a different frequency have it on a pin that isn't the same timer (check the CircuitPython PWM page for more details on timers)

Last updated on 2017-12-01 at 04.59.09 PM Published on 2017-07-26 at 06.08.30 PM