Running blocking code in timers

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
pipponefrancone
Posts: 10
Joined: Sat Sep 12, 2020 6:02 pm

Running blocking code in timers

Post by pipponefrancone » Fri Oct 23, 2020 12:54 pm

Hello everyone,
Whenever I try running a timer that takes as callback a function containg blocking code in it, the whole repl freezes and does not let me enter any word.
Ex.:

Code: Select all

from machine import Timer

def handler(timer):
         time.sleep(1)
         print('hello')
      
x = Timer(0)
x.init(period=1000, mode=1, callback= handler)
What I am really aming for here is something similar to what the threading module does for python, basically starting a background process without freezing the shell. How can I do it? :)

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Running blocking code in timers

Post by jimmo » Sat Oct 24, 2020 4:33 am

Depending on which board/port you're using, MicroPython does support threading, via the _thread module. However, I'd recommend against using it as threading is almost always more problematic than useful.

My recommendation is to use asyncio. The latest version of MicroPython (v1.13) includes a much-improved version of asyncio, and you can see Peter's excellent tutorial and guides here https://github.com/peterhinch/micropython-async

In general though, for embedded systems the approach you need to take is that IRQs and event handlers should only be used to tell your code that something happened and they should do the minimal work possible to record the event (i.e. set a global variable flag or something). Then your main program should be looking at these variables to decide what to do.

Post Reply