carlsopa
Posts: 13
Joined: Sat Mar 28, 2015 1:17 am

using a button long press vs short press

Mon Jun 20, 2016 12:41 am

I am working on an alarm clock project. One aspect of it, is when I press it a button, it will either turn on/off the alarm, or go into a set time mode. My current code, currently works but will also trigger the else statement. I assume this is because after the sleep(3) it still registers a press.

I am looking for any suggestions, or ideas that would make my code better. What I would like to do is a long press enters a set mode, while a single press would set the alarm.

Code: Select all

if (GPIO.input(Alarm) == False):
  sleep(3)
  if (GPIO.input(Alarm) == False):
    AlarmSet = True
    print('set alarm')
    continue
  else:
    Alrm1.setAlarm()
    print('Alarm')

User avatar
Cancelor
Posts: 757
Joined: Wed Aug 28, 2013 4:09 pm
Location: UK

Re: using a button long press vs short press

Mon Jun 20, 2016 8:09 am

One way would be to measure the time that the button is pressed for and then afterwards have some code that decides what to do. :)
Can't find the thread you want? Try googling : YourSearchHere site:raspberrypi.org

PiGraham
Posts: 3671
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: using a button long press vs short press

Mon Jun 20, 2016 8:33 am

It looks like Button in GPIOZero allows an event callback on a hold:

http://bennuttall.com/whats-new-gpio-zero-v1-2/

Code: Select all

from gpiozero import Button

def hello():
    print("Hello")

button = Button(2, hold_time=2)

button.when_held = hello

User avatar
ben_nuttall
Raspberry Pi Foundation Employee & Forum Moderator
Raspberry Pi Foundation Employee & Forum Moderator
Posts: 231
Joined: Sun Aug 19, 2012 11:19 am
Location: Cambridge, UK
Contact: Website

Re: using a button long press vs short press

Fri Jul 01, 2016 7:51 pm

That's right. See http://gpiozero.readthedocs.io/en/lates ... ero.Button

The above example is as simple as it gets!
Community Manager - Raspberry Pi Foundation
Author of GPIO Zero and creator of piwheels

User avatar
Redryno
Posts: 8
Joined: Tue Jun 28, 2016 12:31 am
Location: Missouri, USA

Re: using a button long press vs short press

Sat Jul 02, 2016 4:01 am

You could time how long it is between rising edge and falling edge.

Return to “Python”