🛠 Lire un bouton et afficher dans la console
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
- Raspberry Pi Model B Rev 2 with Raspbian legacy 32-bit
- Push button, breadboard, jumper wires
- Button between GPIO27 (P1-13) and GND; pull-up to 3.3 V enabled in software.
sudo apt install python-rpi.gpioon Raspbian legacy (python2 package).
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
- Forgetting
pull_up_down=GPIO.PUD_UP: the input floats and displays phantom presses. - Wiring the button to 3.3 V instead of GND: inverted state, internal pull-up that "jumps".
- On the very first boards, P1-13 carried the GPIO21 number; check with
gpioinfobefore rewiring. - Running without GPIO permissions on a recent image: use sudo or the gpio group.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython