|
| 1 | +import typing |
| 2 | +import protocols.gpio |
| 3 | +from machine import Pin, PWM |
| 4 | + |
| 5 | +class GPIO(protocols.gpio.GPIO): |
| 6 | + def __init__(self, pin_name: str): |
| 7 | + print(f'Initialising {type(self).__name__} with pin {pin_name}') |
| 8 | + self.pin_name = pin_name |
| 9 | + |
| 10 | + |
| 11 | +class ButtonPin(GPIO, protocols.gpio.ButtonPin): |
| 12 | + def __init__(self, pin_name: str): |
| 13 | + super().__init__(pin_name) |
| 14 | + |
| 15 | + @property |
| 16 | + def value(self) -> bool: |
| 17 | + raise NotImplementedError() |
| 18 | + |
| 19 | + def on_level_changed(self, callback: typing.Callable[[bool], None]) -> None: |
| 20 | + raise NotImplementedError() |
| 21 | + |
| 22 | +class AnalogInputPin(GPIO, protocols.gpio.AnalogInputPin): |
| 23 | + def __init__(self, pin_name: str): |
| 24 | + super().__init__(pin_name) |
| 25 | + |
| 26 | + @property |
| 27 | + def value(self) -> float: |
| 28 | + raise NotImplementedError() |
| 29 | + |
| 30 | +class DigitalOutputPin(GPIO, protocols.gpio.DigitalOutputPin): |
| 31 | + def __init__(self, pin_name: str): |
| 32 | + super().__init__(pin_name) |
| 33 | + self.pin = Pin(int(pin_name), Pin.OUT) |
| 34 | + self._value = False |
| 35 | + self.on = False |
| 36 | + |
| 37 | + @property |
| 38 | + def on(self) -> bool: |
| 39 | + return self._value |
| 40 | + |
| 41 | + @on.setter |
| 42 | + def on(self, on: bool) -> None: |
| 43 | + self.pin.value(1 if on else 0) |
| 44 | + self._value = on |
| 45 | + |
| 46 | +class PWMOutputPin(GPIO, protocols.gpio.PWMOutputPin): |
| 47 | + def __init__(self, pin_name: str): |
| 48 | + super().__init__(pin_name) |
| 49 | + self.pin = PWM(Pin(int(pin_name)), freq=1000) |
| 50 | + self.duty = 0.0 |
| 51 | + |
| 52 | + @property |
| 53 | + def duty(self) -> float: |
| 54 | + return self.pin.duty_u16() / 65535.0 |
| 55 | + |
| 56 | + @duty.setter |
| 57 | + def duty(self, duty: float) -> None: |
| 58 | + self.pin.duty_u16(int(duty * 65535)) |
0 commit comments