I am new to Python, used my Python common sense but did not get any results. I am trying to learn how to do x-times of button presses and in x-amount of time to trigger something. In the below code, I am trying to do double press in 600ms or less to say "Button pressed twice". The end result I am trying to achieve is, press button once and get "Hello!" and press button twice in less than 600ms and get "Button pressed twice". Sorry for repeating.

from gpiozero import Button
from signal import pause

def say_hello():

button = Button(3)

button.when_pressed = say_hello

  • look at the very end of this code ... programcreek.com/python/… – jsotola Oct 7 '20 at 5:42
  • 3
    Is this a Raspberry Pi or a Python question? My answer is Python! – Mats Karlsson Oct 7 '20 at 5:52
  • 2
    I have seen some GPIOZero questions here and GPIOZero is a RPi thing so I thought I would post it here. – user1523934 Oct 7 '20 at 18:07

Two options. You could use wait_for_press followed by wait_for_release followed by wait_for_press, with a timeout:

while True:
    if btn.wait_for_press(timeout=0.6):
        print("pressed twice")

this leaves room for the release to take a long time, so maybe keep track of the timings between the two:

from datetime import datetime, timedelta

while True:
    pressed = datetime.now()
    if btn.wait_for_release(timeout=0.6):
        timeout = pressed - datetime.now()
        if btn.wait_for_press(timeout=timeout):
            print("pressed twice")

Second option: use when_pressed and keep track of the pressed time each time:

from datetime import datetime, timedelta

Button.pressed_time = None

def pressed(btn):
    if btn.pressed_time:
        if btn.pressed_time + timedelta(seconds=0.6) > datetime.now():
            print("pressed twice")
            print("too slow") # debug
        btn.pressed_time = None
        print("pressed once")  # debug
        btn.pressed_time = datetime.now()

btn = Button(3)
btn.when_pressed = pressed

button.when_pressed can be used to record the time. You can then check the time against the last recorded to determine the interval.

You could even extend the Button Class to detect double press.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.