Timers hang when used around many sleeps

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
samneggs
Posts: 20
Joined: Tue Jun 15, 2021 12:57 am

Timers hang when used around many sleeps

Post by samneggs » Tue Jun 15, 2021 1:04 am

I found that timers hang if many sleeps are executed in the main loop.
I get from 1 to 10 ticks of this timer before it hangs. If I replace the sleep with pass or any code it does not hang.
Any ideas?
Sam

Code: Select all

import time, utime
from machine import Timer

def display_timer(timer):
    global count
    count+=1
    if count == 1000:
        count =0
        print('tick,',end='')


tim = Timer()
tim.init(freq=1000, mode=Timer.PERIODIC, callback=display_timer)        # 400

    
count = 0
if __name__ == '__main__':
    try:
        while True:
            #pass
            utime.sleep_ms(1) 
    # When 'Ctrl+C' is pressed, the following will be  executed.
    except KeyboardInterrupt:
        tim.deinit()
        print("All done.")

davef
Posts: 811
Joined: Thu Apr 30, 2020 1:03 am
Location: Christchurch, NZ

Re: Timers hang when used around many sleeps

Post by davef » Tue Jun 15, 2021 4:52 am

Try 20ms. One of the ESP devices has a min of 10ms, it might apply to other devices.

hippy
Posts: 130
Joined: Sat Feb 20, 2021 2:46 pm
Location: UK

Re: Timers hang when used around many sleeps

Post by hippy » Tue Jun 15, 2021 10:12 am

My notes say timer callbacks are as broken on a Pico as threading is but they don't detail what breaks things. I did find this where simply replacing "time.sleep_ms(1_000)" with "time.sleep_us(1_000_000)" causes very odd behaviour with timers -

https://www.raspberrypi.org/forums/view ... 6&t=312874

I wasted so much time on code using broken timers that I edited my MicroPython build to report "Timers are broken" in the REPL whenever I instantiate one so I don't forget that they are.

samneggs
Posts: 20
Joined: Tue Jun 15, 2021 12:57 am

Re: Timers hang when used around many sleeps

Post by samneggs » Wed Jun 16, 2021 12:14 am

Turns out a 20mS timer fails too - it just takes 5x to 10x longer.
I also verified the main loop stops executing but I can gracefully exit with a CTRL-C which prints 'All done'.

My solution is to double down on timers to replace the repeating sleeps. So far, OK.
Sam

Post Reply