Tasks, Stacks & Round-Robin Scheduling on ARM Cortex-M3/M4- Embedded C Training in Hyderabad

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

ARM Cortex-M Programming
Free Embedded C Programming Course

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.

▶ ARM Cortex-M3 / M4📚 Intermediate Level🚀 Free Course✎ Hands-On C Code

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.

T1
Stack T1
1 KB
T2
Stack T2
1 KB
T3
Stack T3
1 KB
T4
Stack T4
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:

  1. Never return — wrap all logic in while(1).
  2. No shared global state without protection — tasks run concurrently and can preempt each other at any instruction.
  3. Keep the stack small — deep call chains or large local arrays will overflow the private 1 KB stack.
  4. 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.

PSP — Process Stack Pointer
Two stacks, two modes — each pointer stays in its lane
T1T2T3T4
Each task gets its own PSP value saved in its TCB
▶ Thread Mode (CONTROL.SPSEL = 1)
MSP — Main Stack Pointer
SysTickPendSVISRs
All exception handlers share a single MSP stack
▶ Handler Mode (always MSP, regardless of CONTROL)

Separating PSP (tasks) from MSP (kernel) prevents a buggy task from corrupting the scheduler’s stack

PropertyMSP — Main Stack PointerPSP — Process Stack Pointer
Used byReset handler, all exception/ISR handlers, kernel codeUser tasks running in Thread mode
ModeHandler mode (always), Thread mode (when SPSEL=0)Thread mode only (when SPSEL=1)
Set byLinker script at startup (_estack)Scheduler at task launch (MSR psp, r0)
Corruption riskOnly if a handler overflows its stackOnly affects that one task — other tasks and kernel are safe
How to switchWrite 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)

RAM_START (0x2000_0000)RAM_END (0x2002_0000)
SchedulerMSP 1 KB
Stack T41 KB
Stack T31 KB
Stack T21 KB
Stack T11 KB
Global/heap/other RAM~123 KB remaining

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

#endif

Why 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

Task 1 Stack
T1_STACK_START (top) 0x2002_0000
Local vars
+ frame
◀ SP
T1_STACK_END (bottom)
Task 2 Stack
T2_STACK_START (top)
Local vars
+ frame
◀ SP
T2_STACK_END (bottom)

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:

Equal Time Slices

Every task gets exactly 1 ms on the CPU, regardless of what it is doing. No task can take more.

Circular Order

T1 → T2 → T3 → T4 → T1 → … repeating forever in a fixed cycle.

No Priority

All tasks are equal. No task can preempt another except via the SysTick timer interrupt.

Preemptive

The CPU is forcibly taken from the running task when SysTick fires — the task does not cooperate.

1 ms Round-Robin Timeline

T1
0 ms
►
T2
1 ms
►
T3
2 ms
►
T4
3 ms
►
T1
4 ms
►
T2
5 ms
►
…
repeats
SysTick fires every 1 ms, triggering scheduler + PendSV context switch

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?

Scheduling

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.

Context Switching

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 ComponentWhere StoredWho Saves/Restores It
r0, r1, r2, r3, r12, LR, PC, xPSRTask’s PSP stack (hardware exception frame)Hardware — automatic
r4, r5, r6, r7, r8, r9, r10, r11Task’s PSP stack (below hardware frame)PendSV handler — manual assembly
Process Stack Pointer (PSP value)Task Control Block (TCB) in RAMPendSV handler — saves updated SP to TCB
Local variables, call stackTask’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    lr

Note 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?

  1. A return 0; at the end
  2. An infinite while(1) loop
  3. A call to exit(0)
  4. A goto back 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?

  1. MSP — Main Stack Pointer
  2. PSP — Process Stack Pointer
  3. Both MSP and PSP simultaneously
  4. 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?

  1. To make the code compile faster
  2. To store local variables and the saved CPU context when the task is suspended
  3. Because Cortex-M4 does not support a shared stack
  4. 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. 1 ms
  2. 2 ms
  3. 4 ms
  4. 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?

  1. 0x00000000
  2. 0xFFFFFFFF
  3. 0x01000000
  4. 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).

Image 1 — RAM Layout Diagram “STM32F407 SRAM layout showing 5 coloured stack regions (T1-T4 + scheduler) from RAM_END downward, with sizes”

Alt: “ARM Cortex-M task stack layout in SRAM for round-robin scheduler embedded C”
Image 2 — PSP vs MSP Split “Two-column diagram: left = PSP with 4 task boxes in Thread mode, right = MSP with SysTick + PendSV in Handler mode”

