From f1617357eddd8c0289e34de4eaa0bf3035f044af Mon Sep 17 00:00:00 2001 From: Irvyn Cornejo Date: Tue, 24 Jan 2023 22:30:40 -0600 Subject: [PATCH] Add button class --- .../rpi-gpio-pico/gpiopico/input_devices.py | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/raspberry-pico/rpi-gpio-pico/gpiopico/input_devices.py b/raspberry-pico/rpi-gpio-pico/gpiopico/input_devices.py index a6372db..d57d992 100644 --- a/raspberry-pico/rpi-gpio-pico/gpiopico/input_devices.py +++ b/raspberry-pico/rpi-gpio-pico/gpiopico/input_devices.py @@ -161,8 +161,36 @@ class LM35(AnalogicInputs): pass class Button: - def __init__(self, pin) -> None: + def __init__( + self, + pin: int, + show_value: bool = False + ) -> None: self._input = Pin(pin, Pin.IN, Pin.PULL_UP) + self._when_pressed = None + self._show_value = show_value + + + @property + def when_pressed(self): + return self._when_pressed + + @when_pressed.setter + def when_pressed(self, callback): + if ( + type(callback).__name__ == 'function' or + type(callback).__name__ == 'bound_method' + ): + self._when_pressed = callback + else: + raise ValueError('callback will be a function or bound_method') + + def check_state(self): + _value = self._input.value() + if self._when_pressed and _value == 0: + self._when_pressed + (print(_value) if self._show_value else None) + sleep(0.3) class PIR: def __init__(