bouton-gpio.py

Raspberry Pi Compute Module 5 (compute-module-5) · File : bouton-gpio.py · Language : Python · Use case : Réagir à l'appui sur un bouton poussoir

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 5 (BCM2712 + RP1) on a CM5 IO Board, powered by 5 V USB-C (up to 25 W over PD), running 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 then python3 your_script.py. The connector 28 GPIOs reuse the Pi 5 BCM numbering; the module adds a PWR_BUT button and an RTC (VBAT).

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

← Back to the board