Raspberry Pi - Button

This tutorial instructs you how to use Raspberry Pi with button. In detail, we will learn:

The button is referred to as a pushbutton, tactile button or momentary switch. It is a fundamental component and is used in many Raspberry Pi projects. It is easy to use. However, it may be perplexing for beginners due to mechanical, physical aspects and how it is used. This tutorial simplifies it for beginners.

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Push Button
1×(Optional) Panel-mount Push Button
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you. We appreciate your support.

Overview of Button

When utilizing a button, beginners often encounter two common difficulties:

1. Floating input problem:.

  • Symptom: The value read from the input pin does not correspond to the state of the button press.
  • Cause: A pull-up or pull-down resistor is not in use on the input pin.
  • Solution: Use a pull-up or pull-down resistor, which will be covered in this tutorial..

2. Chattering phenomenon:.

  • Symptom: The Raspberry Pi code is detecting multiple button presses even when the button is pressed only once.
  • Cause: Mechanical and physical issues are causing the state of the button (or switch) to swiftly alternate between LOW and HIGH several times..
  • Solution: In order to solve this issue, the Raspberry Pi - Button - Debounce tutorial will demonstrate the use of debounce techniques.

For applications that demand exact press detection, this is a consideration that should be made.

※ NOTE THAT:

Do not confuse the button with the following:

The Button Pinout

There are various types of push buttons, which can be broadly categorized into two groups:

  • PCB-mount push button (suitable for mounting on a breadboard)
  • Panel-mount push button
Push button

A PCB-mount button typically has four pins.

Button pinout

Nevertheless, these pins are linked together internally in pairs. Consequently, we only need to utilize two of the four pins, which are not connected internally.

There are four methods of connecting to the button, two of which are symmetrical (refer to the image).

How To Use Button

? Why is it that we only utilize two pins of a button, when it has four pins?

⇒ To ensure that it remains securely in place on the PCB (printed circuit board) and can withstand any pressure applied.

A panel-mount button usually has two pins.

two-pin push button Pinout
image source: diyables.io

How It Works

  • When the button is not pressed, pin A and pin B are not linked.
  • However, when the button is pressed, pin A and pin B become connected.
How Button Works

Raspberry Pi - Button

One button's pin is connected to either VCC or GND. The other pin of the same button is linked to a Raspberry Pi pin. By checking the status of a Raspberry Pi pin set as an input, we can determine whether or not a button has been pressed.

Button State and Pressing State

The connection between the button and Raspberry Pi, as well as the configuration of the Raspberry Pi's pin, will determine the relationship between the button state and the pressing state.

There are two ways to use a button with Raspberry Pi:

  1. Connect one button's pin to VCC and the other to a Raspberry Pi's pin with a pull-down resistor
    • When the button is pressed, the Raspberry Pi's pin state will be HIGH. Otherwise, it will be LOW
    • An internal or external resistor can be used. The internal resistor is built into the Raspberry Pi, and can be set via code.
  • Connect one button's pin to GND and the other to a Raspberry Pi's pin with a pull-up resistor
    • When the button is pressed, the Raspberry Pi's pin state will be LOW. Otherwise, it will be HIGH
    • An internal or external resistor can be used. The internal resistor is built into the Raspberry Pi, and can be set via code.

    ※ NOTE THAT:

    When neither a pull-down nor a pull-up resistor is used, the input pin will enter a “floating” state when the button is not pressed, meaning that the state can be either HIGH or LOW (unstable) and will lead to incorrect detection.

    • The worst practice: initializes the Raspberry Pi pin as an input (by using pinMode(BUTTON_PIN, INPUT)) and does NOT use any external pull-down/pull-up resistor.
    • The best practice: initializes the Raspberry Pi pin as an internal pull-up input (by using pinMode(BUTTON_PIN, INPUT_PULLUP)). It does NOT need to use any external pull-down/pull-up resistor.

    For the convenience of newbies, this tutorial uses the most straightforward approach: setting up the Raspberry Pi pin as an internal pull-up input without the need of an external resistor. No need to worry about how to connect the pull-up/pull-down resistor. All that is required is to use the Raspberry Pi code.

    Wiring Diagram

    • Wiring Diagram between Raspberry Pi and PCB-mount button
    The wiring diagram between Raspberry Pi and Button

    This image is created using Fritzing. Click to enlarge image

    • Wiring Diagram between Raspberry Pi and panel-mount button
    The wiring diagram between Raspberry Pi and two-pin push button

    This image is created using Fritzing. Click to enlarge image

    How To Program For Button

    • Utilize the GPIO.setup() function to initialize the Raspberry Pi pin as an internal pull-up input. For instance, pin 16:
    GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    • Utilizes the GPIO.input() function to determine the state of the Raspberry Pi pin.
    button_state = GPIO.input(16)

    ※ NOTE THAT:

    Two common use cases are available:

    • The first: If the input state is HIGH, perform one action. If the input state is LOW, do the opposite.
    • The second: If the input state changes from LOW to HIGH (or HIGH to LOW), take some action.

    We select one of these depending on the application. For example, when using a button to control an LED:

    • If we want the LED to be ON when the button is pressed and OFF when the button is NOT pressed, we SHOULD use the first use case.
    • If we want the LED to be toggled between ON and OFF each time we press the button, we SHOULD use the second use case.

    Raspberry Pi Code - Reading the state of the button

    Detailed Instructions

    • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
    • Make sure your Raspberry Pi is connected to the same local network as your PC.
    • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
    • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
    • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
    • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
    sudo apt-get update sudo apt-get install python3-rpi.gpio
    • Create a Python script file button.py and add the following code:
    # This Raspberry Pi code was developed by newbiely.com # This Raspberry Pi code is made available for public use without any restriction # For comprehensive instructions and wiring diagrams, please visit: # https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-button import RPi.GPIO as GPIO import time # Define the GPIO pin connected to the button BUTTON_PIN = 16 # Set the GPIO mode to BCM GPIO.setmode(GPIO.BCM) # Initialize the pushbutton pin as an input with a pull-up resistor # The pull-up input pin will be HIGH when the switch is open and LOW when the switch is closed. GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) try: while True: # Read the state of the switch/button button_state = GPIO.input(BUTTON_PIN) # Print out the button's state print(button_state) # Small delay to avoid unnecessary printing time.sleep(0.1) except KeyboardInterrupt: print("\nExiting...") # Clean up GPIO settings GPIO.cleanup()
    • Save the file and run the Python script by executing the following command in the terminal:
    python3 button.py
    • Press and release the button multiple times.
    • Check out the output on the Serial Monitor.
    PuTTY - Raspberry Pi
    1 1 1 0 0 0 0 0 0 1 1 1

    1 is HIGH, 0 is LOW.

    The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

    Code Explanation

    Check out the line-by-line explanation contained in the comments of the source code!

    Raspberry Pi Code - Detecting button press events

    Detailed Instructions

    • Create a Python script file button_pressed.py and add the following code:
    # This Raspberry Pi code was developed by newbiely.com # This Raspberry Pi code is made available for public use without any restriction # For comprehensive instructions and wiring diagrams, please visit: # https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-button import RPi.GPIO as GPIO import time # Define the GPIO pin connected to the button BUTTON_PIN = 16 # Set the GPIO mode to BCM GPIO.setmode(GPIO.BCM) # Initialize the pushbutton pin as an input with a pull-up resistor # The pull-up input pin will be HIGH when the switch is open and LOW when the switch is closed. GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Variable to keep track of the previous button state prev_button_state = GPIO.input(BUTTON_PIN) try: while True: # Read the state of the switch/button button_state = GPIO.input(BUTTON_PIN) # Check if the button state has changed (press or release event) if button_state != prev_button_state: if button_state == GPIO.LOW: # Button is pressed print("The button is pressed!") else: # Button is released print("The button is released!") # Update the previous button state prev_button_state = button_state # Small delay to avoid unnecessary reading time.sleep(0.1) except KeyboardInterrupt: print("\nExiting...") # Clean up GPIO settings GPIO.cleanup()
    • Save the file and run the Python script by executing the following command in the terminal:
    python3 button_pressed.py
    • Press the button and hold it for a moment.
    • Check the output on the Serial Monitor.
    PuTTY - Raspberry Pi
    The button is pressed The button is released

    The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

    Code Explanation

    Check out the line-by-line explanation contained in the comments of the source code!

    ※ NOTE THAT:

    Even if you press and release the button only once, the output in Terminal may display multiple pressed and released events. This is the expected behaviour of the button. This phenomenon is referred to as “chattering”. To learn more about it, please refer to the Raspberry Pi - Button Debounce tutorial.

    Video Tutorial

    Challenge Yourself

    • When the button is pressed, the LED should be turned on.
    • When the button is not pressed, the LED should be turned off.
    • Each time the button is pressed, the LED should switch between ON and OFF.

    Additional Knowledge

    What are the occasions when a pull-down/pull-up resistor should and should not be used for an input pin?

    • If the sensor has either closed or open states, a pull-up or pull-down resistor is required to make these states become LOW and HIGH. Examples of such sensors are push-button, switch, and magnetic contact switch (door sensor).
    • On the other hand, if the sensor has two defined voltage levels (LOW and HIGH), a pull-up or pull-down resistor is NOT necessary. Examples of such sensors are motion sensor and touch sensor.

    ※ OUR MESSAGES

    • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
    • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!