We use button press detection to know when someone presses a physical button connected to the Raspberry Pi. This helps the Pi react to user actions.
0
0
Button press detection in Raspberry Pi
Introduction
You want to turn on an LED when a button is pressed.
You want to start or stop a program by pressing a button.
You want to count how many times a button is pressed.
You want to control a robot or device with button presses.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO import time button_pin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: if GPIO.input(button_pin) == GPIO.LOW: print("Button pressed") time.sleep(0.2) # debounce delay
Use GPIO.setup() to set the button pin as input with a pull-up resistor.
Button press is detected when the input reads GPIO.LOW because the button connects the pin to ground.
Examples
Check once if the button is pressed.
Raspberry Pi
import RPi.GPIO as GPIO button_pin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) if GPIO.input(button_pin) == GPIO.LOW: print("Button is pressed")
Keep checking the button in a loop and print when pressed.
Raspberry Pi
import RPi.GPIO as GPIO import time button_pin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: if GPIO.input(button_pin) == GPIO.LOW: print("Button pressed") time.sleep(0.3) # wait to avoid multiple prints
Sample Program
This program waits for the button press and prints a message each time you press it. It cleans up the GPIO pins when you stop the program.
Raspberry Pi
import RPi.GPIO as GPIO import time button_pin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) print("Press the button...") try: while True: if GPIO.input(button_pin) == GPIO.LOW: print("Button pressed!") time.sleep(0.5) # debounce delay except KeyboardInterrupt: print("Program stopped") finally: GPIO.cleanup()
OutputSuccess
Important Notes
Use GPIO.cleanup() to reset pins when done.
Adding a small delay after detecting a press helps avoid multiple detections from one press (called debounce).
Summary
Button press detection lets your Raspberry Pi respond to physical button presses.
Set the button pin as input with a pull-up resistor and check for GPIO.LOW to detect presses.
Use a loop and a small delay to detect presses continuously and avoid false triggers.