The objective of this post is to explain how to launch a thread on MicroPython running on the ESP32. The tests were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.
The objective of this post is to explain how to launch a thread on MicroPython running on the ESP32. This will be a very simple initial example where we will define a function that will be executed by our thread and periodically prints a “hello world” message.
We start by importing the thread module, which makes available the function needed to launch threads. Note that the module is called _thread (the underscore is not a typo). We will also import the time module, so we can use the sleep function to introduce some delays on our program.
import _thread import time
Next we will define the function that will execute in our thread. Our function will simply print a “hello world” message in an infinite loop, with some delay in each iteration.
We will introduce the delay using the mentioned sleep function of the time module, which receives as input the number of seconds to delay. I’m using a 2 seconds delay, but you can use a different value.
def testThread(): while True: print("Hello from thread") time.sleep(2)
It’s important to consider that when the function returns, the thread exits . Nonetheless, in our case, this will never happen since our thread will run on an infinite loop.
Finally, to start our thread, we simply call the start_new_thread function of the _thread module, specifying as first argument our previously defined function and as second a tuple which corresponds to the thread function arguments.
Since our function expects no arguments, we will pass an empty tuple. An empty tuple is declared using empty parenthesis .
You can check the full source code below.
import _thread import time def testThread(): while True: print("Hello from thread") time.sleep(2) _thread.start_new_thread(testThread, ())
Testing the code
To test the code, simply upload the previous script to your board and run it. You should get an output similar to figure 1, which shows the output of our thread. It should print the message with the periodicity defined in the code.
Figure 1 – Output of the script.