RTOS
Introduction
Thought I would do a page on RTOS so I have the terminology right. May do the same for Zephyr and Embassy to see how they compare.
RTOS Platforms
For me I have come across the different platforms
- Zephyr running on my Nordic boards
- FreeRTOS no used but the course drove me to this
- IDF RTOS running on my ESP32 (not sure the difference)
Arduino
I guess most people of familiar with the Arduino approach to software with sketches. I dislike the ecosystem and try to avoid it but this is what the course used.
void foo1() {
// Do some function
}
void foo2() {
// Do some function
}
void setup() {
// Do some setup
}
void loop() {
// Do something forever
foo1();
foo2();
}
Using Arduino with RTOS
The purpose of this page we will use only one processor, whereas the ESP32 I am using has two. To disable this we will use the following code. It will be omitted from code examples to save space.
// Use only core 1 for demo purposes
#if CONFIG_FREERTOS_UNICORE
static const BaseType_t app_cpu = 0;
#else
static const BaseType_t app_cpu = 1;
#endif
Tasks
In RTOS a task is a unit of work. It have these states
To create a task we use the following code.
// Task to run forever
xTaskCreatePinnedToCore( // Use xTaskCreate() in vanilla FreeRTOS
toggleLED_1, // Function to be called
"Toggle 1", // Name of task
1024, // Stack size (bytes in ESP32, words in FreeRTOS)
NULL, // Parameter to pass to function
1, // Task priority (0 to configMAX_PRIORITIES - 1)
NULL, // Task handle
app_cpu); // Run on one core for demo purposes (ESP32 only)
I guess this is mainly self explanatory. There are other APIs to create a task. I have used xTaskCreate, but I think we are using this to ensure only on CPU is useda task
Scheduler
Clearly the most important part of the deal. This picture was provided with more information than my tiny brain could handle. I guess the salient points were.
- The default timeslice is 1 ms and known as a "tick"
- The hardware time is configure to create an interrupt every tick
- The and the ISR for the timer runs the scheduler
- This chooses which task to run
- The highest priority task is selected
- If there are two, then it uses round robin
- If a task with a higher priority becomes ready it is run immediately rather than wait for the scheduler
- A hardware interrupt is always considered to have a higher priority than any tasks
- You can change priority of a create task two.
Now the pretty picture. Where the pink is an ISR
Memory
Quite liked this picture, although do understand the difference between the heap and the stack, it is a nice picture to remind you.
For RTOS this might be how the memory is allocated.
The task control block for a task holds properties about the task. e.g. Priority stack pointer. The kernel object like semaphores and queues also get allocated on the heap. There are different strategies for allocating memory in FreeRTOS depending on your needs.