Embedded real-time operating system¶
Learning goals: Basic principles of embedded programming.
We will start familiarizing ourselves with embedded systems programming by first reviewing the structure of a program (in Raspberry Pi Pico). After that we will add functionality by learning the usage of different peripheral device libraries.
Real-time operating system¶
In this course, we are using Raspberry Pi Pico C/C++ SDK and ARM toolchain to program our device. In addition we’ll be using the FreeRTOS real-time operating system (RTOS) to aid us in our programming tasks. This RTOS is widely supported in the industry and is easy enough to understand main programming concepts. Both will be used for practice and eventually for our project work. Throughout the material, you’ll find programming examples for the device, but the best way to learn is by experimenting and hands-on practice. Let’s dive in!
An operating system is software that runs applications on a computer. It has two main tasks: providing an execution environment for applications and managing the computer’s hardware resources, peripherals, and access rights. The operating system offers services to applications through interfaces and libraries, allowing them to utilize these resources—for example, memory management, file systems, peripheral device access, and data transfer from the system to external sources. Additionally, the operating system controls application execution by allocating processor time and memory among different applications. More detailed discussions on these topics are covered in later Operating Systems-course, so we’ll skip an exhaustive presentation here.
One important note: the role of the operating system is somewhat different in a microcontroller-based embedded system. On a PC, applications normally run on top of a separately installed operating system such as Windows, Linux, or macOS. The operating system manages the hardware and provides services to applications through system calls and APIs. Applications use these interfaces to access resources such as memory, files, network connections, and peripheral devices. In a microcontroller-based embedded system, the situation is different. With FreeRTOS, the RTOS kernel and the application are typically compiled together into the firmware that runs directly on the microcontroller. Instead of being a large, independent platform, it provides only the minimal set of services, such as drivers, scheduling, or libraries, that the program needs to interact with the device.
A real-time operating system provides an execution environment for applications with timing requirements. Real-time does not necessarily mean that the system is fast. Instead, it means that the system behaves predictably enough that required operations can be completed within defined deadlines. For this reason, the concept of preemption is very important: the operating system can interrupt a running task to allocate resources to another task based on different scheduling policies: mainly time-sharing and priority. The piece of software in charge of deciding which task should run is called the scheduler. The scheduler uses such policies to determine when it needs to stop the current task execution and which task should receive processor time next.
An RTOS can be lightweight, providing only a small set of services such as task scheduling and management. This lightweight design supports applications with strict real-time requirements because the operating system's own routines consume little processor time. The implementation of RTOS services significantly impacts the design, implementation, and maintenance of embedded programs.
As mentioned earlier, it is possible to program embedded systems without an operating system or device firmware. In such cases, the programmer is responsible for implementing the device’s corresponding functionalities, connecting peripheral components to the microcontroller programmatically, and implementing the necessary interfaces/services for the application.
Implementation of an embedded program¶
As mentioned in the previous C language material, modular programming makes a lot of sense and also sense when implementing computer programs. In the embedded world, it’s also sensible to divide the overall program into different tasks in a modular way, where each task’s functionality can be logically encapsulated or in other words, separated. Now, in the program, each task is defined with its own inputs to which it responds and its own outputs.
For example, in the Pico device used in the course, tasks could involve reading sensor data, updating the display, or performing serial or wireless communication. Well, these are not just examples; they are precisely the tasks we’ll implement in the project work.
Now, it makes sense to let the RTOS handle the concurrent execution of tasks to ensure efficient responsiveness. The programmer’s responsibility is to implement the actual task and define its execution parameters, considering efficiency requirements. These execution parameters include timing, priority, memory allocation, initial settings, and more. In this context, learning embedded programming involves understanding how to use these ready-made RTOS features through libraries, interfaces, and software structures.
An alternative to using an RTOS is a superloop architecture. In a superloop-based program, there is no RTOS scheduler. Instead, the application repeatedly executes its different functions inside the main loop, and the programmer is responsible for organizing when each part of the program runs. As mentioned, the superloop is an acceptable solution for small embedded systems with modest resource and performance requirements. However, it sacrifices many benefits of modularity, and the programmer might inadvertently hinder program execution. Administratively, such an approach can become a so called nightmare because even minor code changes may disrupt finely tuned timings. It’s unlikely that anyone would manually implement task prioritization within a superloop; the solution would inevitably be cumbersome. In the professional world, embedded programming is its own art form compared to general workstation programming, especially when dealing with demanding tasks, peripheral drivers, or even custom operating systems.
In addition to implementing tasks and defining execution parameters, synchronizing task behavior requires solutions. For instance, a single input (such as a button press on the device) might trigger one or multiple tasks or cause a sequence of consecutive actions across different tasks. How can such a design be achieved?
Actually, now we’re getting into the territory of the Operating Systems course, so let’s leave those matters there. However, there’s a familiar and straightforward solution from digital technology that we’ll be using in the course: state machines. We’ll use them to coordinate the behavior of different tasks in our program. The course doesn’t aim to delve deeper into the theory of state machines (which is quite extensive),
In short, the idea behind a state machine is that the logical execution of a program progresses from one state to another based on inputs, tasks, and responses. To achieve this, the program defines (at least one) state variable whose value changes according to events and corresponding tasks. Software components (read: functions) that react to tasks and events receive information about state changes and perform actions accordingly. Afterward, the state transitions to the next state, and the software components react to it again. For example, state transitions in an embedded program could look like this:
waiting state -> button press -> read sensor data -> display result/message -> waiting state
In this example, the program could have three or four different tasks: an interrupt handler that responds to button presses, a task for communicating with the sensor, a task for updating the display, and possibly a concurrent task for wireless data transfer. Perhaps even a task for preprocessing data, depending on factors like the amount of data. Now, you could certainly implement this logical functionality using a superloop, but then you’d need to consider the state of other program functionalities in each subtask—for instance, whether you’re currently communicating with peripheral devices. In the example above, we couldn’t receive messages simultaneously while reading sensor data.
Here’s an example: A state machine-based implementation of an embedded program for Arduino. Here also there is an interesting example. Even just looking at the overview on that pages is worthwhile, especially because we’ll be using a similar approach in the course. Let's present a simple example with Arduino:
enum State {
WAITING,
READ_SENSOR,
PROCESS_DATA,
DISPLAY_RESULT,
TRANSMIT_DATA
};
State currentState = WAITING;
void loop() {
switch (currentState) {
case WAITING:
if (buttonPressed()) {
currentState = READ_SENSOR;
}
break;
case READ_SENSOR:
readSensor();
currentState = PROCESS_DATA;
break;
case PROCESS_DATA:
processData();
currentState = DISPLAY_RESULT;
break;
case DISPLAY_RESULT:
displayResult();
currentState = TRANSMIT_DATA;
break;
case TRANSMIT_DATA:
transmitData();
currentState = WAITING;
break;
}
}
Well, more on this shortly.
Introduction of FreeRTOS and Pico SDK¶
In this course we are using Raspberry Pi Pico. In this course we are using Raspberry Pi Pico boards. The original Raspberry Pi Pico is based on the RP2040 microcontroller, while newer Pico 2 boards use the RP2350. In addition the Pico provides external Flash Memory, regulator and a crystal oscillator. The RP2040 architecture is shown in the following picture. It contains two ARM Cortex-M0+ processor cores, 264 KB of RAM, and different peripherals for connecting external devices.
FreeRTOS, the real-time operating system used in the course, provides the basic services needed for real-time task execution, such as task scheduling and management. Luckily, we have Pico C/C++ SDK (later only Pico SDK) maintained by Raspberry Pi. This SDK allows us to use for example the pins and peripheral devices connected to the Pico. This functionality is hidden below API (application programming interface) in various different libraries. By using these libraries, we can enable these functionalities in our program.
We will mention some of these libraries now, but the usage of them in programs will be discussed in detail in later sections of the lecture material.
(For those who are interested: Pico SDK and FreeRTOS are open-source software. This means that their source code is publicly available, so anyone can view it here and here).
The following figure presents the different components from a system perspective:
The RP2040 / RP2350 use the Pico SDK to access their peripherals. The SDK includes low-level drivers and a hardware abstraction layer (HAL) that helps the programmer use the hardware without working directly with the registers. On top of this, APIs and higher-level libraries provide more convenient functionality for building applications. FreeRTOS works alongside these components by adding task scheduling and task-management services. The user application then uses both the Pico SDK and FreeRTOS. This approach makes development significantly easier compared to bare-metal programming, where you would have to work directly with the hardware registers.
Services and libraries¶
We will use the following libraries to implement programs. Don't worry, the terms used below will be discussed in lecture material later.
- hardware_gpio A library to control the I/O pins of the microcontroller. The buttons and LEDs of the Pico are controlled using this library.
- hardware_i2c A library to use the i2c data transfer bus. Many of the devices connected to Pico can be accessed by using this library.
- hardware_uart A library for configuring and using the microcontroller's UART peripheral for serial communication. UART can be used, for example, to exchange data with another device or a PC.
- hardware_pwm A library for producing pulse width modulation (PWM) with the I/O pins of the Pico. PWM keeps the output digital, but changes how long the signal stays high and low during each cycle. By changing this duty cycle, we can control the average power delivered to a device, for example the brightness of an LED. With additional components, such as a low-pass filter, a PWM signal can also be converted into a voltage that approximates an analog output.
In the SDK most of the most impartant libraries are aggregated in the pico_stdlib library which includes among others: hardware_gpio, pico_stdio, and hardware_uart.
(For those who are interested: More information about the libraries can be found from the documentation of Pico SDK)
You can find lots of examples on programming using the Pico-SDK in the official Pico examples repository. It includes examples of FreeRTOS also.
Functionality of a program¶
Let’s take a closer look at the main function in a Pico C program. When working with FreeRTOS and the Pico SDK, the C language might initially appear cryptic due to the extensive use of predefined elements. However, understanding the code and considering what actually happens can be helpful.
In the context of Pico programming, there is a
main function from which the application starts. Before main, the startup code initializes the C runtime, for example by setting up memory sections and other low-level system state. At this point, the FreeRTOS scheduler is not yet running. Task scheduling begins only after vTaskStartScheduler() is called. We won’t delve into those startup details in this course.Below is an example of the
main-function of a FreeRTOS-program://Including the libraries of FreeRTOS and Pico
#include <FreeRTOS.h>
#include <task.h>
#include <stdio.h>
#include <pico/stdlib.h>
#include <inttypes.h>
//Includes libraries for the HAT. Not part of the SDK or FreeRTOS.
#include <TKJHAT/sdk.h>
void buttonFxn(uint gpio, uint32_t eventMask);
void taskFxn(void * pvParams);
#define STACKSIZE 1024
int main(void) {
//(en) Optional support for stdio. Start Pico input/output
stdio_init_all();
//(en) Optional, intialize the Pico HAT. This is not specific for SDK, but for the hat you are using.
init_hat();
TaskHandle_t myTaskHandle = NULL;
// (en) I/O-definition that is used to enable a push button
gpio_init(BUTTON0);
gpio_set_dir(BUTTON0, 0);
// (en) We set and interrupt handler for the button, in this case the function buttonFxn
gpio_set_irq_enabled_with_callback(BUTTON0, GPIO_IRQ_EDGE_FALL, true, buttonFxn);
// (en) We initialize one task to the application, implementation is in taskFn-function
BaseType_t result = xTaskCreate(
taskFxn,
"BUTTON_TASK",
STACKSIZE,
NULL,
1,
&myTaskHandle
);
if(result != pdPASS) {
printf("Task create failed!\n");
return 1;
}
// (en) Tell that the initialization of the device succeeded
printf("Initialization OK!\n");
// (en) Start the FreeRTOS scheduler
vTaskStartScheduler();
// Execution reaches this point only if the scheduler could not start
printf("Scheduler failed to start!\n");
return 1;
}
In C programs,
#include directives are used to include header files that provide the declarations, types, constants, and macros needed to use libraries. With FreeRTOS, several header files are typically included, and we have only shown some of them here. FreeRTOS includes also a configuration file: FreeRTOSConfig.h. We include also the libraries to use the different sensors and actuators of our TKJ HAT (more on this in future chapters). For instance the BUTTON0 is not part of the Raspberry Pi Pico hardware, but of the extension HAT that we will use in the course. In our case the librar is in TKJHAT/sdk.h.In
main we include the different intialization: I/0, HAT and peripherals (defining required I/O settings). In the example, we enable one of the push buttons and define the event handler (interrupt) for button presses, which is the function buttonFxn. Each FreeRTOS task is essentially a C function, and the rules for writing and using them are (with some reservations) the same as for regular C functions.After that, there’s room in the main function to perform other initializations to control the program’s behavior. For example, if we use timers to control task execution, we can initialize them here.
Finally, it’s a good idea to send greetings to the development environment’s console window using the debugger. This way, we can verify that the device initialization was successful. The
puts or printf function can be used to write to the console window. printf works (with minor exceptions) similarly to the standard C library’s printf function. Remember that embedded implementations of standard libraries can vary in terms of implemented features.Note that the code includes a check to ensure that the task was created successfully. Such checks are useful in embedded systems because our view of the device’s internal operation is limited. You can also used led blinking to show that the process have succeed, specially when you do not have access to console.
A common question is how the program keeps running forever if there is no infinite loop in main() like in Arduino. The reason is that once we call vTaskStartScheduler();, the FreeRTOS kernel takes control of execution. The scheduler starts the different tasks and manages how they run. Each task is typically written with its own internal infinite loop, ensuring that it continues executing as long as the scheduler is active. A common question is how the program keeps running forever if there is no infinite loop in
main() like in Arduino. Once vTaskStartScheduler() is called, the FreeRTOS scheduler takes control of execution and starts managing the tasks. Each task is typically written with its own infinite loop. If no application task is ready to run, FreeRTOS runs its idle task, so the scheduler continues operating.Conclusion¶
We’ve now covered the basics of executing programs in FreeRTOS. We’ll delve deeper into using FreeRTOS libraries in the course’s lab exercises.
The example code above may seem cryptic after the clear C language we’ve seen before. However, upon closer examination, you’ll notice that FreeRTOS code relies heavily on existing libraries, their function calls (with their own naming conventions), predefined data structures, pointers, and constants. In essence, it’s still the same C language.