Hobby servos turn to an angle you choose and hold it. They are the moving parts of robot arms, grippers, pan-tilt camera mounts and animatronics. A Pico can drive one directly with its built-in PWM hardware.
What you need
How a servo knows where to go
A servo reads a pulse every 20 milliseconds (50 times a second). The pulse width sets the angle: about 0.5ms is one end, 1.5ms is the centre, and about 2.5ms is the other end. The exact range varies a little between servos.
1. Wire it up
| Servo wire | Pico |
|---|---|
| Brown / black (ground) | GND (pin 38) |
| Red (power) | VBUS (pin 40, 5V from USB) |
| Orange / yellow (signal) | GP15 (pin 20) |
Set up MicroPython and Thonny as described in our NeoPixel tutorial.
2. Sweep code
import time
from machine import Pin, PWM
servo = PWM(Pin(15))
servo.freq(50)
MIN_US, MAX_US = 500, 2500 # adjust if your servo buzzes at the ends
def angle(deg):
deg = max(0, min(180, deg))
us = MIN_US + (MAX_US - MIN_US) * deg / 180
servo.duty_ns(int(us * 1000))
while True:
for a in range(0, 181, 2):
angle(a)
time.sleep(0.02)
for a in range(180, -1, -2):
angle(a)
time.sleep(0.02)
The horn sweeps back and forth. If the servo buzzes or strains at either end, narrow MIN_US and MAX_US slightly: it's being asked to go past its mechanical stop.
Powering more servos
One micro servo is fine on USB power. Several servos, or a larger one like the standard servo, can draw more current than USB can supply. Power them from a separate 5–6V supply and connect its ground to the Pico's ground. For many servos, a 16-channel servo HAT on a Raspberry Pi handles the timing and power for you.
Next steps
- Add a potentiometer to an ADC pin and make the servo follow the knob.
- Use two servos for a pan-tilt camera mount.
- Ready for a bigger build? Browse our robotics kits.