🛠 Lire un bouton et afficher dans la console

Raspberry Pi Model B Revision 2 (2012) — Board Sheet · debutant · Schéma : IMG-model-b-rev2-debutant-2-modelb2-bouton-console.svg — Bouton poussoir sur GPIO27 (P1-13) vers GND avec résistance de rappel interne, terminal console à l'écran

Objectives

Wire a push button on the Model B Rev 2, read its state from Python, and display a message in the console on each press, relying on the BCM2835's internal pull-up resistor.

Hardware

Full Code

#!/usr/bin/env python
# bouton.py - bouton sur GPIO27 (P1-13) vers GND, rappel interne haut
import RPi.GPIO as GPIO
import time

BTN = 27
GPIO.setmode(GPIO.BCM)
GPIO.setup(BTN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
print("Appuie sur le bouton (Ctrl-C pour quitter)")
try:
    while True:
        if GPIO.input(BTN) == GPIO.LOW:
            print("Bouton appuye !")
            time.sleep(0.3)          # anti-rebond logiciel
        time.sleep(0.02)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup

Expected Verification

python bouton.py displays a message on each press, without any external hardware other than the button. On Ctrl-C, the script terminates cleanly and releases the pin.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials