How do I make a button do different things based on how long the button is pressed? See the code below, kind of explains what I need to figure out.
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.off()
button.when_pressed = buttonpressed
HERE IS WHAT I NEED = buttonlongpressed
pause()
You’ll need to consult this documentation:
https://pypi.org/project/gpiozero/
They have this example code:
from gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(3)
button.when_pressed = led.on
button.when_released = led.off
pause()
There is “when_pressed” and “when_released” so you can implement something to count the time between press and release.
in psuedocode:
button.when_pressed = start_timer
Press+release < 2 sec might run something and
Press > 4 sec might run something else
You could use this
from gpiozero import Button
import time
print("hello")
end = time.time()
print(end - start)
button = Button(2)
while True:
if button.is_pressed:
print("Button is pressed")
else:
print("Button is not pressed")
https://gpiozero.readthedocs.io/en/latest/recipes.html#button
With this:
https://stackoverflow.com/questions/7370801/how-do-i-measure-elapsed-time-in-python
import time
start = time.time()
print("hello")
end = time.time()
print(end - start)
To build something to measure a button press length