0
votes

There is a FreeRTOS library for Arduino, purported to even run on the UNO.

I'm trying to understand the inner workings of how a multi-tasking operating system can run on such limited hardware. I understand the principles of task scheduling/switching, but how does the kernel actually suspend a task in order to execute another one? How does it interrupt (and then later resume) the currently-executing code?

My guess is that a scheduled ISR (timer) directly modifies the stack to change the instruction pointer, but if it does this, it needs to make a copy of the stack and registers before switching tasks, then restore the current task's stack/registers before resuming execution. I'm not clear on how it would do this.

Can the FreeRTOS kernel switch tasks in the middle of, for example, a Serial.println() function call, (or any call that doesn't include cli()) and if so, how does it do this?

Thanks for any clarification.

1

1 Answers

1
votes

My guess is that a scheduled ISR (timer) directly modifies the stack to change the instruction pointer, but if it does this, it needs to make a copy of the stack and registers before switching tasks, then restore the current task's stack/registers before resuming execution. I'm not clear on how it would do this.

Your guess is correct. If you look at port.c you will see, that the FreeRTOS makros portSAVE_CONTEXT and portRESTORE_CONTEXT are pushes respective pops all registers of the current running task to perform the task switch. Furthermore the watchdog timer interrupt is used to run the scheduler.

As long this watchdog timer is enabled and is triggerd, task switches can happen any time. So a switch can also happen during any function call like Serial.println. This implies that if you call this function from several task you will sooner or later corrupt your output of the serial stream.