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

Raspberry Pi Model B (Rev 1, 2012) — Board Sheet · debutant · Schéma : IMG-model-b-rev1-debutant-2-modelb1-bouton-console.svg — Bouton poussoir entre GPIO4 (broche 7) et GND (broche 9), résistance de pull interne activée, terminal affichant l'état lu

Objectives

Learn how to read a digital input on the 26-pin P1 connector of the Model B Rev 1: a push button connected to ground, with the internal pull-up resistor of the BCM2835 enabled via libgpiod. You will monitor the button state in a loop in the console.

Hardware

Complete code

#!/bin/sh
# bouton.sh - surveille un bouton sur GPIO4 (broche physique 7)
# c'est la broche 7, GND est la broche 9.
# Rappel interne : GPIO4 possède un pull-up interne activable.

# Lecture en boucle : gpiomon attend les changements d'état
gpiomon --num-events=0 --rising-edge gpiochip0 4 &
while true; do
  ETAT=$(gpioget --bypass-direction-check gpiochip0 4 2>/dev/null || gpioget gpiochip0 4)
  if [ "$ETAT" = "0" ]; then
    echo "BOUTON APPUYE (etat bas = 0, pull-up interne)"
  else
    echo "au repos (1)"
  fi
  sleep 0.1
done

Expected verification

At rest, the console displays au repos (1) thanks to the internal pull-up. Each time the button is pressed, the GPIO is connected to ground and the state changes to 0: the console displays BOUTON APPUYE. The button is wired between pin 7 (GPIO4) and pin 9 (GND).

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials