bouton-gpio.py
A button on the GPIO header triggers an action on press and release. gpiozero provides when_pressed/when_released callbacks with built-in debounce and event-driven pause().
Hardware
A Raspberry Pi Zero W (BCM2835, 512 MB) running Raspberry Pi OS, with 2.4 GHz Wi-Fi and Bluetooth. 1 push button (one leg to the GPIO pin, the other to GND).
Wiring
Button between physical pin 7 (GPIO4) and GND; the pull-up resistor is internal (pull_up=True).
How it works
The pin level is watched; a valid edge (stable for 30 ms) runs the action. gpiozero delegates everything to asynchronous callbacks.
Running it
Copy the script (scp), chmod +x, run. Recent Raspberry Pi OS: GPIO access works without sudo (gpio group).
Variants
Press counter, double-click (interval measurement), or triggering a shell script via subprocess.
bouton-gpio.py
#!/usr/bin/env python3
# Bouton poussoir avec gpiozero : reaction sur appui et relachement.
from gpiozero import Button, LED
from signal import pause
bouton = Button(4, pull_up=True, bounce_time=0.05) # GPIO4, broche 7
led = LED(17)
def sur_appui():
print("Appui !")
led.on()
def sur_relachement():
print("Relache.")
led.off()
bouton.when_pressed = sur_appui
bouton.when_released = sur_relachement
print("Pret : Ctrl-C pour quitter")
pause() # laisse tourner les callbacks en tache de fond