Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Hard
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction 

FreeRTOS is an open-source real-time operating system (RTOS) for embedded systems (pronounced "free-arr-toss"). FreeRTOS is supposed to be "compact, simple, and easy to use" and supports a variety of architectures and compiler toolchains.

FreeRTOS has been in active development since Richard Barry began working on it in 2002. The primary function of FreeRTOS, like all operating systems, is to execute tasks. Prioritising, scheduling, and running user-defined tasks make up the majority of FreeRTOS' code. FreeRTOS is a real-time operating system that works on embedded platforms, unlike all other operating systems.

What is "Embedded" and "Real-Time"?

An embedded system, such as the system in a TV remote control, in-car GPS, digital watch, or pacemaker, is a computer system that is designed to do only a few functions. Embedded systems are usually smaller and slower than general-purpose computers, as well as being less expensive. A low-end embedded system might feature an 8-bit CPU running at 25MHz, a few KB of RAM, and possibly 32KB of flash memory. A higher-end embedded system might feature a 750MHz 32-bit CPU, 1 GB of RAM, and several GB of flash memory.

Real-time systems are built to do something in a specific period of time, ensuring that things happen when they should.

A great example of a real-time embedded system is a pacemaker. To keep you alive, a pacemaker must contract the heart muscle at the appropriate time; it cannot be too busy to respond in time. Pacemakers and other real-time embedded devices are meticulously engineered to complete duties on time.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Architecture Overview

FreeRTOS is a little piece of software. FreeRTOS has a minimum score of a little under 9000 lines of code, including comments and blank lines, with just three sources (.c) files and a few header files. The average binary code picture is less than 10KB in size. The code of FreeRTOS is divided into three sections: tasks, communication, and hardware interfacing.

Tasks: Almost half of FreeRTOS' core code is dedicated to task management, which is a significant concern in many operating systems. A task is a priority-based user-defined C function. The primary lifting for creating, scheduling, and maintaining tasks is done by tasks.c and task.h.

Communication: Tasks are useful, but tasks that can interact with one another are even more so! This brings us to FreeRTOS' second task: communication. Communication accounts for about 40% of FreeRTOS' main code. FreeRTOS communication is handled by a queue.c and queue.h. Queues are used by tasks and interrupts to transfer data and to signify the use of essential resources via semaphores and mutexes.

The Hardware Whisperer: The roughly 9000 lines of code that make up the foundation of FreeRTOS are hardware agnostic; the same code executes whether FreeRTOS is running on an 8051 or the newest, flashiest ARM core. Approximately 6% of the FreeRTOS core code serves as a shim between the hardware-independent FreeRTOS core and the hardware-dependent code. The hardware-dependent code will be discussed in the following section.

Hardware considerations

On top of a hardware-dependent layer, the hardware-independent FreeRTOS layer rests. This hardware-dependent layer knows how to communicate with any chip architecture. The figure depicts the layers of FreeRTOS.

                               

FreeRTOS includes all of the hardware-independent and hardware-dependent code needed to get a system up and running. It works with a variety of compilers (CodeWarrior, GCC, IAR, and others) and processor architectures (ARM7, ARM Cortex-M3, various PICs, Silicon Labs 8051, x86, etc.). A list of supported architectures and compilers may be found on the FreeRTOS website.

FreeRTOS is designed to be very configurable. FreeRTOS can be developed as a single-processor, bare-bones RTOS that only supports a few tasks or as a multicore beast with TCP/IP, a file system, and USB.

Various #defines in FreeRTOSConfig.h are used to select configuration options. This file allows you to customise clock speed, heap size, mutexes, and API subsets, among other things. Here are some examples of how to configure the maximum number of task priority levels, CPU frequency, system tick frequency, minimal stack size, and total heap size:

 

#define configMAX_PRIORITIES      ( ( unsigned portBASE_TYPE ) 5 )
#define configCPU_CLOCK_HZ        ( 12000000UL )
#define configTICK_RATE_HZ        ( ( portTickType ) 1000 )
#define configMINIMAL_STACK_SIZE  ( ( unsigned short ) 100 )
#define configTOTAL_HEAP_SIZE     ( ( size_t ) ( 4 * 1024 ) )

Scheduling Tasks

Each task has a priority that ranges from 0 (lowest priority) to configMAX PRIORITIES-1 (highest priority) (the highest priority). If configMAX PRIORITIES is set to 5, FreeRTOS will employ five priority levels: 0 (lowest priority), 1, 2, 3, and 4 (highest priority) (highest priority).

To keep track of all jobs that are now ready to run, FreeRTOS employs a "ready list." It uses an array of task lists to implement the ready list:

static xList pxReadyTasksLists[ configMAX_PRIORITIES ];  /* Prioritised ready tasks.  */

The System Tick

The system tick is the heartbeat of a FreeRTOS system. The system is set up in FreeRTOS to generate a periodic tick interrupt. The tick interrupt frequency, which is normally in the millisecond range, can be configured by the user. The vTaskSwitchContext() function is called every time the tick interrupt triggers. vTaskSwitchContext() finds the highest-priority ready task and stores it in the pxCurrentTCB variable as follows:

/* Find the highest-priority queue that contains ready tasks. */
while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopReadyPriority ] ) ) )
{
    configASSERT( uxTopReadyPriority );
    --uxTopReadyPriority;
}

/* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the tasks of the same
priority get an equal share of the processor time. */
listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopReadyPriority ] ) );

uxTopReadyPriority is guaranteed to be greater than or equal to the priority of the highest-priority ready job before the while loop starts. The while() loop starts at the uxTopReadyPriority priority level and traverses down the pxReadyTasksLists[] array to identify the highest-priority level with ready jobs. The following ready task from that priority level's ready list is subsequently grabbed by listGET OWNER OF NEXT ENTRY().

When vTaskSwitchContext() returns, the hardware-dependent code starts performing that job and pxCurrentTCB points to the highest-priority task.

These nine lines of code form the foundation of FreeRTOS. The remaining 8900+ lines of FreeRTOS are there to ensure that those fine lines are all that's required to keep the most critical task going.

A high-level representation of a ready list is shown below. With one priority 0 task, no priority 1 tasks, and three priority 2 tasks, this sample has three priority levels.

 

   

Let's get into the details now that we've covered the high-level overview. Tasks, lists, and queues are the three basic data structures in FreeRTOS.

Semaphores and Mutexes

Queues are used by FreeRTOS to communicate between and among jobs. Semaphores and mutexes are also implemented in FreeRTOS via queues.

What's The Difference?

Although semaphores and mutexes seem similar, they are not the same thing. They're implemented similarly in FreeRTOS, but they're meant to be utilized in various ways. What are the different ways they should be used? A semaphore should only be used to transition from one task to another. Each process that uses the shared resource that a mutex protects is supposed to take and release it in that sequence. Tasks that use semaphores, on the other hand, either signal ["send" in FreeRTOS terms] or wait ["receive" in FreeRTOS terms].A mutex is a shared resource protection mechanism. A task gets a mutex, utilizes the shared resource, and then releases it. While a mutex is being held by another job, no task can obtain it. This ensures that a shared resource can only be used by one task at a time.

One task uses semaphores to signal another task.

Frequently Asked Questions

What can you do with FreeRTOS?

FreeRTOS provides methods for multiple threads or tasks, mutexes, semaphores and software timers. A tickless mode is provided for low power applications. Thread priorities are supported.

Is FreeRTOS hard in real-time?

It may take some adaptation – but a FreeRTOS kernel should work in hard real-time. Things such as timer tick(s), interrupt latency, real hardware performance, etc. (it's a long list) have to be examined to see if the system is capable of hard real-time.

When should I use FreeRTOS?

A job can use FreeRTOS to block on events, whether they are temporal or external to the system. This means no time is wasted polling or checking timers when there are no events that need to be processed. This can result in significant reductions in CPU usage. Code only runs when it is required.

Is FreeRTOS secure?

FreeRTOS has achieved PSA Functional API Certification using TF-M. TF-M provides a set of secure services – Crypto, Attestation and Secure Storage. It also provides secure boot through a 2nd stage bootloader based on mcuboot for authenticating runtime images and updates of the platform.

Conclusion

So, in a nutshell, we read about FreeRTOS and how it implements certain things but there are a lot of things which can be learnt more about this as knowing about a whole OS is a great learning curve.  

Check out our Coding Ninjas Studio Guided Path to learn about Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and more, Take a look at the mock test series and participate in the contests hosted by Coding Ninjas Studio if you want to improve your coding skills. If you are new to preparation and want to work for firms such as Amazon, Microsoft, Uber, and others, you should review the problemsinterview experiences, and interview bundle for placement preparations.

Consider taking one of our paid courses to give yourself and your profession an edge!

Please vote for our blogs if you find them valuable and exciting.

Happy Learning!!

Topics covered
1.
Introduction 
2.
What is "Embedded" and "Real-Time"?
3.
Architecture Overview
3.1.
Hardware considerations
4.
Scheduling Tasks
4.1.
The System Tick
5.
Semaphores and Mutexes
5.1.
What's The Difference?
6.
Frequently Asked Questions
6.1.
What can you do with FreeRTOS?
6.2.
Is FreeRTOS hard in real-time?
6.3.
When should I use FreeRTOS?
6.4.
Is FreeRTOS secure?
7.
Conclusion