servo_sweep.py

Raspberry Pi 3 Model B (model-3b) · Fichier : servo_sweep.py · Langage : Python · Usage : Piloter un micro-servo (bras robotisé, caméra orientable) en PWM 50 Hz

Un micro-servo de type SG90 est piloté en PWM 50 Hz sur GPIO18 (broche 12) via PWMOutputDevice de gpiozero : value=0 correspond à 0°, value=1 à 180°. Le script balaie en continu d'un bord à l'autre. Attention à l'alimentation du servo, surtout si la carte est déjà limitée en courant.

Matériel requis

Une Raspberry Pi 3 Model B (BCM2837 quad-core 1,2 GHz, Wi-Fi 2,4/5 GHz + Bluetooth 4.1, 4 ports USB, GPIO 40 broches). Un micro-servo SG90 (ou similaire), alimentation externe 5 V conseillée, fils dupont.

Câblage

Signal orange/jaune sur GPIO18 (broche 12), brun ou rouge sur 5 V, noir ou jaune sur GND commune avec la carte.

Fonctionnement

PWMOutputDevice génère un train d'impulsions 50 Hz, largeur 0,5–2,5 ms ; le servo positionne son axe selon la largeur d'impulsion.

Exécution

Copiez le script sur la carte (scp), puis lancez-le avec python3 (ou bash). Raspberry Pi OS inclut gpiozero ; sinon sudo apt install python3-gpiozero. Le brochage 40 broches est documenté sur le site officiel Raspberry Pi.

Variantes

Servo(angle) de gpiozero pour une API en degrés ; deux servos pour un ''plateau XY''. Wi-Fi 2,4 GHz intégré : pensez à configurer wpa_supplicant ou Raspberry Pi Imager ; 5 V/2,5 A conseillée.

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")

← Retour à la fiche