Python Forum
This is probably a simple one for this forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
This is probably a simple one for this forum
#1
I need to have one button do different things based on how long it was pressed. It will be adapted to my "washer and dryer timer" box that initiates timers on different user's phones based on different button pressings. All buttons are currently in use, and I can't add another button. Hoping I can add a function to a button by how long it is pressed. I have reduced the code down to a very simple example. For the code below, I just want different LEDs to light based on how long the button was pressed. Short press gets only LED1 on, long press gets only LED2 on.

from gpiozero import Button, LED

from signal import pause
from time import sleep
import time


button = Button(16)
LED1 = LED(18)
LED2 = LED(25)


#  How do I get the "buttonlongpressed" to happen without
#  the "buttonpressed" happenening too?

#  Button is pressed and released within a second
def buttonpressed():
    print("Short pressed")
    LED1.on()
    LED2.off()
    
#  Button is pressed for more than 5 seconds and released
def buttonlongpressed():
    print("Long pressed")
    LED2.on()
    LED1.on()


button.when_pressed = buttonpressed
HERE IS WHAT I NEED = buttonlongpressed

pause()
Reply
#2
One solution I imagine is changing it to when the button is released, but upon release it checks a variable that was set when the button was held for a certain amount of time. Not sure where to start with that
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020