🛠 Bouton poussoir et retour dans la console

Raspberry Pi 3 Model B+ (2018) — Board Sheet · debutant · Schéma : IMG-model-3b-plus-debutant-2-model3bp-bouton-console.svg — Bouton entre GPIO27 (broche 13) et GND (broche 9), résistance de pull-up interne, terminal affichant l'état

Objectives

Read a digital input: a push button wired to GND with an internal pull-up, and display the state in the console on each press. You will learn about inverted logic (press = low level), mechanical bounce, and simple polling in the shell.

Hardware

Complete Code

Wiring: pin 13 (GPIO27) → one leg of the button; other leg → pin 9 (GND). The internal pull-up keeps the line at 1 when idle.

#!/usr/bin/env bash
# bouton.sh — affiche un message à chaque appui (GPIO27, broche 13)
# Active le pull-up interne puis boucle sur la lecture de la ligne.
sudo gpioset --quiet --hold-period 0ms gpiochip0 27=0 2>/dev/null || true

echo "Appuyez sur le bouton (Ctrl-C pour quitter)..."
while true; do
    # gpiodetect/gpiget : lecture de la ligne ; 0 = bouton pressé (logique inversée)
    etat=$(sudo gpiget gpiochip0 27 2>/dev/null || echo 1)
    if [ "$etat" = "0" ]; then
        echo "Bouton pressé à $(date +%T)"
        sleep 0.3        # anti-rebond logiciel grossier
        while [ "$(sudo gpiget gpiochip0 27 2>/dev/null || echo 1)" = "0" ]; do
            sleep 0.05   # attend le relâchement
        done
    fi
    sleep 0.02
done

Expected Verification

Each press displays a line "Button pressed" with the time, only once per press despite mechanical bounce. When idle, the line reads 1 thanks to the internal pull-up; when pressed, it drops to 0.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials