🛠 Lire un bouton et afficher l'état dans la console

Orange Pi PC (Allwinner H3) · debutant · Schéma : IMG-orangepi-pc-debutant-2-opipc-bouton-console.svg — Bouton poussoir externe entre une broche GPIO et la masse avec résistance de pull-up, et le bouton d'alimentation SW4 (PL3) de l'Orange Pi PC, entrées d'un terminal console.

Objectives

Learn how to read a digital input on the Orange Pi PC: configure a pin as an input with an internal pull-up, detect button presses, and display each event in the console. You will use gpiomon (libgpiod) to wait for edges, and you will discover that the board already has a button: SW4, the power button, wired to PL3 (gpiochip1, r_pio) and active low.

Hardware

Complete Code

Bash script that monitors a button on a named pin (adjust the pin name to match your wiring):

#!/usr/bin/env bash
# bouton.sh — détection d'appui avec gpiomon (libgpiod)
set -euo pipefail

# Exemple avec le bouton d'alimentation SW4 = PL3 (chip r_pio, actif-low)
LINE="$(gpiofind PL3)"
echo "Surveillance de ${LINE} (Ctrl-C pour quitter)..."

# rising/falling : chaque front est affiché horodaté
gpiomon --num-events=0 --rising-edge "${LINE}" | while read -r _ _ event _; do
    echo "$(date '+%H:%M:%S') — SW4 relâché (${event})"
done

Equivalent Python version using python3-libgpiod:

#!/usr/bin/env python3
import gpiod, time
chip = gpiod.Chip("gpiochip0")
ligne = chip.get_line(15)          # PA15 réutilisé en entrée pour l'exo
ligne.request(consumer="bouton", type=gpiod.LINE_REQ_EV_RISING_EDGE,
              flags=gpiod.LINE_REQ_FLAG_BIAS_PULL_UP)
print("En attente de fronts montants...")
while True:
    evts = ligne.event_wait(sec=1)
    if evts:
        ligne.event_read
        print(time.strftime("%H:%M:%S"), "— appui détecté")

Expected Verification

Each press/release displays a timestamped line in the terminal. With the SW4 button, a long press also triggers shutdown (KEY_POWER): for this experiment, press briefly.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials