Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Hands-On RTOS with Microcontrollers
Hands-On RTOS with Microcontrollers

Hands-On RTOS with Microcontrollers: Create high-performance, real-time embedded systems using FreeRTOS, STM32 MCUs, and SEGGER debug tools , Second Edition

eBook
AU$49.99 AU$55.99
Paperback
AU$68.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Hands-On RTOS with Microcontrollers

What is “real-time” anyway?

Real-time systems are systems that have timing requirements. A real-time system is considered to fail when it doesn’t meet a timing requirement. How a timing failure is defined (and the consequences of a failed system) can vary widely. It is extremely important to realize that real-time requirements can vary widely, both in the speed of the timing requirement and the severity of consequences if the required real-time deadlines are not met.

Every real-time system is constrained in its ability to respond to events and/or signals. A system’s ability to respond to events and/or signals is referred to as the system’s bandwidth. For example, when designing a signal acquisition chain, the system’s bandwidth for each filter stage must be wide enough to pass through the desired signal in order to maintain the integrity of the signal. If the system’s bandwidth for the filters is not properly designed, the system will fail to provide the desired real-time response to certain input signals.

The system’s hardware and software both have limited bandwidth. All software executes on hardware that has limited resources. For example, the clock frequency of an MCU limits how many instructions it can execute in a given period of time. The rate of instruction execution is also limited by the MCU architecture, which determines how many clock cycles are required to execute each instruction. The ability of the software to respond to events in real time is affected by the algorithms used, the operating system (OS) used (if any), and the effective use of the OS’s features, such as multitasking and timing features.

The limitations of the hardware and software make real-time design both challenging and fun. Challenging, because the designer often has to look into the nitty-gritty of the MCU architecture, including the hardware peripheral registers and the assembly code instructions. But fun, from the satisfaction of understanding the intricacies of how the hardware works, and from being able to write software that takes advantage of it.

It is both a science and an art to balance these limitations and to understand the trade-offs between hardware and software in order to get to the end goal of a working real-time system.

The range of timing requirements

To illustrate the range of timing requirements that can be encountered, let’s consider a few different systems that acquire readings from analog-to-digital converters (ADCs).

Let’s first look at a lower-bandwidth control system. The control system is part of a soldering iron, and the control system maintains the tip’s temperature (as seen in Figure 1.1). The parts of the system we’re concerned with are the MCU, ADC, sensor, and heater.

The MCU is the brain of the control system. It is responsible for the following:

  • Taking readings from a temperature sensor via the ADC
  • Running a closed-loop control algorithm (to maintain a constant temperature at the soldering iron tip)
  • Adjusting the output of the heater as needed

These can be seen in the following figure:

Figure 1.1: MCU-controlled soldering iron

Figure 1.1: MCU-controlled soldering iron

A typical soldering iron would have pretty low bandwidth needs. For example, since the temperature of the tip doesn’t change very quickly, the MCU may only need to acquire 50 ADC samples per second (50 Hz). The control algorithm responsible for adjusting the heater (to maintain a constant temperature) may run at an even slower pace, perhaps 5 times per second (5 Hz).

While we are here, let’s take a quick look at the timing requirements of the ADC. Doing so will give us a feel for some of the time constraints we deal with when designing real-time systems. Figure 1.2 shows a common interface between an MCU and an ADC:

Figure 1.2: MCU with external ADC

Figure 1.2: MCU with external ADC

The ADC asserts a signal to inform the MCU that the ADC has completed a conversion of the analog signal and that a digital value is ready for the MCU to read. The MCU must read the converted digital value, using the communication channel, before the next conversion takes place, or the result will be overwritten. The MCU has up to 20 ms to transfer the data from the ADC to internal memory before a new reading needs to be taken (as seen in Figure 1.3 below). The MCU also needs to be running the control algorithm to calculate the updated values for the heater output at 5 Hz (200 ms). Both of these cases (although not particularly fast) are examples of real-time requirements.

Figure 1.3: Free-running 50-Hz ADC

Figure 1.3: Free-running 50-Hz ADC

Now that we have looked at a lower-bandwidth control system, let’s consider that other control systems may require much higher bandwidth. For example, a network analyzer or oscilloscope may require reading an ADC at a rate of tens of GHz! The raw ADC readings will likely be converted into the frequency domain and graphically displayed on a high-resolution front panel dozens of times a second. To function properly, such a system requires significant data-processing bandwidth, and it must adhere to extremely tight timing requirements.

Somewhere in the middle of the possible bandwidth requirements, you’ll find systems such as closed-loop motion controllers, which will typically need to execute their proportional–integral–derivative (PID) control loops between hundreds of Hz to tens of kHz in order to provide stability in a fast-moving system. So, how fast is real-time? Well, as you can see from the ADC examples alone, it depends on the requirements.

In some of the previous cases, such as the oscilloscope or soldering iron, failure to meet a timing requirement results in poor performance or incorrect data being reported. In the case of the soldering iron, this might be poor temperature control (which could cause damage to components). For the oscilloscope, missing deadlines could cause erroneous readings, which is a failure. Too many inaccurate readings will cause the device to be viewed as unreliable, and sales will decline—all because a real-time requirement wasn’t being met consistently.

In other systems, such as the flight control of an unmanned aerial vehicle (UAV) or motion control in industrial process control, failing to run the control algorithm in a timely manner could result in something more physically catastrophic, such as a crash. In this case, the consequences are potentially life-threatening.

Thankfully, there are steps that can be taken to avoid all of these failure scenarios.

The ways of guaranteeing real-time behavior

One of the easiest ways to ensure that a system does what it is meant to do is to make sure it is as simple as possible while still meeting the requirements (some call this the KISS principle—Keep It Simple, Stupid!). This means resisting the urge to over-complicate a simple task. If a toaster is meant to toast a slice of bread, don’t put a display on it and make it tell you the weather too; just have it turn on a heating element for the right amount of time. This simple task has been accomplished for years without requiring any code or programmable devices whatsoever.

As programmers, when we encounter a problem, we tend to reach for the nearest MCU and start coding. However, some functions of a product are best handled without code at all (this is especially pertinent if a product has electro-mechanical components). A car window doesn’t really need an MCU with a polling loop to run, turning on motors through drivers and watching sensors for feedback to shut them off. This task can actually be handled by a few mechanical switches and diodes. If a feedback-reporting mechanism is required for a given system—such as an error that needs to be asserted in the case of a stuck window—then there may be no choice but to use a more complex solution. However, our goal as engineers should always be the same—solve the problem as simply as possible, without adding additional complexity.

If a problem can be solved by hardware alone, then explore that possibility with the team first before breaking out the MCU. If a problem can be handled by using a simple while loop to perform some polling of the sensor status, then simply poll the sensor for the status; there may be no need to start coding interrupt service routines (ISRs) (we will discuss these later in the book). If the functionality of the device is single-purpose, there are many cases where a full-blown RTOS can simply get in the way—so don’t use one!

Hardware and software roles in real-time systems

There are many different trade-offs when using hardware and software to achieve real-time behavior in a system. The following sections discuss the various ways hardware and software are deployed in real-time systems you might encounter. Also, note that it is possible to have combinations of the following systems working together as subsystems. These different subsystems can occur at the product, board, or even chip level (this approach is discussed in Chapter 15, Multi-Processor and Multi-Core Systems).

Hardware-only

The original real-time system is hardware-only, and it is often the best solution when there are extremely tight tolerances and/or fast timing requirements. It can be implemented with discrete digital logic, analog components, programmable logic, or an application-specific integrated component (ASIC). Other options for the hardware include programmable logic devices (PLDs), complex programmable logic devices (CPLDs), and field-programmable gate arrays (FPGAs). Hardware-based real-time systems can cover anything from analog filters, closed-loop control, and simple state machines to complex video codecs. When implemented with power saving in mind, ASICs can be made to consume less power than an MCU-based solution. In general, hardware has the advantage of performing operations in parallel and instantly (this is, of course, an over-simplification), as opposed to a single-core MCU, which only gives the illusion of parallel processing.

The downsides for real-time hardware development generally include the following:

  • The inflexibility of non-programmable devices
  • The expertise required is generally less commonly available than software/firmware developers
  • The cost of full-featured programmable devices (for example, large FPGAs)
  • The high cost of developing a custom ASIC

Bare-metal firmware

Bare-metal firmware is considered (for our purposes) to be any firmware that doesn’t use a preexisting RTOS. Instead, the designer must write firmware for the features that an RTOS would typically provide. Some engineers take this a step further, arguing that true bare-metal firmware can’t use any preexisting libraries (such as vendor-supplied hardware-abstraction libraries)—there is some merit to this view as well. A bare-metal implementation has the advantage that the user’s code has total control of all aspects of the hardware. The only way for the main-loop code execution to be interrupted is if an interrupt occurs, giving control over to an ISR. In this case, the only way for anything else to take control of the CPU is for the existing ISR to finish or for a higher-priority interrupt to occur.

Bare-metal firmware implementations excel when there is a small number of relatively simple tasks to perform—or one monolithic task. If the firmware is kept focused and best practices are followed, deterministic performance is generally easy to measure and guarantee due to the relatively small number of interactions between ISRs (or in some cases, a lack of ISRs).

In some extreme cases for heavily loaded MCUs (or MCUs that are highly constrained in ROM/RAM), bare-metal is the only option. Back when bare-metal development first started, the MCUs were highly constrained, and programming bare-metal was a necessity. However, as the silicon industry has matured, more and more memory fits inside a tiny MCU. There are now many devices available, with plenty of memory, and at a low cost, which makes it unnecessary to limit yourself to bare-metal programming. Often, it makes sense to use an RTOS, which we will explore next.

RTOS-based firmware

As bare-metal implementations become more elaborate when dealing with events asynchronously, they start to overlap with the functionality provided by an RTOS. An important consideration to keep in mind is that by using an RTOS—rather than attempting to roll your own thread-safe system—you automatically benefit from all of the testing the RTOS provider has put in.

You’ll also have the opportunity to use code that has the power of hindsight behind it—many of the RTOSes available today have been around for several years. The authors have adapted and added functionality the entire time to make the RTOSes robust and flexible for different applications. Using one of these mature RTOSes provides a high-quality starting point for your application.

RTOS-based firmware differs from bare-metal firmware in that it runs on top of a scheduling kernel on an MCU. For RTOS-based firmware, the term firmware signifies a type of RTOS that is very limited in regard to its features – typically it operates out of limited flash memory (e.g., 64KB, 256KB, etc.), and it provides a scheduling kernel for use by tasks. It is like bare-metal firmware in that the programmer often has to be very aware of the hardware peripherals and registers offered by the MCU. However, the RTOS often abstracts away some of those details and also provides timing mechanisms that the application firmware can take advantage of.

With an RTOS, having a scheduler and some RTOS primitives allows tasks to operate under the illusion that they have the processor to themselves (discussed in detail in Chapter 6, Understanding RTOS Tasks). Using an RTOS enables the system to remain responsive to the most important events while performing other complex tasks in the background.

There are a few downsides to having several tasks running on the processor. Sharing data between tasks requires the proper use of synchronization methods to avoid problems such as deadlock and priority inversion. Later in the book, we will discuss some of these synchronization methods, although it adds complexity to the code. Interrupts will generally use task signaling to take care of the interrupt as quickly as possible and defer as much processing to a task as possible. If handled properly, this solution is excellent for keeping complex systems responsive, despite many complex interactions.

RTOS-based software

RTOS-based software differs from RTOS-based firmware in that this software runs on a more full-featured RTOS. The features are similar to those found in a general-purpose OS and may include things such as hardware drivers, bootloaders, applications, filesystems, etc. In fact, some general-purpose OSes offer real-time variants (e.g., RTLinux).

These RTOSes typically require significantly more memory (e.g., 1 MB or more) and processors with specific features. For example, the RTOS may make use of the processor’s memory management unit (MMU). Also, the RTOS may provide features such as application loading and a defined driver framework. The software applications for an RTOS can be highly complex, requiring many different interactions between various internal and external systems. The advantage of using this type of RTOS is all of the capabilities that come along with it—both hardware and software.

In addition, on the hardware side, a more complex processor is often used to provide additional event-handling capacity (bandwidth) to the application. For example, there may be multiple CPU cores available running at higher clock rates. There can be GBs of RAM and persistent memory available. Adding peripheral hardware can be as simple as the addition of a card (provided there are pre-existing drivers).

On the software side, there is a plethora of open-source and vendor-proprietary solutions for networking stacks, UI development, file handling, and so on. The availability of these solutions means that certain features of the end product will require less development time to implement. Underneath all of these capabilities and options, the kernel is still implemented in such a way that the critical tasks won’t be blocked for an indefinite period of time, which is possible with a general-purpose OS. Because of this, getting deterministic performance is still within reach, just like with RTOS-based firmware.

Carefully crafted OS software

Similar to RTOS-based software, a standard OS has all of the libraries and features a developer could ask for. What’s missing, however, is a strict focus on meeting timing requirements. Generally speaking, systems implemented with a traditional OS are going to have much less deterministic behavior (and none that can be truly counted on in a safety-critical situation). For example, how many times have you sat at your PC and had a program indicate “not responding”? Now imagine if your PC also happened to be controlling the timer on your toaster – you might end up with some burnt toast!

If there is a lax real-time requirement without catastrophic consequences if a wishy-washy deadline isn’t met on time, a standard OS can be made to work, as long as care is taken in choosing what software stacks are running and their resource use is kept in check. The Linux kernel with PREEMPT_RT patches is a good example of this type of RTOS.

So, now that several of the options for achieving a real-time system with hardware and software have been laid out, it’s time to define exactly what we mean when we refer to an RTOS, specifically an MCU-based RTOS.

Defining RTOSes

An RTOS is a version of an OS that is carefully designed to offer real-time mechanisms to programmers. General-purpose OSes (such as Windows, Linux, and macOS) were created to provide a consistent programming environment that abstracts away the underlying hardware to make it easier to write and maintain computer programs. They provide application programmers with many different primitives, such as threads and mutexes.

Threads are sections of software that have their own stack and operating context. Threads are like tasks in that they run independently from each other. Mutexes are primitives offered by OSes. Mutexes provide a means for threads to synchronize their processing.

Threads (or tasks) and mutexes can be used by application software to create more complex behavior. For example, it is possible to create a multi-threaded program that provides protected access to shared data:

Figure 1.4: Multi-threaded shared memory

Figure 1.4: Multi-threaded shared memory

The preceding application doesn’t implement thread and mutex primitives, it only makes use of them. The actual implementations of threads and mutexes are handled by the OS. This has a few advantages:

  • The application code is less complex
  • It is easier to understand—the same primitives are used regardless of the programmer, making it easier to understand code created by different people
  • There is better hardware portability—with the proper precautions, the code can be run on any hardware supported by the OS without modification

In the preceding example, a mutex is used to ensure that only one thread can access the shared data at any given time. In the case of a general-purpose OS, each thread will happily wait indefinitely for the mutex to become available, before moving on to access the shared data. This is where an RTOS diverges from a general-purpose OS. In an RTOS, all blocking system calls are time-bound; instead of waiting for the mutex indefinitely, an RTOS allows a maximum delay to be specified. For example, with a general-purpose OS, if Thread 1 attempts to acquire Mutex and still doesn’t have it after 100 ms, or even 100 seconds, it will continue waiting for Mutex to become available—even if it takes forever.

In an RTOS implementation, the maximum amount of time to wait for Mutex to become available is specified by the programmer. The programmer could specify that Thread 1 must acquire Mutex within 100 ms. If Thread 1 still hasn’t received Mutex after 101 ms, Thread 1 will receive a notification that Mutex hasn’t been acquired by the specified time. This is called a timeout, and it is specified to help create a deterministic system.

An OS that provides a way of executing a given piece of code, within specified timing requirements, can be considered a real-time OS. This definition of an RTOS covers a fairly large number of systems.

There are a couple of characteristics that tend to differentiate applications that use an RTOS: how often not meeting a real-time deadline is acceptable, and the severity of not meeting a real-time deadline. The different ranges of applications that use an RTOS are usually lumped into three categories—hard, firm, and soft real-time systems.

Don’t get too hung up on the differences between hard, firm, and soft real-time systems. The definitions for these terms don’t even have unanimous agreement from within our industry. What does matter is that you know your system’s requirements and design a solution to meet them!

Hard real-time systems

A hard real-time system must meet its deadline 100% of the time. If the system does not meet a deadline, then it is considered to have failed. This doesn’t necessarily mean a failure will hurt someone if it occurs in a hard real-time system—only that the system has failed if it misses a single deadline.

The severity of a failure is generally deemed safety-critical if a failure will cause the loss of life or significant property. There are also hard real-time systems that have nothing to do with safety.

Some examples of hard real-time systems can be found in medical devices, such as pacemakers and control systems with extremely tightly controlled parameters. In the case of a pacemaker, if the pacemaker misses a deadline to administer an electrical pulse at the right moment in time, it might kill the patient (this is why pacemakers are defined as safety-critical systems).

In contrast, if a motion control system on a computer numerical control (CNC) milling machine doesn’t react to a command in time, it might plunge a tool into the wrong part of the item being machined, ruining it. In these cases that we have mentioned, one failure caused a loss of life, while the other turned some metal into scrap—but both were failures caused by a single missed deadline.

Firm real-time systems

As opposed to hard real-time systems, firm real-time systems need to hit their deadlines nearly all of the time. If video and audio lose synchronization momentarily, it probably won’t be considered a system failure, but will likely upset the consumer of the video.

In most control systems (similar to the soldering iron in a previous example), if a few samples are read slightly outside of their specified time, it is unlikely the system will be destroyed. If a control system has an ADC that automatically takes a new sample, and the MCU doesn’t read the new sample in time, it will be overwritten by a new one. This can occur occasionally, but if it happens too often, the temperature stability will be ruined. However, other systems cannot tolerate missed samples. Motor control loops, for example, might lose control of the motor if even a few samples are missed. This highlights the need for the programmer to understand the real-time requirements of the system and to design accordingly.

Soft real-time systems

Soft real-time systems are the most lax when it comes to how often the system must meet its deadlines. These systems often offer only a best-effort promise to keep deadlines. These real-time systems don’t consider it a failure when their deadlines are not met, though the user of the system might consider it an annoyance.

Cruise control in a car is a good example of a soft real-time system because there are no hard specifications or expectations of it. Drivers typically don’t expect their speed to converge to within +/- X mph/kph of the set speed, within N seconds. They expect that given reasonable circumstances, such as no large hills, the control system will eventually get them close to their desired speed most of the time. However, they might still be annoyed when they have to step on the gas to get the car to climb that large hill!

Next, we’ll look at the various types of RTOSes that are currently available, and the RTOS used in this book.

Practical real-time systems

In practice, real-time systems often have a combination of firm, hard, and soft real-time requirements. For example, the soldering iron example may have hard real-time requirements for a thermal run-away safety monitor, firm real-time requirements for the temperature measurement and control loop, and soft real-time requirements for updating the user display. Achieving this combination of real-time requirements is made easier by using an RTOS, but it requires careful attention to these constraints when designing the system.

The range of RTOSes

There are many RTOSes on the market. They range widely in their functionality, and in what processor architecture and size they’re best suited to. On the smaller side are 8-bit to 32-bit MCU-focused RTOSes, including FreeRTOS, Keil RTX, Micrium µC/OS, ThreadX, and many more. This class of RTOS is suitable for use on microcontrollers, and a compact real-time kernel is provided as the most basic offering. When moving from MCUs to 32-bit and 64-bit application processors, there are RTOSes such as Wind River VxWorks, Wind River Linux, Green Hills’ Integrity OS, and even Linux with PREEMPT_RT kernel extensions. These full-blown OSes offer a large selection of software, providing solutions for both real-time scheduling requirements as well as general computing tasks. Even with the OSes we’ve just rattled off, we’ve only scratched the surface of what’s available. There are free and paid solutions (some costing well over $10,000) at all levels of RTOSes, big and small.

So, why would you choose to pay for a solution when there is something available for free? The main differentiating factors between freely available RTOS solutions and paid solutions are safety approvals, middleware, and customer support. Because an RTOS provides a highly deterministic execution environment, they are often used in complex safety-critical applications. These systems require deterministic operation because they must behave in a predictable way all the time. Guaranteeing that the code responds to events within a fixed amount of time is a significant step toward ensuring they behave consistently. Most of these safety-critical applications are regulated and have their own sets of governing bodies and standards, such as DO-178B and DO-178C for aircraft or IEC 61508 SIL 3 and ISO 26262 ASILD for industrial applications. To make safety-critical certifications more affordable, designers typically use one of two approaches. One approach is to keep code for these systems extremely simple, and not to use an RTOS. This makes it possible to prove mathematically that the system will function consistently and nothing can go wrong. The other approach is to turn to a commercial RTOS solution, which has been through the certification process, as a starting point. For example, WITTENSTEIN SafeRTOS is a derivative of FreeRTOS that carries approvals for industrial, medical, and automotive use.

Middleware can also be an extremely important component in complex systems. Middleware is code that runs between the user code (code that you, the application programmer, write) and lower layers, such as the RTOS or bare-metal (no RTOS). A value proposition of paid solutions is that the ecosystem offers a suite of pre-integrated high-quality middleware (such as filesystems, networking stacks, GUI frameworks, industrial protocols, and so on), and it minimizes the amount of development required and reduces overall project risk.

The reason for using middleware, rather than rolling your own, is to reduce the amount of original code being written by an in-house development team. This reduces both the risk and the total time spent by the team—so it can be a worthwhile investment, depending on factors such as project complexity and schedule requirements.

Paid solutions will also typically come with some level of customer support directly from the firmware vendor. Engineers are expensive to hire and keep on staff. There’s nothing a manager dreads more than walking into a room full of engineers who are puzzling over their tools, rather than working on the real problems that need to be solved. Having expert help that is an email or phone call away., can increase a team’s productivity dramatically, which leads to a shorter turnaround and a happier workplace for everyone.

FreeRTOS has both paid support and training options, as well as paid middleware solutions that can be integrated. However, open-source and other free middleware components are also available, some of which will be discussed later in this book.

The RTOS used in this book

With all of the options available, you might be wondering: why is it that this book is only covering one RTOS on a single model of MCU? There are a few reasons, one being that most of the concepts we’ll cover are applicable to nearly any RTOS available, in the same way that good coding habits transcend the language in which you happen to be coding. By focusing on a single implementation of an RTOS with a single MCU, we’ll be able to dive into topics in more depth than would have been possible if all of the alternatives were also attempted to be discussed.

FreeRTOS is one of the most popular RTOS implementations for MCUs, and it is very widely available. It has been around for over 15 years and has been ported to dozens of platforms. If you’ve ever spoken to a true low-level embedded systems engineer who is familiar with RTOS programming, they’ve certainly heard of FreeRTOS and have likely used it at least once. By focusing our attention on FreeRTOS, you’ll be well positioned to quickly migrate your knowledge of FreeRTOS to other hardware or transition to another RTOS, if the situation calls for it.

The other reason we’re using FreeRTOS? Well, it’s FREE! FreeRTOS is distributed under the MIT license. See https://www.freertos.org/a00114.html for more details on licensing and other FreeRTOS derivatives, such as SafeRTOS and OpenRTOS.

The following is a diagram showing where FreeRTOS sits in a typical ARM firmware stack. Stack refers to all of the different layers of firmware components that make up the system and how they are stacked on top of one another. A user in this context refers to the programmer using FreeRTOS (rather than the end user of the embedded system):

Figure 1.5: Typical ARM FreeRTOS firmware stack

Figure 1.5: Typical ARM FreeRTOS firmware stack

Some noteworthy items are as follows:

  • User code is able to access the same FreeRTOS API, regardless of the underlying hardware port implementation
  • FreeRTOS does not prevent user code from using vendor-supplied drivers, the CMSIS, or raw hardware registers

Having a standardized API that is consistent across hardware means code can be easily migrated between hardware targets without being constantly rewritten. The ability to have code directly control hardware also provides the means to write extremely efficient code when necessary (at the expense of portability).

Now that we know what an RTOS is, let’s have a closer look at when it is appropriate to use an RTOS, and when it is not. And, when it is appropriate, we’ll look at determining the type of RTOS to use.

Choosing an RTOS

Occasionally, when someone first learns of the term real-time OS, they mistakenly believe that an RTOS is the only way to achieve real-time behavior in an embedded system. While this is certainly understandable (especially given the name), it couldn’t be further from the truth. Sometimes, it is best to think of an RTOS as a potential solution, rather than the solution to be used for everything. Generally speaking, for an MCU-based RTOS to be the ideal solution for a given problem, it needs to have a Goldilocks-level of complexity—not too simple, but not too complicated.

If there is an extremely simple problem, such as monitoring two states and triggering an alert when they are both present, the solution could be a straightforward hardware solution (such as an AND gate). In this case, there may be no reason to complicate things further, since the AND gate solution is going to be very fast, with high determinism and extreme reliability. It will also require very little time for development.

Now, consider a case where there are only one or two tasks to be performed, such as controlling the speed of a motor and watching an encoder to ensure the correct distance is traversed. This could certainly be implemented in discrete analog and digital hardware, but having a configurable distance would add some complexity. Additionally, tuning the control loop coefficients would likely require twiddling the potentiometer settings (possibly for each individual board), which is undesirable in some or most cases, by today’s manufacturing standards. So, on the hardware solution side, we’re left with a CPLD or an FPGA to implement the motion control algorithm and track the distance traveled. This happens to be a very good fit for either since it is potentially small enough to fit into a CPLD, but in some cases, the cost of an FPGA might be unacceptable. This problem is also handled by MCUs regularly. If existing in-house resources don’t have the expertise required with hardware languages or toolchains, then a bare-metal MCU firmware solution is probably a good fit.

Let’s say the problem is more complicated, such as a device that controls several different actuators (for example, a motor or a solenoid valve). The device reads data from a range of sensors and stores those values in local storage. Perhaps the device also needs to sit on some sort of network, such as Ethernet, Wi-Fi, a controller area network (CAN), and so on. An RTOS can solve this type of problem quite well. The fact that there are many different tasks that need to be completed, more or less asynchronously with one another, makes it very easy to argue that the additional complexity the RTOS brings will pay off.

Some RTOS tasks are lower-priority and more complex, such as networking and filesystem processing. Other tasks are time-critical, such as controlling actuators and reading sensors. The RTOS helps us to ensure the lower-priority and more complex tasks won’t interfere with the time-critical tasks. Also, in many cases, there may be some form of control system that generally benefits from being run at well-defined time intervals—a strength of the RTOS.

Consider a system similar to the previous one, but now there are multiple networking requirements, such as serving a web page, dealing with user authentication in a complex enterprise environment, and pushing files to various shared directories that require different network-based file protocols. This level of complexity can be achieved using an RTOS, but again, depending on the available team resources, this might be better left to a full-blown OS to handle (either an RTOS or a general-purpose OS) since many of the complex software stacks required already exist. Sometimes, a multi-core approach might be taken, with one of the cores running an RTOS and the other running a general-purpose OS.

By now, it is probably obvious that there is no definitive way to determine exactly which real-time solution is correct for all cases. Each project and team will have its own unique requirements, backgrounds, skill sets, and contexts that set the stage for this decision. There are many factors that go into selecting a solution to a problem; it is important to keep an open mind and choose the solution that is best for your team and project at that point in time.

Summary

In this chapter, we talked a lot about real-time systems. We defined a real-time system and gave some examples of real-time systems in the real world. At this point, you should understand how real-time systems have different timing requirements and how there are different consequences for not meeting those timing requirements.

We then looked at the ways to use hardware and software to implement real-time systems. We saw that some real-time systems can just use hardware to meet their timing requirements. On the other hand, some real-time systems can get away with just using software on a general-purpose OS. In between those extremes is the focus of this book: applications that depend on an RTOS and run on an MCU.

After better understanding real-time systems, we defined an RTOS and described how it differs from a general-purpose OS. We explored the difference between hard, firm, and soft real-time systems. It is important to remember that the timing requirements of the real-time system determine what type of RTOS is necessary to achieve the desired performance.

We discussed the types of RTOSes that are available and why FreeRTOS was chosen for this book. FreeRTOS is mature and is used widely in industry. It is also free! And, learning FreeRTOS is a way to better understand RTOSes in general.

Finally, we looked at when it is appropriate to use an RTOS, and when it is not. And, when appropriate, we looked at determining the type of RTOS to use.

Upcoming chapters show how FreeRTOS works, and how to use it. The chapters are illustrated with example programs that run on an ST development board. The next two chapters present the development board, and also, the development tools (e.g., the IDE) that we will be using to run the example programs.

Left arrow icon Right arrow icon

Key benefits

  • Understand and master RTOS concepts using the powerful STM32 platform
  • Strengthen your embedded programming skills for real-world applications
  • Explore advanced RTOS techniques to unlock innovative embedded solutions
  • All formats include a free PDF and an invitation to the Embedded System Professionals community

Description

This updated edition of Hands-On RTOS with Microcontrollers is packed with cutting-edge content to help you expand your skills and stay ahead of the curve with embedded systems development. Written by senior engineers with decades of experience in cybersecurity, operating systems (OSs), and embedded systems, it covers the role of real-time OSs in today’s time-critical applications and FreeRTOS with its key capabilities and APIs. You’ll find a detailed overview of system design (memory management), project design (MCU, IDE, and RTOS APIs), and hands-on system use as well as the system platform, dev-boards with an MCU and a debug probe, and development tools (IDE, build system, and source-code debugging). This second edition teaches you how to implement over 20 real-world embedded applications with the latest FreeRTOS features and how to optimize your code with dynamic analysis. The chapters include example programs on GitHub with detailed instructions. You’ll create and install your own FreeRTOS system on the dev-board and set up an IDE project with debugging tools. With dozens of reference manuals listed, you’ll always have ample resources for system development. By the end of this book, you’ll have the hands-on skills to design, build, and optimize embedded applications using FreeRTOS, dev-boards, and modern debugging tools.

Who is this book for?

This book is for systems programmers, embedded systems engineers, and software developers who want to learn about real-time operating systems (RTOS) and how to use FreeRTOS in their embedded system design. A basic understanding of the C programming language, embedded systems, and microcontrollers is assumed. The book also includes hardware tutorials for systems programmers.

What you will learn

  • Understand RTOS use cases, and decide when (and when not) to use real-time OS
  • Utilize the FreeRTOS scheduler to create, start, and monitor task states
  • Improve task signaling and communication using queues, semaphores, and mutexes
  • Streamline task data transfer with queues and notifications
  • Upgrade peripheral communication via UART, USB, and DMA by using drivers and ISRs
  • Enhance interface architecture with a command queue for optimized system control
  • Maximize FreeRTOS memory management with trade-off insights
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 30, 2025
Length: 570 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803237725
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Sep 30, 2025
Length: 570 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803237725
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Table of Contents

12 Chapters
Hands-On RTOS with Microcontrollers, Second Edition: Create high-performance, real-time embedded systems using FreeRTOS, STM32 MCUs and SEGGER debug tools Chevron down icon Chevron up icon
Introducing Real-Time Systems Chevron down icon Chevron up icon
Introducing the Development-Board Chevron down icon Chevron up icon
Introducing the Development Tools Chevron down icon Chevron up icon
Understanding Super-Loops Chevron down icon Chevron up icon
Implementing the Super-Loop Chevron down icon Chevron up icon
Understanding RTOS Tasks Chevron down icon Chevron up icon
Running the FreeRTOS Scheduler Chevron down icon Chevron up icon
Protecting Data and Synchronizing Tasks Chevron down icon Chevron up icon
Intertask Communication Chevron down icon Chevron up icon
Drivers and ISRs Chevron down icon Chevron up icon
Efficient Drivers and ISRs Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Abhishek Jun 26, 2025
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is well explained book and also provided clear understanding of STM32 development, tools and structure.
Subscriber review Packt
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon