🛠 Lire un bouton et afficher dans la console

Raspberry Pi 3 Model B (model-3b) · debutant · Schéma : IMG-model-3b-debutant-2-model3b-bouton-console.svg — bouton-poussoir entre GPIO4 (broche 7) et GND (broche 6), résistance de pull-up interne activée, sortie texte sur la console

Objectives

Read the state of a push button on the Raspberry Pi 3 Model B GPIO and display a message in the console on each press. Learn how to enable the internal pull-up resistor (the button is wired to GND, active-low logic) and how to avoid mechanical bouncing with a software delay.

Hardware

Complete code

The button is wired between physical pin 7 (GPIO4) and physical pin 6 (GND). The internal pull-up keeps the input at 1 when idle; pressing the button brings it to 0:

#!/usr/bin/env bash
# bouton.sh — surveille GPIO4 (broche physique 7), bouton vers GND
# requis : libgpiod-utils (gpiodetect, gpioget)

echo "Surveillance GPIO4 — Ctrl-C pour quitter"

while true; do
  etat=$(gpioget --numeric gpiochip0 4)
  if [ "$etat" = 0 ]; then
    echo "$(date +%T) : bouton appuyé !"
    sleep 0.3   # anti-rebond logiciel
  fi
  sleep 0.05
done

Save as bouton.sh, then run chmod +x bouton.sh and ./bouton.sh. Python alternative: from gpiozero import Button; b = Button(4, pull_up=True) then b.wait_for_press — gpiozero is preinstalled on Raspberry Pi OS.

Expected verification

When idle, gpioget gpiochip0 4 returns 1 (internal pull-up). On each button press held down, the console displays a timestamped line "button pressed!". Upon release, the state returns to 1. Without the pull-up enabled, the input floats and displays random states — this is the best test to understand their usefulness.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials