🛠 Bouton poussoir et retour console avec gpiozero
Objectives
Read a push button and control an LED from Python using gpiozero on the Raspberry Pi 3 A+: when_pressed / when_released events, internal pull-up, event loop. gpiozero numbers pins in Broadcom format, just like libgpiod.
Hardware
- Raspberry Pi 3 A+ running Raspberry Pi OS Bookworm, accessed via SSH (no Ethernet: network via WiFi or micro-USB cable in gadget mode)
- Push button, LED + 330 Ω resistor
- Button: GPIO27 (pin 13) to GND (pin 20); LED + 330 Ω: GPIO17 (pin 11) to GND (pin 14)
Complete Code
#!/usr/bin/env python3
# blink_btn.py — sudo apt install python3-gpiozero
from gpiozero import LED, Button # numérotation Broadcom
from signal import pause
led = LED(17) # GPIO17 = broche physique 11
btn = Button(27, pull_up=True) # GPIO27 = broche 13, repos à l'état haut
def on_press:
print("Bouton pressé — la LED clignote")
led.blink(on_time=0.2, off_time=0.2)
def on_release:
print("Bouton relâché — LED éteinte")
led.off
btn.when_pressed = on_press
btn.when_released = on_release
print("3A+ prêt (4x Cortex-A53 @ 1,4 GHz) — appuyez sur le bouton")
pause # garde la boucle d'événements alive
sudo apt install -y python3-gpiozero
python3 blink_btn.py
Expected Verification
The console displays "3A+ ready"; each time the button is pressed, the LED starts blinking and a message is displayed; when released, the LED turns off. Ctrl+C exits cleanly.
Common Errors
- Wiring the button to 3.3 V instead of GND without understanding pull-ups: with
pull_up=True, the idle state is high and pressing the button results in a low state. - Forgetting
pause: the script terminates immediately and the button never responds. - Connecting GPIO27 directly to 5 V: the 3 A+ logic operates at 3.3 V, and 5 V can damage the SoC.
- Confusing pin 13 (GPIO27) and pin 11 (GPIO17) on the 40-pin connector.
Other tutorials for this board
- Allumer une LED en C avec libgpiod sur le GPIO 40 broches
- Premier script Python : inventaire du système
- Variation d'intensité d'une LED avec le PWM matériel
- Capteur I2C : température et pression avec BME280
- Connexion WiFi station et administration en SSH
- Démarrage SD/USB et récupération d'une carte qui ne boot plus
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython