🛠 Premier script Python : LED + bouton réunis

Raspberry Pi 3 Model B+ (2018) — Board Sheet · debutant · Schéma : IMG-model-3b-plus-debutant-3-model3bp-premier-script-python.svg — LED sur GPIO17 avec résistance et bouton sur GPIO27 reliés à la carte, éditeur de script à l'écran

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials