Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating a 'holdable button' with gpiozero
from gpiozero import Button
from threading import Timer
class HoldableButton(Button):
def __init__(self, pin=None, pull_up=True, bounce_time=None, hold_time=1, repeat=False):
super(HoldableButton, self).__init__(pin, pull_up, bounce_time)
# Set Button when_pressed and when_released to call local functions
# cant use super() as it doesn't support setters
Button.when_pressed.fset(self, self._when_button_pressed)
Button.when_released.fset(self, self._when_button_released)
self._when_held = None
self._when_pressed = None
self._when_released = None
self._is_held = False
self.hold_time = hold_time
self.repeat = repeat
self._held_timer = None
#override button when_pressed and when_released
@property
def when_pressed(self):
return self._when_pressed
@when_pressed.setter
def when_pressed(self, value):
self._when_pressed = value
@property
def when_released(self):
return self._when_released
@when_released.setter
def when_released(self, value):
self._when_released = value
@property
def when_held(self):
return self._when_held
@when_held.setter
def when_held(self, value):
self._when_held = value
@property
def is_held(self):
return self._is_held
def _when_button_pressed(self):
self._start_hold()
if self._when_pressed != None:
self._when_pressed()
def _when_button_released(self):
self._is_held = False
self._stop_hold()
if self._when_released != None:
self.when_released()
def _start_hold(self):
self._held_timer = Timer(self.hold_time, self._button_held)
self._held_timer.start()
def _stop_hold(self):
if self._held_timer != None:
self._held_timer.cancel()
def _button_held(self):
self._is_held = True
if self._when_held != None:
if self.repeat and self.is_pressed:
self._start_hold()
self._when_held()
if __name__ == "__main__":
from time import sleep
def button_pressed():
print("pressed")
def button_released():
print("released")
def button_held():
print("held")
pin = 26
but = HoldableButton(pin, hold_time = 0.5, repeat = True)
but.when_held = button_held
but.when_pressed = button_pressed
but.when_released = button_released
while True:
sleep(0.1)
print("Is held = {}".format(but.is_held))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.