Raspberry Pi – Push Button

In this course, we’ll look at how to read the value of a pushbutton on the Raspberry Pi. This can be very useful for interacting with the user.

Here’s the diagram to connect the push button to the Raspberry Pi:

We’ve added a pull-down resistor so that when the push-button is not pressed, the board reads a low state and there are no undefined states.

Programming

Here is the program to read the values coming from the push button:

import RPi.GPIO as GPIO
import time

# Pin configuration
button_pin = 17

# Initial GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

try:
    print(“Wait until the button is pressed...”)

    while True:
        if GPIO.input(button_pin) == GPIO.LOW:
            print(“Button pressed!”)
            time.sleep(0.2) # Debouncing, wait a short time to avoid button bouncing
            while GPIO.input(button_pin) == GPIO.LOW:
                time.sleep(0.1) # Wait for button to be released
        time.sleep(0.1)

except KeyboardInterrupt:
    pass

finally:
    # Clean GPIO resources
    GPIO.cleanup()