2021-09-17 17:40:20 +02:00
|
|
|
from micropython import const
|
2022-03-05 12:12:28 +01:00
|
|
|
from supervisor import ticks_ms
|
2018-10-17 07:43:47 +02:00
|
|
|
|
2021-09-13 17:18:01 +02:00
|
|
|
_TICKS_PERIOD = const(1 << 29)
|
|
|
|
_TICKS_MAX = const(_TICKS_PERIOD - 1)
|
|
|
|
_TICKS_HALFPERIOD = const(_TICKS_PERIOD // 2)
|
2018-10-07 09:44:04 +02:00
|
|
|
|
2018-09-28 23:35:52 +02:00
|
|
|
|
2022-10-02 20:49:23 +02:00
|
|
|
def ticks_diff(new: int, start: int) -> int:
|
2021-09-13 17:18:01 +02:00
|
|
|
diff = (new - start) & _TICKS_MAX
|
|
|
|
diff = ((diff + _TICKS_HALFPERIOD) & _TICKS_MAX) - _TICKS_HALFPERIOD
|
|
|
|
return diff
|
2018-09-28 23:35:52 +02:00
|
|
|
|
|
|
|
|
2022-10-02 20:49:23 +02:00
|
|
|
def ticks_add(ticks: int, delta: int) -> int:
|
2022-03-09 02:22:09 +01:00
|
|
|
return (ticks + delta) % _TICKS_PERIOD
|
|
|
|
|
|
|
|
|
2022-10-02 20:49:23 +02:00
|
|
|
def check_deadline(new: int, start: int, ms: int) -> int:
|
2021-09-13 17:18:01 +02:00
|
|
|
return ticks_diff(new, start) < ms
|
2022-03-05 12:12:28 +01:00
|
|
|
|
|
|
|
|
|
|
|
class PeriodicTimer:
|
2022-10-02 20:49:23 +02:00
|
|
|
def __init__(self, period: int):
|
2022-03-05 12:12:28 +01:00
|
|
|
self.period = period
|
|
|
|
self.last_tick = ticks_ms()
|
|
|
|
|
2022-10-02 20:49:23 +02:00
|
|
|
def tick(self) -> bool:
|
2022-03-05 12:12:28 +01:00
|
|
|
now = ticks_ms()
|
|
|
|
if ticks_diff(now, self.last_tick) >= self.period:
|
|
|
|
self.last_tick = now
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|