servo_sweep.py

Raspberry Pi 5 (model-5) · File : servo_sweep.py · Language : Python · Use case : Piloter un micro-servo (bras robotisé, caméra orientable) en PWM 50 Hz

An SG90-class servo is driven with 50 Hz PWM on GPIO18 (pin 12) via gpiozero PWMOutputDevice: value=0 means 0 degrees, value=1 means 180. The script sweeps continuously. Mind the power budget: puce I/O RP1, USB-C 5 V/5 A (27 W), deux ports CSI, connecteur JST pour caméra/ventilateur; power servos separately beyond two.

Hardware

A Raspberry Pi 5 (quad-core BCM2712 at 2.4 GHz, RP1 I/O chip, 40-pin GPIO, recommended 5 V/5 A USB-C power, two CSI camera ports). One SG90 micro-servo (or similar), an external 5 V supply recommended, dupont wires.

Wiring

Orange/yellow signal wire to GPIO18 (pin 12), brown/red to 5 V, black/yellow to GND shared with the board.

How it works

PWMOutputDevice emits a 50 Hz pulse train, 0.5–2.5 ms wide; the servo angles its horn with the pulse width.

Running it

Copy the script to the board (scp), then run it with python3. On Bookworm, gpiozero 2.x drives the pins through the RP1 chip; keep gpiozero and python3-rpi.gpio updated (sudo apt full-upgrade). A 5 V/5 A supply is advised.

Variants

Use gpiozero Servo(angle) for a degree API; two servos make an XY tracker. A 27 W (5 V/5 A) supply is recommended; without it USB output is capped at 600 mA total.

servo_sweep.py

# servo_sweep.py — balaie un micro-servo (SG90) de 0 a 180 degres.
# Deps: sudo apt install python3-gpiozero
from gpiozero import PWMOutputDevice
from time import sleep

servo = PWMOutputDevice(18, frequency=50, pulse_width=0.001)

print("Balayage servo, Ctrl+C pour sortir")
try:
    while True:
        for deg in range(0, 181, 15):
            servo.value = deg / 180.0
            sleep(0.05)
        for deg in range(180, -1, -15):
            servo.value = deg / 180.0
            sleep(0.05)
except KeyboardInterrupt:
    servo.off()
    print("Arret")

← Back to the board