🛠 Allumer une LED avec un bouton poussoir sur le CM3
Objectives
Combine a GPIO input and output: read a push button and light up an LED while pressed, with mechanical bounce handling integrated into gpiozero. You will also learn about the role of the CM3's weak internal pulls (50-65 kΩ, datasheet RP-008161-DS §6), present on all pins except GPIO28/29/44/45.
Hardware
- CM3 on CMIO3, Raspberry Pi OS started, python3-gpiozero installed
- 1 push button between GPIO4 and GND (GPIO4 has a default pull-up)
- 1 LED + 330 Ω resistor between GPIO17 and GND
Complete code
#!/usr/bin/env python3
# bouton_led.py — bouton sur GPIO4 (vers GND), LED sur GPIO17
from gpiozero import Button, LED
from signal import pause
btn = Button(4, pull_up=True, bounce_time=0.05) # rebond ignoré 50 ms
led = LED(17)
btn.when_pressed = led.on
btn.when_released = led.off
pause # boucle d'événements gpiozero (gère le SIGINT)
python3 bouton_led.py
Expected verification
Pressing the button turns on the LED, releasing it turns it off, without parasitic flickering thanks to bounce_time. Ctrl-C terminates the program cleanly. Variant without wiring: placing a finger on GPIO4 sometimes triggers the input — a sign that the pin is indeed in a sensitive pull-up state.
Common errors
- Forgetting
bounce_time: the mechanical button bounces and triggers dozens of events per press. - Button on GPIO28/29/44/45 relying on the internal pull: these pins have no default pull, the input floats and the state is random — add an external pull-up resistor (10 kΩ to the bank's VREF).
- Short circuit when the button is pressed: here the current remains below 1 mA thanks to the internal pull, but never connect an output directly to GND in push-pull mode.
- Forgetting
pause: without an event loop, the script terminates immediately and the LED stops reacting.
Other tutorials for this board
Code examples for this board
clignotante.pyPythonbouton-gpio.pyPythoncapteur-i2c.shBashsurveillance-temperature.shBashcapteur-dht11.pyPythonservo-pwm-sysfs.shBash