🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

RTOS on ARM: Ports, System Ticks, and Context Switching

Microcontrollers & ARMRTOS and DebugđŸŸĸ Free Lesson

RTOS on ARM: Ports, System Ticks, and Context Switching

What You'll Learn

  • 1Explain the Cortex-M context switch sequence
  • 2Map RTOS task priorities onto NVIC priorities
  • 3Implement critical sections with the priority mask
  • 4Diagnose stack overflow and scheduling faults

Real time operating system ports for Cortex-M lean almost entirely on the architecture exception model, which is why they are compact and portable. SysTick provides the time slice, PendSV provides a deferred, lowest priority context switch, and the priority mask register provides the critical section. Tasks are just stacks with a saved register context at the top, and switching means letting the exception entry and exit machinery restore the next task. Understanding this machinery removes most of the mystery from RTOS debugging.

PendSV and the Switch Sequence

PendSV is a pendable exception that is almost always configured at the lowest priority so it runs only when nothing else needs the core. When a switch is required, software pends it, and on entry the handler saves the callee saved registers and the link register onto the current task stack, records the stack pointer in the task control block, then loads the next task stack pointer and restores its registers. Returning from the handler restores the next task as if it had been interrupted.

The special exception return value carried in the link register tells the hardware which stack to use and whether floating point state is present. Because the switch happens inside exception exit, no task ever directly manipulates another task context, which keeps the design small and hard to get wrong.

SysTick and Time Slicing

The RTOS ticks SysTick at a fixed rate, typically one hundred or one thousand hertz, and the handler increments a tick count, decrements the time slice of the running task, and pends PendSV when the slice expires. The tick also drives timeouts, software timers, and delayed reads. Tickless idle stops the periodic interrupt during long sleeps and reprograms the timer for the next deadline, which is how an RTOS stays usable on battery.

The tick rate is a trade-off: a higher rate gives finer timeouts and faster response but raises the background interrupt load, since the handler runs at every tick regardless of what the system is doing.

Priorities, Masking, and Faults

RTOS task priorities are software constructs and are completely separate from NVIC hardware priorities, but the two interact through the priority mask. Raising the mask above the highest interrupt priority creates a critical section that both task switching and interrupt handlers respect, and masking only up to a chosen level lets high rate control interrupts keep running while a kernel structure is touched. SysTick and PendSV are kept below all application interrupts for exactly this reason.

The most common failures are stack overflow and a critical section held too long. Stack canaries and a margin check at the tick catch the first, and cycle counting around kernel calls catches the second. When a fault occurs, the stacked registers and the fault status registers name the task and the instruction that failed.

RTOS Port Building Blocks

ElementARM MechanismRole
Time baseSysTickTicks, timeouts, and time slices
Context switchPendSV at lowest priorityDeferred task restore and save
Critical sectionPriority mask registerBlocks interrupts up to a level
Task stackProcess stack pointerHolds saved registers and locals
Kernel service callSupervisor call exceptionTraps into privileged kernel code
Fault handlingHard and memory management faultsNames the failing task and instruction

Real-World Examples

  • Trace a context switch — The tick handler pends PendSV, the handler saves r4 to r11 and the link register, then swaps stack pointers and returns into the next task.
  • Build a mask based critical section — Raise the priority mask above kernel priorities, touch the list, then restore the previous mask value atomically.
  • Keep control interrupts free — Map PendSV and SysTick to the lowest priority so the current control interrupt always preempts them.
  • Find a stack overflow — Enable the stack limit check or a canary pattern and inspect the task stack high water mark from the tick.

📝Task Priorities Are Not Interrupt Priorities

RTOS priorities decide which task runs; NVIC priorities decide which interrupt preemps. Confusing them produces scheduling bugs that only appear under load.

Common Mistakes

Doing critical sections by disabling interrupts globally

Fix: Use the priority mask so high rate control interrupts can still run while kernel data is protected.

Calling kernel functions from an interrupt at the wrong priority

Fix: Kernel calls from interrupts require the interrupt priority to be compatible with the masking scheme.

Ignoring stack overflow checks

Fix: Overflow corrupts the adjacent task silently and shows up as unrelated data corruption much later.

Key Takeaways

  • PendSV performs the switch during exception exit for portability and safety.
  • SysTick drives time slices, timeouts, and tickless idle.
  • The priority mask builds critical sections that cooperate with the NVIC.
  • Task priorities and interrupt priorities are separate domains that must be mapped deliberately.

Frequently Asked Questions

Why is PendSV used instead of switching in SysTick?

Deferring the switch to the lowest priority lets any pending interrupt complete first and keeps the switch out of the tick handler.

Does an RTOS make hard real time guarantees?

It gives bounded, analyzable latency only when priorities and masking are configured with worst case analysis in mind.

How much RAM does a task cost?

Each task needs its own stack, typically from a few hundred bytes to a few kilobytes, plus a small task control block.

Interview Questions

Q1: Walk through a Cortex-M RTOS context switch.

The tick pends PendSV, the handler pushes r4 to r11 and the link register on the current stack, saves the stack pointer in the task control block, loads the next task stack pointer, pops its registers, and returns using the exception return value.

Q2: How do you protect kernel data structures?

Raise the priority mask to a level above kernel work but below critical application interrupts, modify the structure, then restore the mask in one step.


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Microcontrollers & ARM Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement