Running multiple tasks on a microcontroller can be a bit complicated using the traditional coding style (Figure 1). Sometimes we have to restructure the whole code just to add a new feature to the system. Using Real Time Operating System (RTOS) coding style (Figure 2), it is easier to manage tasks. In this tutorial, we will be using pyRTOS on Maker Pi Pico.
What is RTOS?
Real-time operating system (RTOS) is a software component that rapidly switches between tasks, giving the impression that multiple programs are being executed at the same time (see Figure 3). Multicore systems are able to truly run tasks simultaneously by using different cores to run different tasks. RTOS is useful for running multiple tasks that have strict execution timings. For example, NASA’s Perseverance rover uses RTOS (VxWorks) in order to operate various scientific instruments in real time.
Why use RTOS?
An RTOS makes development easier for many projects, and it makes them more expandable, maintainable, portable, and secure. Saving time and cost for development. A simple loop program will get more and more messy, degenerating into spaghetti code, becoming difficult to manage as new features are added into the code. It will be more difficult to maintain, modify and expand.
Multitasking, alone, is enough reason to use an RTOS in many systems. It allows you to break a complex problem into simpler pieces and focus on the development of each task rather than on scheduling when things run. It also makes it easier to delegate work among members of a team. RTOS also allows us to utilize the maximum capabilities of the microcontroller, even more so on a dual core microcontroller like the Pico.
Installing pyRTOS on Maker Pi Pico
|1||Download Mu Editor||Download Thonny|
|2||Download libraries for Maker Pi Pico|
|3||Copy pyRTOS folder from CircuitPython example code to Maker Pi Pico lib folder|| |
Copy pyRTOS folder from MicroPython example code to Maker Pi Pico through Thonny (video below)
Coding with pyRTOS (MicroPython Example)
1. Import pyRTOS and tasks dependencies
import pyRTOS import machine # import task dependencies
2. Define task
def task1(self): ledpin1 = machine.Pin(0, machine.Pin.OUT) # Task1 setup ledpin1.value(0) yield while True: ledpin1.toggle() # Task1 loop yield [pyRTOS.timeout(1)] # Delay for 1 second (Other task can run)
3. Add task.
4. Start RTOS