"""
pyb package dummy classes
"""
import time
from utime import ticks_ms, ticks_us
from typing import Optional, Callable, Dict
[docs]class LED:
"""LED Class"""
# Keep track of LED states across instances
_values: Dict[int, bool] = {}
def __init__(self, led_id: int):
"""Create LED instance
:param led_id: id of the LED
"""
self._intensity = 0
self.id = led_id
if self.id not in self._values:
self._values[self.id] = False
[docs] def intensity(self, value: int = None) -> Optional[int]:
"""Set _intensity through PWM, from 0 to 255
Does not work on our Nucleo! None of the LEDs are connected to a PWM
pin. We don't bother a universal value here.
"""
if value is None:
return self._intensity
self._intensity = value
[docs] def off(self):
"""Turn LED off"""
self._values[self.id] = False
[docs] def on(self):
"""Turn LED on"""
self._values[self.id] = True
[docs] def toggle(self):
"""Toggle LED state"""
self._values[self.id] = not self._values[self.id]
[docs] def test_is_on(self) -> bool:
"""Get the current state of the LED
Getting the state does not seem possible on regular micropython.
"""
return self._values[self.id]
[docs]class Switch:
"""Class for a digital switch
Can only be used for the on-board user switch
"""
# Keep track of switch values
_values: Dict[str, bool] = {}
def __init__(self):
"""Create switch for the user button"""
self._func = None
self.id = 'switch' # Only the one switch
if self.id not in self._values:
self._values[self.id] = False
[docs] def value(self) -> bool:
"""Get the current button state"""
return self._values[self.id]
[docs] def callback(self, func: Optional[Callable]):
"""Set an interrupt callback
Set `func` to None to disable it.
"""
self._func = func
[docs] def test_set_value(self, value: bool):
"""Set button state"""
state = bool(value)
self._values[self.id] = state
if state and self._func is not None:
self._func()
[docs] def test_push(self, value: bool = True):
"""Set button state and return it to the previous state"""
old_state = self.value()
# Set state (it will handle callbacks if any)
self.test_set_value(value)
time.sleep(0.10) # Give to time to e.g. tickers to register the push
# Recover previous state
self.test_set_value(old_state)
#
# Global functions:
#
[docs]def delay(ms: float):
"""Pause for a number of milliseconds"""
time.sleep(ms / 1e3)
[docs]def udelay(us: float):
"""Pause for a number of microseconds"""
time.sleep(us / 1e6)
[docs]def millis() -> int:
"""Get the current runtime in milliseconds"""
return ticks_ms()
[docs]def micros() -> int:
"""Get the current runtime in microseconds"""
return ticks_us()
[docs]def elapsed_millis(start=0):
"""Get the current number of elapsed milliseconds since `start`
Takes care of unwrapping to extend pas integer overflow.
"""
return millis() - start