bouton-gpio.py

Raspberry Pi Compute Module 3+ (CM3+ / CM3+ Lite) · 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 3+ (BCM2837B0, 1 GB LPDDR4) on a Compute Module IO Board v3, powered at 5 V, running Raspberry Pi OS (Bullseye). 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 Bullseye: sudo apt install python3-gpiozero then python3 your_script.py. The CM3+ behaves like a Pi 3 B+; IO Board pins follow the BCM numbering.

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