microbit-foundation / micropython-microbit-v2

Temporary home for MicroPython for micro:bit v2 as we stablise it before pushing upstream
MIT License
41 stars 22 forks source link

`microbit.run_every` with `power.deep_sleep()` with has odd timings #128

Closed microbit-carlos closed 1 year ago

microbit-carlos commented 1 year ago

This simple script should wake up every 10 seconds and print the running time to serial.

from microbit import *
import power

@run_every(s=10)
def print_time():
    print(running_time())

while True:
    power.deep_sleep(run_every=True)

This is what I get on a random run with v2.1.0-beta.3:

20176
50176
50179
50182
53838
80177
80180
102019
110176
110178
162895
170175
170178
170182
180176

It doesn't seem very predictable, but mostly looks like it misses a lot of the wake up times from the run_every and double/triple logs the time the next time it wakes up. Running the script next to a stopwatch and the times printed are more or less accurate.

Implementing https://github.com/microbit-foundation/micropython-microbit-v2/issues/118 might also affect this result, but it's a good simple test to run as well while working on that.

Also, at this might be related to some of the CODAL sleep issues, but we need to double check this problem after the CODAL fixes land in the next release.

microbit-carlos commented 1 year ago

Actually this might be related to the fact that there is no sleep() in infinite loop, adding one and the times look much better:

from microbit import *
import power

@run_every(s=10)
def print_time():
    print(running_time())

while True:
    power.deep_sleep(run_every=True)
    sleep(100)
10182
20181
30180
40182
50180
60180
70182
80180
90180
100182
110180
120180

I guess the main fiber needs to yield for sleep to work correctly? Do you have any insights or recommendations @JohnVidler @martinwork?

dpgeorge commented 1 year ago

I think this was a problem on MicroPython's side, not giving the internal MicroPython scheduler time to run the outstanding events.

Fixed by implementing #118.

microbit-carlos commented 1 year ago

Thanks Damien! I can confirm this works now without the sleep. 🎉