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 adafruit_motor
which manages servos for you quite nicely! adafruit_motor
is a library so be sure to grab it from the library bundle if you have not yet! If you need help installing the library, check out the CircuitPython Libraries page.
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 pack. 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 A1 or A2 but you can use any PWM-capable pin.
Servo Code
Here's an example that will sweep a servo connected to pin A2 from 0 degrees to 180 degrees and back:
import time import board import pulseio from adafruit_motor import servo # create a PWMOut object on Pin A2. pwm = pulseio.PWMOut(board.A2, duty_cycle=2 ** 15, frequency=50) # Create a servo object, my_servo. my_servo = servo.Servo(pwm) while True: for angle in range(0, 180, 5): # 0 - 180 degrees, 5 degrees at a time. my_servo.angle = angle time.sleep(0.05) for angle in range(180, 0, -5): # 180 - 0 degrees, 5 degrees at a time. my_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 initialize the servo
object with a different min_pulse
and max_pulse
. For example:
servo = adafruit_motor.servo.Servo(pwm, min_pulse = 0.5, max_pulse = 2.5)
For more detailed information on using servos with CircuitPython, check out the CircuitPython section of the servo guide!