🛠 GPIO en Python : LED et bouton avec gpiozero

Raspberry Pi Zero 2 W (2021) — Board Sheet · intermediaire · Schéma : IMG-zero-2w-intermediaire-1-led-bouton-gpiozero.svg — connecteur 40 broches de la Zero 2 W, LED + 330 Ω sur la broche physique 11 (GPIO17), bouton sur la broche 13 (GPIO27) vers GND.

Objectives

Control the 40-pin HAT-compatible connector on the Zero 2 W: 3.3 V logic (careful, not 5 V!), Broadcom numbering (GPIO17 = physical pin 11), inputs with internal pull-up, and the event-driven model of gpiozero — preinstalled on Raspberry Pi OS — which avoids blocking polling. Current constraints to remember: 16 mA per pin, 50 mA TOTAL across all pins.

Hardware

Complete code

#!/usr/bin/env python3
"""LED sur GPIO17, compteur d'appuis sur bouton GPIO27 (gpiozero).
Rappel : 16 mA max par broche, 50 mA au total sur toutes les broches."""
from gpiozero import LED, Button
from signal import signal, SIGINT, default_int_handler

led = LED(17)                       # numérotation BCM, pas numéro de broche !
button = Button(27, pull_up=True)   # au repos = HIGH ; appuyé = relié à GND

presses = 0
def on_press(_):
    global presses
    presses += 1
    print(f"Bouton appuyé {presses} fois")

button.when_pressed = on_press      # événementiel, pas de boucle de polling

signal(SIGINT, default_int_handler) # Ctrl-C propre au lieu de rester bloqué
try:
    led.blink(on_time=0.5, off_time=0.5)   # non bloquant : thread en arrière-plan
    while True:
        pass
finally:
    led.close                     # remet la broche à 0 à la sortie

Execution: python3 bouton.py, stop with Ctrl-C. To start it at boot: a simple systemd service with ExecStart=/usr/bin/python3 /home/pi/bouton.py.

Expected verification

The LED blinks at 1 Hz upon launch; each press displays a counter in the terminal. After Ctrl-C, the LED turns off (the pin is properly released by led.close). If nothing blinks, first check the physical pin / GPIO number inversion.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials