🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Tasks, Stacks & Round-Robin Scheduling on ARM Cortex-M3/M4
Learn what a task really is, how to design private stacks for multiple tasks, when to use PSP vs MSP, and how to build a preemptive round-robin scheduler step by step.
1 — What Is a Task?
In bare-metal embedded programming, a task is simply a C function that runs on the CPU and performs one specific job. What makes it a task — rather than a plain function — is that it is schedulable: the OS can pause it at any point, save everything it was doing, let another task run, and resume it later as if nothing happened.
🔨
Core Identity
A Schedulable Function
A task is a C function that is designed to run forever (infinite loop). The scheduler decides when it runs, not the task itself.
💾
Private Stack
Its Own RAM Region
Every task owns a dedicated block of RAM for its stack. Local variables, function call frames, and saved CPU registers all live here.
📷
State Preservation
Never Loses Its Place
When the scheduler suspends a task, it saves the complete CPU register state onto the task’s private stack. On resume, every register is restored exactly.
♻
Lifecycle
Run Until Deleted
A task keeps its state across any number of preemptions. Only explicit deletion removes it from the scheduler permanently.
Key rule: A task must never return from its top-level function. If it does, the program counter jumps to an undefined address and the system crashes. Always wrap task code in an infinite while(1) loop.
Four Tasks Visualised
Our scheduler application uses exactly four user tasks. Each has its own dedicated stack region in SRAM. The scheduler alternates between them every 1 ms.
1 KB
1 KB
1 KB
1 KB
Each task has an independent C function body and a private 1 KB stack in SRAM
2 — Creating Four Concurrent User Tasks in C
Each task is a plain C function with an infinite loop. The important constraints are:
- Never return — wrap all logic in
while(1). - No shared global state without protection — tasks run concurrently and can preempt each other at any instruction.
- Keep the stack small — deep call chains or large local arrays will overflow the private 1 KB stack.
- Use delay loops sparingly — a busy-wait delay wastes the entire time slice; a proper RTOS uses timer-based blocking instead.
#include <stdint.h>
#include <stdio.h>
/* Simple busy-wait delay.
In a real RTOS you would use a timer-based sleep instead. */
static void delay_ms(volatile uint32_t ms)
{
/* Assumes ~168 MHz core clock; adjust multiplier for your MCU */
while (ms--) {
volatile uint32_t i = 16800;
while (i--);
}
}
/* ── Task 1: blink an LED ───────────────────────────────────────── */
void task1_handler(void)
{
while (1) {
printf("[T1] LED on\n");
delay_ms(500);
printf("[T1] LED off\n");
delay_ms(500);
}
}
/* ── Task 2: count events ───────────────────────────────────────── */
void task2_handler(void)
{
uint32_t count = 0;
while (1) {
printf("[T2] event count = %lu\n", ++count);
delay_ms(1000);
}
}
/* ── Task 3: read a sensor (simulated) ──────────────────────────── */
void task3_handler(void)
{
while (1) {
printf("[T3] temperature = 25 C\n");
delay_ms(2000);
}
}
/* ── Task 4: heartbeat monitor ─────────────────────────────────── */
void task4_handler(void)
{
while (1) {
printf("[T4] system alive\n");
delay_ms(3000);
}
}No return value, no parameters. Task functions always have the signature void task_name(void). Passing arguments into a task must be done through a Task Control Block (TCB) structure, not through function parameters.
3 — Stack Pointer Selection: PSP for Tasks, MSP for Handlers
ARM Cortex-M has two stack pointers. Choosing which one to use for tasks vs the scheduler is not optional — getting it wrong causes stack corruption and hard-to-debug crashes.
Separating PSP (tasks) from MSP (kernel) prevents a buggy task from corrupting the scheduler’s stack
| Property | MSP — Main Stack Pointer | PSP — Process Stack Pointer |
|---|---|---|
| Used by | Reset handler, all exception/ISR handlers, kernel code | User tasks running in Thread mode |
| Mode | Handler mode (always), Thread mode (when SPSEL=0) | Thread mode only (when SPSEL=1) |
| Set by | Linker script at startup (_estack) | Scheduler at task launch (MSR psp, r0) |
| Corruption risk | Only if a handler overflows its stack | Only affects that one task — other tasks and kernel are safe |
| How to switch | Write bit 1 (SPSEL) of the CONTROL register, then execute ISB | |
/*
* Call once, before the first task starts.
* Loads the initial PSP of task0 and flips CONTROL.SPSEL so that
* Thread mode uses PSP from this point onward.
* Exception handlers automatically switch to MSP — no action needed.
*/
void switch_to_psp(uint32_t initial_psp)
{
__asm volatile (
"msr psp, %0 \n" /* load PSP with task 0's initial stack top */
"mov r0, #0x02 \n" /* CONTROL = 0b10: SPSEL=1, nPRIV=0 */
"msr control, r0 \n"
"isb \n" /* instruction sync barrier — required */
: : "r"(initial_psp) : "r0", "memory"
);
}
/* Read the current PSP — used by PendSV to save the running task's stack */
static inline uint32_t get_psp(void)
{
uint32_t psp;
__asm volatile ("mrs %0, psp" : "=r"(psp));
return psp;
}
/* Write PSP — used by PendSV to restore the next task's stack */
static inline void set_psp(uint32_t psp)
{
__asm volatile ("msr psp, %0" : : "r"(psp));
}
4 — Stack Assessment: Sizing and Placing Task Stacks in RAM
Before writing a single line of scheduler code, you must answer two questions: how big is each task stack? and where in RAM does each stack live? Getting this wrong causes stack overflow — a silent, catastrophic bug on bare-metal systems with no MMU.
RAM Layout for STM32F407 (128 KB SRAM)
Five 1 KB stacks (4 tasks + scheduler MSP) placed at the top of SRAM, growing downward. Total reserved: 5 KB.
Stacks grow downward on ARM. The stack pointer starts at the top of the allocated region and decreases as items are pushed. Place the highest-address stack at RAM_END and work downward so stacks grow away from each other and toward lower addresses.
Stack Addresses in C — No Linker Script Needed
#ifndef MAIN_H
#define MAIN_H
#include <stdint.h>
/* STM32F407VGT6: SRAM ends at 0x2002_0000 (128 KB above 0x2000_0000) */
#define SRAM_END (0x20000000U + (128U * 1024U))
#define STACK_SIZE 1024U /* 1 KB per task / scheduler */
/* Stack tops — each stack starts 1 KB below the previous one */
#define T1_STACK_START SRAM_END
#define T2_STACK_START (T1_STACK_START - STACK_SIZE)
#define T3_STACK_START (T2_STACK_START - STACK_SIZE)
#define T4_STACK_START (T3_STACK_START - STACK_SIZE)
#define IDLE_STACK_START(T4_STACK_START - STACK_SIZE) /* MSP / scheduler */
/* Task IDs */
#define TASK_COUNT 4
#endifWhy define stack tops, not bottoms? On ARM the stack pointer is initialised to the top of the stack region (the highest address in the block). The CPU then decrements it on each push. Defining the top address directly is the natural way to initialise the PSP for each task.
Stack Growth Visualised
+ frame
+ frame
Both stacks grow downward independently. A crash in T2 cannot affect T1’s stack because they occupy separate SRAM regions.
5 — Scheduling Policy: Round-Robin at 1 ms per Slot
A scheduling policy decides which task runs next and for how long. We use round-robin preemptive scheduling — the simplest correct policy:
Every task gets exactly 1 ms on the CPU, regardless of what it is doing. No task can take more.
T1 → T2 → T3 → T4 → T1 → … repeating forever in a fixed cycle.
All tasks are equal. No task can preempt another except via the SysTick timer interrupt.
The CPU is forcibly taken from the running task when SysTick fires — the task does not cooperate.
1 ms Round-Robin Timeline
Each coloured block is one 1 ms time slice. Four tasks repeat in a cycle of 4 ms total.
SysTick Configuration for 1 ms
#include "stm32f4xx.h"
/*
* SysTick is a 24-bit down-counter.
* It fires an interrupt when it reaches zero, then reloads.
* Reload value = (SystemCoreClock / ticks_per_second) - 1
*
* For 168 MHz clock and 1 ms period:
* reload = (168,000,000 / 1,000) - 1 = 167,999
*/
void init_systick_1ms(void)
{
/* CMSIS helper: sets reload, resets current, enables counter + interrupt */
SysTick_Config(SystemCoreClock / 1000U);
/* Set SysTick to the highest configurable priority so it preempts tasks */
NVIC_SetPriority(SysTick_IRQn, 0);
/* PendSV at the lowest priority so the context switch runs last */
NVIC_SetPriority(PendSV_IRQn, 0xFF);
}
6 — What Is Scheduling? What Is Context Switching?
The Decision Algorithm
Scheduling is the algorithm that decides which task gets the CPU next and for how long. The decision can be based on priorities, deadlines, round-robin order, resource availability, or system load. Our implementation uses the simplest possible algorithm: next task in a fixed cycle.
The Mechanical Step
Context switching is the physical act of saving the outgoing task’s CPU register state onto its private stack and restoring the incoming task’s register state from its private stack — then returning execution to the new task. PendSV performs this step on ARM Cortex-M.
Scheduling vs context switching: Scheduling makes the decision; context switching executes it. The SysTick handler runs the scheduler (makes the decision). The PendSV handler performs the context switch (executes the decision). They are separate functions for a very good reason — see the previous lesson on why mixing them causes UsageFaults.
What “Context” Means
| Context Component | Where Stored | Who Saves/Restores It |
|---|---|---|
| r0, r1, r2, r3, r12, LR, PC, xPSR | Task’s PSP stack (hardware exception frame) | Hardware — automatic |
| r4, r5, r6, r7, r8, r9, r10, r11 | Task’s PSP stack (below hardware frame) | PendSV handler — manual assembly |
| Process Stack Pointer (PSP value) | Task Control Block (TCB) in RAM | PendSV handler — saves updated SP to TCB |
| Local variables, call stack | Task’s private stack (already there) | Implicit — no extra save needed |
7 — Full Working Example: Four Tasks with SysTick Scheduler
main.c
#include <stdint.h>
#include <stdio.h>
#include "main.h"
#include "scheduler.h"
void task1_handler(void);
void task2_handler(void);
void task3_handler(void);
void task4_handler(void);
int main(void)
{
hardware_init(); /* clock, UART, etc. */
init_scheduler_stack(IDLE_STACK_START); /* set MSP for the scheduler */
init_tasks_stack(); /* build fake frames on each task stack */
init_systick_1ms(); /* 1 ms SysTick interrupt */
switch_to_psp(); /* flip Thread mode to use PSP */
task1_handler(); /* start the first task — scheduler takes over via SysTick */
/* Never reached */
return 0;
}scheduler.c
#include "scheduler.h"
#include "main.h"
#include "stm32f4xx.h"
/* ── Task function declarations ────────────────────────────────── */
extern void task1_handler(void);
extern void task2_handler(void);
extern void task3_handler(void);
extern void task4_handler(void);
/* ── Task Control Blocks ───────────────────────────────────────── */
typedef struct {
uint32_t psp_value; /* saved stack pointer for this task */
} tcb_t;
static tcb_t user_tasks[TASK_COUNT];
static uint8_t current_task = 0;
/* Stack top addresses for each task */
static const uint32_t task_stacks[TASK_COUNT] = {
T1_STACK_START,
T2_STACK_START,
T3_STACK_START,
T4_STACK_START
};
static void (*task_entries[TASK_COUNT])(void) = {
task1_handler,
task2_handler,
task3_handler,
task4_handler
};
/*
* Build a fake Cortex-M exception frame on each task's stack so that
* PendSV can "restore" a brand-new task using the same path as a
* previously interrupted task.
*/
void init_tasks_stack(void)
{
for (int i = 0; i < TASK_COUNT; i++) {
uint32_t *sp = (uint32_t *)task_stacks[i];
/* Hardware-saved frame (exception entry pushes these) */
*--sp = 0x01000000; /* xPSR — Thumb bit set */
*--sp = (uint32_t)task_entries[i]; /* PC — task entry */
*--sp = 0xFFFFFFFDU; /* LR — EXC_RETURN */
*--sp = 0x00000000; /* r12 */
*--sp = 0x00000000; /* r3 */
*--sp = 0x00000000; /* r2 */
*--sp = 0x00000000; /* r1 */
*--sp = 0x00000000; /* r0 */
/* Manually-saved frame (PendSV pushes r4-r11) */
*--sp = 0x00000000; /* r11 */
*--sp = 0x00000000; /* r10 */
*--sp = 0x00000000; /* r9 */
*--sp = 0x00000000; /* r8 */
*--sp = 0x00000000; /* r7 */
*--sp = 0x00000000; /* r6 */
*--sp = 0x00000000; /* r5 */
*--sp = 0x00000000; /* r4 */
user_tasks[i].psp_value = (uint32_t)sp;
}
}
void init_scheduler_stack(uint32_t sched_top)
{
__asm volatile ("msr msp, %0" : : "r"(sched_top) : "memory");
}
void switch_to_psp(void)
{
/* Load PSP of the first task, then set CONTROL.SPSEL = 1 */
__asm volatile (
"ldr r0, =user_tasks \n"
"ldr r0, [r0] \n" /* r0 = user_tasks[0].psp_value */
"msr psp, r0 \n"
"mov r0, #0x02 \n" /* CONTROL: SPSEL=1, nPRIV=0 */
"msr control, r0 \n"
"isb \n"
: : : "r0", "memory"
);
}
/* Exposed to PendSV handler (accessed by assembly) */
uint32_t get_psp_of_current_task(void)
{
return user_tasks[current_task].psp_value;
}
void save_psp_of_current_task(uint32_t sp)
{
user_tasks[current_task].psp_value = sp;
}
void update_next_task(void)
{
current_task = (current_task + 1) % TASK_COUNT;
}
uint32_t get_psp_of_next_task(void)
{
return user_tasks[current_task].psp_value;
}
/* SysTick handler: only makes the scheduling decision */
void SysTick_Handler(void)
{
update_next_task();
/* Trigger PendSV to do the actual context switch */
SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk;
}pendsv.s
.syntax unified
.thumb
.extern get_psp_of_current_task
.extern save_psp_of_current_task
.extern get_psp_of_next_task
.global PendSV_Handler
.type PendSV_Handler, %function
PendSV_Handler:
@ ── 1. Save the outgoing task ──────────────────────────────────
mrs r0, psp @ r0 = current PSP
isb
@ Push callee-saved registers onto the task's stack
stmdb r0!, {r4-r11} @ decrement-before, save r4-r11
@ save_psp_of_current_task(r0) — stores updated SP in TCB
push {lr} @ preserve EXC_RETURN value
bl save_psp_of_current_task
pop {lr}
@ ── 2. Restore the incoming task ───────────────────────────────
push {lr}
bl get_psp_of_next_task @ returns new task's PSP in r0
pop {lr}
@ Pop callee-saved registers from new task's stack
ldmia r0!, {r4-r11} @ increment-after, restore r4-r11
@ Set PSP to the new task's stack pointer
msr psp, r0
isb
@ Return: 0xFFFFFFFD = Thread mode, PSP, no FP extension
bx lrNote on push/pop lr: When PendSV calls a C function via bl, LR is overwritten with the return address. We push/pop LR around each C call to preserve the original EXC_RETURN value that the CPU needs to exit the exception correctly.
Output
Expected UART Output
// Tasks interleave every 1 ms — output rate depends on delay_ms() calls
[T1] LED on
[T2] event count = 1
[T3] temperature = 25 C
[T4] system alive
[T1] LED off
[T1] LED on
[T2] event count = 2
[T3] temperature = 25 C
…
Verify the scheduler is working: All four tasks must print at their expected rates. If T1 runs but T2-T4 never print, the PendSV handler is not switching tasks. Check that PENDSVSET is being written in SysTick_Handler and that PendSV priority is set lower than SysTick.
Build Command
arm-none-eabi-gcc \
-mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard \
-O1 -g -Wall \
-T STM32F407VGTx_FLASH.ld \
main.c tasks.c scheduler.c pendsv_handler.s \
startup_stm32f407vgtx.s \
-o rtos_demo.elf
arm-none-eabi-objcopy -O binary rtos_demo.elf rtos_demo.bin
# Flash via ST-Link
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg \
-c "program rtos_demo.elf verify reset exit"
🧠 Quick Knowledge Check
1. Which C construct must every task body contain to prevent an undefined return?
- A
return 0;at the end - An infinite
while(1)loop - A call to
exit(0) - A
gotoback to main
Check Answer
Correct answer: B — An infinite while(1) loop
Every task must loop forever inside while(1). Returning from a task function leads to an undefined program counter value and a crash.
2. Which stack pointer do user tasks use in Thread mode?
- MSP — Main Stack Pointer
- PSP — Process Stack Pointer
- Both MSP and PSP simultaneously
- Whichever has more free space
Check Answer
Correct answer: B — PSP — Process Stack Pointer
Tasks use PSP (CONTROL.SPSEL = 1). Exception handlers always use MSP regardless of SPSEL. This isolation protects the kernel stack from task bugs.
3. Why does each task need its own private stack?
- To make the code compile faster
- To store local variables and the saved CPU context when the task is suspended
- Because Cortex-M4 does not support a shared stack
- To allow the task to run in privileged mode
Check Answer
Correct answer: B — To store local variables and the saved CPU context when the task is suspended
The private stack holds local variables during execution AND the saved register context (r0-r11, LR, PC, xPSR) when the task is suspended. Without a private stack, resuming a task would corrupt its local variables.
4. In a round-robin scheduler with 4 tasks and a 1 ms time slice, how long is one full cycle?
- 1 ms
- 2 ms
- 4 ms
- 8 ms
Check Answer
Correct answer: C — 4 ms
4 tasks × 1 ms per slot = 4 ms per full cycle. Task 1 therefore gets CPU time once every 4 ms.
5. What value must you store in the xPSR slot of a fake task stack frame?
- 0x00000000
- 0xFFFFFFFF
- 0x01000000
- 0xFFFFFFFD
Check Answer
Correct answer: C — 0x01000000
0x01000000 sets bit 24 — the Thumb state bit (T bit). Cortex-M always runs Thumb instructions, so T must be 1. If T=0 when the task starts, it triggers a UsageFault (INVSTATE).
Alt: “ARM Cortex-M task stack layout in SRAM for round-robin scheduler embedded C”
Alt: “PSP vs MSP ARM Cortex-M4 task scheduler stack pointer selection”
Alt: “Round-robin preemptive scheduling 1ms time slice ARM Cortex-M bare metal C”

2 Comments