07a485b04d
- stricter timeouts: Instead of adding an entire millisecond, use a list of timeouts that are supposed to be handled on the same tick. This reduces the delay between target tick and actual tick, especially for many timeouts issued to the same tick, i.e. combos. - consistent timeouts: Timeouts are now guaranteed to be handled in the order they were issued. Timer rollover is handled properly. caveat / change to the interface: the returned `timeout_key` is a tuple of the target timeout tick and the index of the timeout at that tick.
35 lines
807 B
Python
35 lines
807 B
Python
from micropython import const
|
|
from supervisor import ticks_ms
|
|
|
|
_TICKS_PERIOD = const(1 << 29)
|
|
_TICKS_MAX = const(_TICKS_PERIOD - 1)
|
|
_TICKS_HALFPERIOD = const(_TICKS_PERIOD // 2)
|
|
|
|
|
|
def ticks_diff(new, start):
|
|
diff = (new - start) & _TICKS_MAX
|
|
diff = ((diff + _TICKS_HALFPERIOD) & _TICKS_MAX) - _TICKS_HALFPERIOD
|
|
return diff
|
|
|
|
|
|
def ticks_add(ticks, delta):
|
|
return (ticks + delta) % _TICKS_PERIOD
|
|
|
|
|
|
def check_deadline(new, start, ms):
|
|
return ticks_diff(new, start) < ms
|
|
|
|
|
|
class PeriodicTimer:
|
|
def __init__(self, period):
|
|
self.period = period
|
|
self.last_tick = ticks_ms()
|
|
|
|
def tick(self):
|
|
now = ticks_ms()
|
|
if ticks_diff(now, self.last_tick) >= self.period:
|
|
self.last_tick = now
|
|
return True
|
|
else:
|
|
return False
|