🛠 Premier script Python : LED + bouton réunis
Objectives
Write, make executable, and run a first Python 3 script that combines the two previous tutorials: the button turns on the LED. You will discover gpiozero (preinstalled on Raspberry Pi OS), BCM numbering, proper handling of Ctrl-C, and the role of the shebang.
Hardware
- Raspberry Pi 3 Model B+ type board running Raspberry Pi OS (gpiozero preinstalled)
- LED + 330 Ω resistor on GPIO17 (pin 11), button on GPIO27 (pin 13) to GND
- A text editor (nano) via SSH or locally
Complete code
#!/usr/bin/env python3
"""Bouton -> LED sur carte 40 broches (logique 3,3 V, pin <= 16 mA).
LED anode -> 330 ohm -> GPIO17 ; bouton -> GPIO27 -> GND."""
from gpiozero import LED, Button
from signal import signal, SIGINT, default_int_handler
led = LED(17) # numérotation BCM, comme pinout.xyz
button = Button(27, pull_up=True) # pull-up interne, appui vers GND
button.when_pressed = led.on # piloté par événement, pas de boucle active
button.when_released = led.off
signal(SIGINT, default_int_handler) # Ctrl-C nettoie l'état des broches
while True: # gpiozero fait tourner ses threads
pass
chmod +x bouton_led.py
./bouton_led.py # Ctrl-C pour quitter
Expected verification
While the script is running, pressing the button turns on the LED, releasing it turns it off — almost instantly (event-driven callback). After Ctrl-C, the LED turns off cleanly because gpiozero releases the pins. python3 -c "import gpiozero; print(gpiozero.__version__)" confirms the presence of the library.
Common errors
ModuleNotFoundError: gpiozero: minimal image without recommended packages —sudo apt install python3-gpiozero.- Forgetting
chmod +xor the shebang:./bouton_led.pyrefuses to run; launch withpython3 bouton_led.py. - LED stays on after Ctrl-C: the script was killed abruptly (SIGKILL); restart cleanly or turn it off via a new script.
- Wrong pin: gpiozero expects the BCM number (17, 27), not the physical pin number (11, 13).
- Wires not properly inserted into the 40-pin connector: the classic "it doesn't work" case — test the LED and button separately first.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython