pwm-servo.py

Raspberry Pi Pico · File : pwm-servo.py · Language : Python · Use case : Faire balayer un servo-moteur avec un signal PWM

The hobby servo sweeps 0 to 180° and back, driven at 50 Hz PWM by machine.PWM. The angle() helper converts degrees into a 0.5 to 2.5 ms pulse through duty_u16, the standard technique with no dedicated library.

Hardware

A Raspberry Pi Pico (RP2040 dual Cortex-M0+ @ 133 MHz) with MicroPython installed, powered over USB. 1 hobby servo (SG90 class, 3 wires: signal, +, -); external supply advised beyond a micro servo.

Wiring

Signal wire (orange) to GP16, + (red) to 5 V or external 5 V supply, - (brown) to common GND.

How it works

PWM(Pin) generates a 50 Hz square wave (20 ms period). duty_u16 sets the proportional pulse width: 0.5 ms = 0°, 1.5 ms = 90°, 2.5 ms = 180°.

Running it

Install MicroPython if needed (hold BOOTSEL, plug USB, drop the .uf2 file), then copy the script to the board drive or via Thonny. The script auto-starts when named main.py.

Variants

Drive the angle with a potentiometer on the ADC (GP26) for a follower arm, or store positions in an angle table.

pwm-servo.py

# Balayage 0-180 degres d'un servo d'angle avec machine.PWM.
from machine import Pin, PWM
import time

SERVO_PIN = 16
servo = PWM(Pin(SERVO_PIN))
servo.freq(50)  # periode 20 ms : standard des servos

def angle(a):
    # 0 degre = impulsion 0,5 ms ; 180 degres = 2,5 ms.
    # duty_u16 : 65535 = 100 % de la periode de 20 ms.
    ms = 0.5 + (a / 180.0) * 2.0
    servo.duty_u16(int(ms / 20.0 * 65535))

print("Balayage servo 0-180")
while True:
    for a in range(0, 181, 5):
        angle(a)
        time.sleep_ms(30)
    for a in range(180, -1, -5):
        angle(a)
        time.sleep_ms(30)

# Alimentation : pour un gros servo, utiliser une source 5 V
# externe en reliant les masses (GND commun avec la carte).

← Back to the board