bouton-gpio.py

Hardkernel ODROID-XU4 (Samsung Exynos5422) · 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. Generic version that polls the gpiod line directly, with a 30 ms software debounce filter.

Hardware

An ODROID-XU4 (Samsung Exynos5422, 4 Cortex-A15 + 4 Cortex-A7, 2 GB) running Ubuntu Hardkernel or Armbian, with gigabit Ethernet and an eMMC port. 1 push button (one leg to the GPIO pin, the other to GND).

Wiring

Button between the chosen GPIO and GND; enable the internal pull via the gpiod flag if the circuit has no resistor.

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

On Ubuntu Hardkernel or Armbian: apt install gpiod python3-gpiod; the 40-pin header shows up in gpiodetect (gpiochip0/1 chips on Exynos), check pins with gpioinfo.

Variants

Press counter, double-click (interval measurement), or triggering a shell script via subprocess.

bouton-gpio.py

#!/usr/bin/env python3
# Bouton poussoir avec python3-gpiod : scrutation + anti-rebond.
import gpiod
from time import sleep

PUCE = "gpiochip1"   # verifier avec gpiodetect
LIGNE = 16           # GPIO du bouton (schema de la carte)

chip = gpiod.Chip(PUCE)
line = chip.get_line(LIGNE)
line.request(consumer="bouton", type=gpiod.LINE_REQ_DIR_IN,
             default_val=gpiod.LINE_REQ_FLAG_NONE)

print("Scrutation du bouton (Ctrl-C pour quitter)")
precedent = line.get_value()
try:
    while True:
        etat = line.get_value()
        if etat != precedent:
            sleep(0.03)                      # anti-rebond 30 ms
            etat = line.get_value()
            if etat != precedent:
                print("Bouton:", "APPUIE" if etat else "relache")
                precedent = etat
        sleep(0.01)
finally:
    line.release()

← Back to the board