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 required
A Compute Module 4 (BCM2711) on its Compute Module IO Board, powered by 5 V USB-C, running 64-bit Raspberry Pi OS (Bookworm). 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. On Bookworm: sudo apt install python3-gpiozero (libgpiod backend) then python3 your_script.py. GPIOs follow the BCM numbering of the 40-pin header.
Going further
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