🛠 Bouton poussoir et messages dans la console

Raspberry Pi 2 Model B (2015) — Board Sheet · debutant · Schéma : IMG-model-2b-debutant-1-model2b-bouton-console.svg — bouton poussoir entre GPIO4 et masse avec résistance de pull-up interne, terminal affichant les appuis

Objectives

Read a logical state on a GPIO input and react in the console. You will wire a push button, enable the internal pull-up resistor to avoid an external component, then poll the pin in a loop to display a message on each press.

Hardware

Complete code

#!/bin/bash
# bouton.sh — surveille GPIO4 (actif au niveau bas, pull-up interne)
CHIP=gpiochip0
while true; do
  etat=$(sudo gpioget --pull-up $CHIP 4)
  if [ "$etat" = "0" ]; then
    echo "$(date +%T) : bouton appuye !"
    while [ "$(sudo gpioget --pull-up $CHIP 4)" = "0" ]; do sleep 0.05; done
    echo "$(date +%T) : bouton relache"
  fi
  sleep 0.05
done

Save as bouton.sh, then run: chmod +x bouton.sh && ./bouton.sh

Expected verification

Each press displays a timestamped line "button pressed!" followed by "button released" upon release. Without any press, the loop remains silent. Stop with Ctrl+C.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials