🛠 Bouton poussoir et messages dans la console
Objectives
Wire a push button, understand the internal pull-up, and display a message in the console on each press. You will write two versions: polling and event-driven, the latter being the method recommended by the official gpiozero documentation.
Materials
- Raspberry Pi 4B, breadboard, Dupont cables
- 1 push button, 1 LED, 2 330-ohm resistors
- python3-gpiozero (pre-installed on the desktop, otherwise
sudo apt install python3-gpiozero)
Complete Code
#!/usr/bin/env python3
# bouton.py - GPIO17 (broche 11) -> 330R -> LED -> GND ; GPIO27 (broche 13) <- bouton <- GND
from gpiozero import LED, Button
from signal import pause
led = LED(17) # sortie active a l'etat haut
btn = Button(27, pull_up=True) # pull-up interne, appui actif a l'etat bas
while True:
if btn.is_pressed:
print("Bouton appuye !")
led.on
else:
led.off
# Version evenementielle recommandee :
# btn.when_pressed = led.on
# btn.when_released = led.off
# pause
Expected Verification
Run python3 bouton.py then press the button: the message "Bouton appuye !" is displayed and the LED lights up; it turns off when released. Ctrl+C terminates the script cleanly.
Common Errors
- Forgetting the pull-up (internal or 10 kOhm external): the input floats and displays phantom presses.
- Wiring the button to 3.3 V instead of GND: with the pull-up active, the button must connect to GND when pressed.
- Missing
pull_up=Truein the code while the wiring assumes an external pull-up. - Tight polling loop that consumes an entire CPU core: prefer
when_pressedandpause. - Confusion between physical/BCM pin numbering: pin 13 = GPIO27, pin 11 = GPIO17.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython