diff --git a/examples/buttons.py b/examples/buttons.py index 8c82e9a..f864380 100644 --- a/examples/buttons.py +++ b/examples/buttons.py @@ -9,6 +9,7 @@ """ from modulino import ModulinoButtons +from time import sleep buttons = ModulinoButtons() @@ -24,6 +25,13 @@ buttons.on_button_c_long_press = lambda : print("Button C long press") buttons.on_button_c_release = lambda : print("Button C released") +buttons.led_a.on() +sleep(0.5) +buttons.led_b.on() +sleep(0.5) +buttons.led_c.on() +sleep(0.5) +buttons.set_led_status(False, False, False) # Turn off all LEDs while True: buttons_state_changed = buttons.update() diff --git a/src/modulino/buttons.py b/src/modulino/buttons.py index 64f0a81..b16cda7 100644 --- a/src/modulino/buttons.py +++ b/src/modulino/buttons.py @@ -2,6 +2,26 @@ from time import ticks_ms from micropython import const +class ModulinoButtonsLED(): + def __init__(self, buttons): + self._value = 0 + self._buttons = buttons + + def on(self): + self.value = 1 + + def off(self): + self.value = 0 + + @property + def value(self): + return self._value + + @value.setter + def value(self, value): + self._value = value + self._buttons._update_leds() + class ModulinoButtons(Modulino): """ Class to interact with the buttons of the Modulino Buttons. @@ -35,7 +55,37 @@ def __init__(self, i2c_bus = None, address = None): self._on_button_a_long_press = None self._on_button_b_long_press = None self._on_button_c_long_press = None + + # LEDs + self._led_a = ModulinoButtonsLED(self) + self._led_b = ModulinoButtonsLED(self) + self._led_c = ModulinoButtonsLED(self) + + @property + def led_a(self) -> ModulinoButtonsLED: + """ Returns the LED A object of the module. """ + return self._led_a + + @property + def led_b(self) -> ModulinoButtonsLED: + """ Returns the LED B object of the module. """ + return self._led_b + @property + def led_c(self) -> ModulinoButtonsLED: + """ Returns the LED C object of the module. """ + return self._led_c + + def _update_leds(self): + """ + Update the physical status of the button LEDs by writing the current values to the module. + """ + data = bytearray(3) + data[0] = self._led_a.value + data[1] = self._led_b.value + data[2] = self._led_c.value + self.write(data) + def set_led_status(self, a: bool, b: bool, c: bool) -> None: """ Turn on or off the button LEDs according to the given status. @@ -45,11 +95,10 @@ def set_led_status(self, a: bool, b: bool, c: bool) -> None: b (bool): The status of the LED B. c (bool): The status of the LED C. """ - data = bytearray(3) - data[0] = 1 if a else 0 - data[1] = 1 if b else 0 - data[2] = 1 if c else 0 - self.write(data) + self._led_a._value = 1 if a else 0 + self._led_b._value = 1 if b else 0 + self._led_c._value = 1 if c else 0 + self._update_leds() @property def long_press_duration(self) -> int: