← MicroPython on Pi Pico and Projects

Project 2.1

Project 2.1: Moving a Servo

PWM for position instead of brightness, and a reusable servo.py

This is for after leds.py from Project 1 is working, signed off, and no longer needed for today. A servo is a new breadboard, a new component, and the first time PWM means something other than brightness.

Wire the servo

A servo has three wires, not two: signal, power, and ground. Check yours against its documentation if the colors differ from what’s below, servo wire colors aren’t fully standardized.

  1. Ground wire to your spare ground rail from Project 1.1, physical pin 18. You never needed it for the LED circuit; this is what it was wired and ready for.
  2. Power wire to VBUS, physical pin 40, not 3V3. VBUS is the Pico’s own 5V, the same 5V your USB cable supplies, and a servo wants more voltage and current than the 3V3 rail reliably provides.
  3. Signal wire to GP16, physical pin 21.

Set up PWM on the servo

from machine import Pin, PWM

servo = PWM(Pin(16))
servo.freq(50)

Only 50 times a second, much slower than the LED’s 1000. A servo doesn’t care about flicker, it reads the width of each pulse, not how fast they repeat, and 50 Hz (a 20-millisecond period) is the standard RC servo rate.

Duty cycle means angle now, not brightness

duty_u16() still sets a fraction of each cycle, the same function from Project 1.5, but a servo reads that timing completely differently: the width of the on pulse tells the motor what angle to turn to, not how bright to glow. Try these three in the REPL, one at a time, and watch the servo’s position change instead of its brightness:

servo.duty_u16(3277)
servo.duty_u16(4915)
servo.duty_u16(6554)

These are roughly 0°, 90°, and 180°, a 1, 1.5, and 2 millisecond pulse out of the 20-millisecond cycle. “Roughly” is doing real work in that sentence: exact endpoints vary by servo model, so don’t worry if yours stalls or buzzes right at the extreme ends. Pull back toward center if it does.

Turning any angle into a duty cycle

Once your servo sweeps back and forth on its own, you’re done with it for a little while. Project 2.2 picks up the potentiometer on its own terms, and a joystick brings the servo back a few projects later.