Raspberry Pi - Button - Long Press Short Press

This tutorial instructs you how to use Raspberry Pi to delect the button's long press and short press. To make it simple, we will break it down into the following examples:

In the final section, we will explore how to utilize debounce in a practical setting. For further information on why debouncing is necessary for buttons, please refer to this article. Without debouncing, it is possible to incorrectly detect a short press of the button.

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Breadboard-mount Button with Cap
1×Breadboard-mount Button Kit
1×Panel-mount Push Button
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) Power Adapter for Raspberry Pi 4B
1×(Optional) Plastic Case for Raspberry Pi 4B

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.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Button

If you are unfamiliar with buttons (including pinouts, how they operate, and how to program them), the following tutorials can provide guidance:

Wiring Diagram

The wiring diagram between Raspberry Pi and Button

This image is created using Fritzing. Click to enlarge image

In this tutorial, we will make use of the internal pull-up resistor. As a result, when the button is not pressed, its state is HIGH, and when it is pressed, its state is LOW.

How To Detect Short Press

We calculate the amount of time between the pressed and released events. If the period is less than a predetermined time, we detect a short press event.

Specify the duration of a short press.

SHORT_PRESS_TIME = 0.5 # 500 milliseconds
  • Detect if the button has been pressed and record the time of the press.
if prev_button_state == GPIO.HIGH and button_state == GPIO.LOW: # Button is pressed press_time_start = time.time()
  • Determine when the button has been released and record the time of release.
if prev_button_state == GPIO.LOW and button_state == GPIO.HIGH: # Button is released press_time_end = time.time()
  • Determine the press duration.
press_duration = press_time_end - press_time_start
  • Compare the press duration to the defined short press time to identify a short press.
if press_duration < SHORT_PRESS_TIME: print("A short press is detected")

Raspberry Pi Code for detecting the short press

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 short_press.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-long-press-short-press """ import RPi.GPIO as GPIO import time BUTTON_PIN = 16 SHORT_PRESS_TIME = 0.5 # 500 milliseconds DEBOUNCE_TIME = 0.1 # 100 milliseconds # Variables will change: prev_button_state = GPIO.LOW # the previous state from the input pin button_state = None # the current reading from the input pin press_time_start = 0 press_time_end = 0 # Set up GPIO and configure the pull-up resistor GPIO.setmode(GPIO.BCM) 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) # Perform debounce by waiting for DEBOUNCE_TIME time.sleep(DEBOUNCE_TIME) if prev_button_state == GPIO.HIGH and button_state == GPIO.LOW: # Button is pressed press_time_start = time.time() elif prev_button_state == GPIO.LOW and button_state == GPIO.HIGH: # Button is released press_time_end = time.time() press_duration = press_time_end - press_time_start if press_duration < SHORT_PRESS_TIME: print("A short press is detected") # Save the last state prev_button_state = button_state except KeyboardInterrupt: print("\nExiting the program.") GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 short_press.py
  • Press the button briefly multiple times.
  • Check out the outcome in the Terminal.
PuTTY - Raspberry Pi
A short press is detected A short press is detected A short press is detected

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

How To Detect Long Press

There are two scenarios for recognizing a long press:

  • The long-press event is identified immediately after the button is released
  • The long-press event is identified while the button is being held down, even before it is released.

In the first scenario, the duration between the pressed and released events is calculated. If this duration exceeds a predetermined amount of time, then a long-press event is identified.

In the second scenario, when the button is pressed, the pressing duration is continuously checked until the button is released. As the button is held down, if the duration exceeds a predetermined amount of time, the long-press event is detected.

Raspberry Pi Code for detecting long press when released

Detailed Instructions

  • Create a Python script file long_press_1.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-long-press-short-press """ import RPi.GPIO as GPIO import time BUTTON_PIN = 16 LONG_PRESS_TIME = 1.0 # 1 seconds DEBOUNCE_TIME = 0.1 # 100 milliseconds # Variables will change: prev_button_state = GPIO.LOW # the previous state from the input pin button_state = None # the current reading from the input pin press_time_start = 0 press_time_end = 0 # Set up GPIO and configure the pull-up resistor GPIO.setmode(GPIO.BCM) 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) # Perform debounce by waiting for DEBOUNCE_TIME time.sleep(DEBOUNCE_TIME) if prev_button_state == GPIO.HIGH and button_state == GPIO.LOW: # Button is pressed press_time_start = time.time() elif prev_button_state == GPIO.LOW and button_state == GPIO.HIGH: # Button is released press_time_end = time.time() press_duration = press_time_end - press_time_start if press_duration >= LONG_PRESS_TIME: print("A long press is detected") # Save the last state prev_button_state = button_state except KeyboardInterrupt: print("\nExiting the program.") GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 long_press_1.py
  • Press the button during 2 seconds and then release the button.
  • Check the result on the Terminal.
PuTTY - Raspberry Pi
A long press is detected

The event of long-pressing is only identified when the button is released.

Raspberry Pi Code for detecting long press during pressing

Detailed Instructions

  • Create a Python script file long_press_2.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-long-press-short-press """ import RPi.GPIO as GPIO import time BUTTON_PIN = 16 LONG_PRESS_TIME = 1.0 # 1000 milliseconds (1 second) # Variables will change: prev_button_state = GPIO.LOW # the previous state from the input pin button_state = None # the current reading from the input pin press_time_start = 0 is_pressing = False is_long_detected = False # Set up GPIO and configure the pull-up resistor GPIO.setmode(GPIO.BCM) 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) if prev_button_state == GPIO.HIGH and button_state == GPIO.LOW: # Button is pressed press_time_start = time.time() is_pressing = True is_long_detected = False elif prev_button_state == GPIO.LOW and button_state == GPIO.HIGH: # Button is released is_pressing = False if is_pressing and not is_long_detected: press_duration = time.time() - press_time_start if press_duration > LONG_PRESS_TIME: print("A long press is detected") is_long_detected = True # Save the last state prev_button_state = button_state except KeyboardInterrupt: print("\nExiting the program.") GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 long_press_2.py
  • Press the button and hold it for a few seconds then release the button.
  • Check out the result on the Serial Monitor.
PuTTY - Raspberry Pi
A long press is detected

The event of long-pressing is only detected even when the button has not been released.

How To Detect Both Long Press and Short Press

Detailed Instructions

  • Create a Python script file long_short_press.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-long-press-short-press """ import RPi.GPIO as GPIO import time BUTTON_PIN = 16 SHORT_PRESS_TIME = 0.5 # 500 milliseconds LONG_PRESS_TIME = 1.0 # 1 seconds DEBOUNCE_TIME = 0.1 # 100 milliseconds # Variables will change: prev_button_state = GPIO.LOW # the previous state from the input pin button_state = None # the current reading from the input pin press_time_start = 0 press_time_end = 0 # Set up GPIO and configure the pull-up resistor GPIO.setmode(GPIO.BCM) 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) # Perform debounce by waiting for DEBOUNCE_TIME time.sleep(DEBOUNCE_TIME) if prev_button_state == GPIO.HIGH and button_state == GPIO.LOW: # Button is pressed press_time_start = time.time() elif prev_button_state == GPIO.LOW and button_state == GPIO.HIGH: # Button is released press_time_end = time.time() press_duration = press_time_end - press_time_start if press_duration < SHORT_PRESS_TIME: print("A short press is detected") elif press_duration >= LONG_PRESS_TIME: print("A long press is detected") # Save the last state prev_button_state = button_state except KeyboardInterrupt: print("\nExiting the program.") GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 long_short_press.py
  • Press the button, both for a short and long duration.
  • Check out the results on the Terminal.

Video Tutorial

Why Needs Long Press and Short Press

  • To minimize the number of buttons, one button can be used to perform multiple functions. For instance, a short press can be used to switch the operation mode, while a long press can be used to turn off the device.
  • Using a long press helps to prevent accidental short presses. For example, some devices use a button to initiate a factory reset. If the button is pressed unintentionally, it could be hazardous. To avoid this, the device is designed to only initiate a factory reset when the button is held down for a certain amount of time (e.g. 5 seconds).

※ 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!