Alt: “PSP vs MSP ARM Cortex-M4 task scheduler stack pointer selection”
Image 3 — Round-Robin Timeline “Horizontal timeline with 4 coloured task blocks repeating every 4 ms, SysTick tick marks at each 1 ms boundary”

Alt: “Round-robin preemptive scheduling 1ms time slice ARM Cortex-M bare metal C”

Frequently Asked Questions

What happens if a task stack overflows?

On a bare-metal Cortex-M without MPU protection, a stack overflow silently corrupts whatever data lives below the stack in RAM. This could be another task’s stack, global variables, or the heap — leading to completely unpredictable behaviour and very hard-to-debug crashes.

To detect overflow, you can use the Cortex-M MPU to mark a small “guard” region at the bottom of each stack as no-access. Any write to that region triggers a MemManage fault, giving you an early warning. FreeRTOS also offers stack watermarking: fill the stack with a known pattern (0xDEADBEEF) at creation and periodically check how far the pattern has been overwritten.

How do I choose the right stack size for each task?

The stack must hold all local variables, the deepest function call chain’s stack frames, and the 16-register exception frame saved on each preemption (64 bytes).

Start with 512 bytes–1 KB for simple tasks. Measure actual usage by filling the stack with a sentinel value and checking the high-water mark after running for a while. If your task calls printf or uses large local arrays, 2–4 KB is safer. Never allocate large arrays on the task stack — use global or dynamically allocated memory instead.

Why does the fake stack frame include LR = 0xFFFFFFFD?

When a task calls another function, LR is set to the return address by the CPU. When a task is interrupted by an exception, LR is set by the hardware to a special EXC_RETURN value (e.g. 0xFFFFFFFD) that encodes how to return to Thread mode.

We pre-fill LR with 0xFFFFFFFD in the fake frame so that if the task’s top-level function ever tries to return, it will trigger an EXC_RETURN — which will attempt to restore the exception stack frame. This is a useful way to detect a bug (task returned) rather than silently jumping to a random address. In practice you would also provide a task_exit_hook that catches this case and halts the system.

What is the difference between preemptive and cooperative scheduling?

In preemptive scheduling, the OS can forcibly remove the running task from the CPU at any time (typically on a timer interrupt). The task does not need to do anything — it is simply suspended. This is what we implement with SysTick + PendSV.

In cooperative scheduling, a task voluntarily gives up the CPU by calling a yield function. No task is ever forcibly preempted. This is simpler to implement but dangerous: a buggy task that never yields will hang the entire system. Most real RTOS designs use preemptive scheduling.

Can I add more tasks later? What is the maximum task count?

Yes. Increase TASK_COUNT, add the task entry function to the task_entries[] array, and define a new stack top address constant. The scheduler loop (current_task = (current_task + 1) % TASK_COUNT) automatically handles any number of tasks.

The maximum is limited only by available RAM. Each 1 KB stack costs 1 KB of SRAM. On an STM32F407 with 192 KB of SRAM you could run 100+ tasks, though in practice more than 20-30 tasks is unusual without a priority scheme to manage responsiveness.

How is this related to FreeRTOS or Zephyr?

FreeRTOS and Zephyr use exactly the same low-level mechanism: SysTick for the tick, PendSV for the context switch, PSP/MSP separation, and a TCB array. What they add on top is:

● Priority-based preemption (not just round-robin)
● Task blocking and unblocking (semaphores, queues, mutexes)
● Dynamic memory allocation for stacks and TCBs
● Idle task and tickless low-power mode
● Software timers, event groups, stream buffers

Building this simple scheduler from scratch is the best way to understand what FreeRTOS is doing internally. Once you grasp the basics here, reading the FreeRTOS source code (tasks.c, port.c) will make complete sense.

Why do I get a HardFault immediately when the first SysTick fires?

The most common causes are:

1. PendSV priority not set to 0xFF — if PendSV has a higher or equal priority to SysTick, it can preempt SysTick and attempt an invalid exception return, causing a UsageFault (INVPC) or HardFault.

2. xPSR Thumb bit not set — if you initialised a task stack with xPSR = 0x00000000, the CPU tries to execute in ARM mode (T=0) which is illegal on Cortex-M, causing an INVSTATE UsageFault promoted to HardFault.

3. PSP not switched before calling the first task — if you call task1_handler() without first switching CONTROL to use PSP, the task runs on MSP. When SysTick fires and PendSV tries to load the task’s PSP, it reads an uninitialised value.

4. Stack alignment — Cortex-M4 requires 8-byte stack alignment at exception entry. Ensure your stack tops are 8-byte aligned (i.e. the address is divisible by 8).

EmbeddedPathashala — Embedded Systems Programming on ARM Cortex-M3/M4

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →