Skip to content

4 Understanding the code

Alex Au edited this page Sep 11, 2018 · 3 revisions
Inside the code there are already some detailed comments about the functions of each block of code, so in here only the RTOS coding methodology and peripherals interfacing will be explained

1. Threads

The core concept of a multitasking OS, threads are the sequence of instructions that can be run independently and simultaneously by our MCU. Imagine that you have to blink your LED with 1s interval, you may do this:

Loop:
    turn on LED
    wait for 500ms
    turn off LED
    wait for 500ms

Then, what if you also want to turn a motor on and off in a 0.8s interval? It will take a lot more code to make the timing right.

Loop:
    turn on LED
    turn on MOTOR
    wait for 400ms
    turn off MOTOR
    wait for 100ms
    turn off LED
    wait for 300ms
    turn on MOTOR
    wait for 200ms
    turn on LED
    ...(until the pattern repeats)

In other scenarios, you may need to call a function to check something repeatedly and rapidly (e.g. reading a pin) while doing something with lower frequency (blinking a LED?), where the problem will be more significant.

With threads, the OS can schedule the tasks for you. One can create almost infinite threads running on some function (even same) "concurrently". The OS do this by performing a context switch to another thread when the active thread function try to be inactive (sleep, wait, terminate etc). In other words, the MCU will always try to run something else useful instead of waiting for only one task.