Tag: m4

  • Master Exception For System Level Services in Arm Cortex Processor (2026)

    Exception For System Level Services in Arm Cortex Processor : When you’re working with ARM Cortex processors, especially in embedded systems, you’ll hear a lot about exceptions. But what are they, and how do they help your system run more smoothly — especially at the system level?

    Let’s break it down simply.

    Exception For System Level Services in Arm Cortex Processor

    What is an Exception?

    An exception is a special kind of signal that tells the processor to stop what it’s doing and do something more important first. Think of it like this:

    “Hey CPU, pause your current work. There’s something urgent to handle!”

    This could be an interrupt from hardware, a system fault, or even a software request like a system call.

    Why Are Exceptions Important in ARM Cortex?

    ARM Cortex-M processors are designed for embedded and real-time systems. Exceptions allow the processor to respond quickly to:

    • 🔌 Hardware interrupts (like GPIO or Timer events)
    • 🧱 Faults (like trying to access invalid memory)
    • 🧬 System-level services (like context switching in an RTOS)

    They help keep the system responsive, safe, and organized.

    Types of Exceptions in Cortex-M

    There are two main categories:

    1. System Exceptions (Predefined by ARM)

    These are built into the Cortex-M core itself. Examples:

    • Reset – Triggered when the system starts or restarts.
    • NMI (Non-Maskable Interrupt) – High-priority interrupt that can’t be disabled.
    • HardFault – Happens when something goes very wrong (e.g., divide by zero).
    • SVCall (Supervisor Call) – Used by the OS to switch between user/system mode.
    • PendSV – Used for context switching in RTOS (e.g., FreeRTOS).
    • SysTick – A system timer interrupt, often used for OS ticks.

    2. External Interrupts (IRQs)

    These come from outside peripherals — like buttons, UART, I2C, etc.

    System-Level Services Using Exceptions

    Here’s how exceptions help in system-level operations like OS scheduling:

    SVCall (Supervisor Call)

    When a user app needs the OS to perform a system-level task (like memory allocation), it can make a supervisor call. This triggers the SVCall exception.

    Think of it like:

    “Hey OS, please do something privileged for me.”

    PendSV (Pendable Service Call)

    The RTOS uses this to perform context switches. When it’s time to switch tasks, the OS sets PendSV as “pending”. When the CPU is ready, it runs the PendSV handler to switch tasks.

    SysTick (System Timer)

    This fires at regular intervals (e.g., every 1ms). It’s often used to keep track of time and schedule tasks in real-time operating systems.

    Simple Real-World Use Case

    Let’s say you’re building a smart fan with FreeRTOS running on a Cortex-M4:

    1. SysTick triggers every 1ms and updates the system tick.
    2. Based on tick count, the OS decides to switch to another task.
    3. It sets the PendSV exception.
    4. The processor runs the PendSV handler, which saves the current task context and switches to the next.
    5. A user app asks for memory — it triggers SVCall to request memory allocation from the kernel.

    All these system-level services run smoothly using exceptions!

    Bonus: What Happens on Errors?

    If your program does something wrong, the processor triggers:

    • HardFault
    • MemManage Fault
    • BusFault
    • UsageFault

    These exceptions protect your system and help with debugging.

    Summary

    ExceptionPurpose
    ResetSystem starts
    NMIHigh-priority external signal
    HardFaultSerious error handling
    SVCallRequest system-level services
    PendSVContext switching in RTOS
    SysTickSystem timekeeping

    ARM Cortex-Mx processors, focusing on SVC and PendSV:

    Exceptions for System-Level Services (Cortex-Mx)

    The ARM Cortex-Mx processors support various exceptions, but two key system-level service exceptions used in operating systems are:

    1. SVC (Supervisor Call) Exception

    • Purpose: Used to request privileged operations or access to system-level services from a less privileged task.
    • When Used: A user-mode application or thread generates an SVC exception using the SVC instruction.
    • Common Use Case:
      • Requesting services from the OS kernel such as:
        • Accessing peripherals
        • Managing device drivers
        • Allocating memory
    • Why Needed: Ensures that only authorized and controlled code (OS) can access critical system resources.

    📌 Example:
    User task calls SVC 0x01 → triggers an SVC exception → OS handler processes it → returns result to user task.

    2. PendSV (Pendable Service Call) Exception

    • Purpose: Designed specifically for context switching between tasks in an OS.
    • When Used: When a context switch is required, the OS sets the PendSV interrupt to pending.
    • Pendable: It is a low-priority, software-triggered exception that can be delayed until no higher-priority exceptions are active.
    • Common Use Case:
      • Task switching in RTOS (e.g., switching from Task A to Task B)
    • Why Needed: Ensures context switching doesn’t interfere with high-priority interrupts or exceptions.

    📌 Example:
    Task A finishes → OS schedules Task B → PendSV is triggered → saves Task A context & restores Task B context.

    Summary Table

    ExceptionPurposeTrigger SourceUse Case in OS
    SVCRequest system servicesSVC instructionAccessing device drivers, memory
    PendSVPerform context switchingSoftwareSwitching between tasks

    What is SVC (Supervisor Call)?

    SVC is a special instruction in the Thumb Instruction Set Architecture (ISA) of ARM Cortex-M processors.

    • When a CPU executes SVC, it causes a special exception called the SVC exception.
    • This transfers control from user code (unprivileged mode) to kernel code (privileged mode).
    • It’s like raising your hand to ask the operating system (OS) to do something you’re not allowed to do directly.

    Why Do We Use SVC?

    In embedded systems or RTOS, we often run:

    • User tasks in unprivileged mode (to protect the system)
    • Kernel code in privileged mode (can access hardware, critical memory, etc.)

    Since user code cannot access critical resources (like hardware registers or memory-mapped peripherals) directly, it uses SVC to request the OS to do so on its behalf.

    Example Uses:

    • Creating/deleting tasks
    • Accessing hardware (GPIO, UART)
    • Requesting memory allocation
    • Starting/stopping timers

    How SVC Works — Step by Step:

    Let’s break it down:

    1. The User Code Issues an SVC Instruction

    __asm("SVC #0");   // Inline Assembly — calls SVC with number 0
    
    • The #0 is the SVC number — a value used to indicate which service you’re requesting (like a function ID).
    • This instruction triggers the SVC exception.

    2. Processor Automatically Saves Context

    When the SVC is executed:

    • The processor switches to handler mode (privileged mode).
    • It pushes some registers (R0–R3, R12, LR, PC, xPSR) onto the stack to save the current context.
    • This is similar to how interrupts are handled.

    3. Processor Jumps to the SVC Handler

    The processor now jumps to the address of the SVC handler, defined in the vector table:

    void SVC_Handler(void) {
       // Kernel code handles the request here
    }
    

    4. The SVC Handler Decodes the Request

    The handler checks the SVC number used in the instruction to determine what service is requested.

    How to extract the SVC number:

    Because the number is embedded in the instruction (not passed in R0–R3), the handler must read the instruction that caused the exception:

    void SVC_Handler(void) {
        uint32_t *stack_ptr;
        uint8_t svc_number;
    
        // Get stack pointer (usually MSP or PSP depending on context)
        __asm("TST lr, #4\n"
              "ITE EQ\n"
              "MRSEQ %0, MSP\n"
              "MRSNE %0, PSP\n"
              : "=r" (stack_ptr));
    
        // Find the instruction that caused the SVC
        uint16_t *svc_instr_addr = ((uint16_t*)stack_ptr[6]) - 1;
        uint16_t svc_instr = *svc_instr_addr;
    
        // Extract the SVC number (last 8 bits)
        svc_number = (uint8_t)(svc_instr & 0xFF);
    
        switch (svc_number) {
            case 0:
                // Handle SVC #0 request
                break;
            case 1:
                // Handle SVC #1 request
                break;
            // and so on...
        }
    }
    

    5. Kernel Code Executes the Requested Service

    • After identifying the request (like start a task, turn on LED), the kernel performs the task in privileged mode.

    6. Return to User Code

    • Once the handler completes, the context is restored, and execution resumes at the next instruction after SVC.

    Key Points

    ConceptExplanation
    SVC InstructionCauses a software exception (like a controlled interrupt)
    Used ByUnprivileged user code to request services from kernel
    SVC NumberA number (0–255) passed with the SVC instruction to indicate what service is needed
    Handler NameSVC_Handler() — OS or firmware must implement this
    Privilege EscalationSwitches temporarily from user mode to privileged mode
    SecurityEnsures user tasks don’t access critical resources directly

    Analogy

    Think of it like this:

    • You are in a library (user task), and you need access to a restricted book (privileged resource).
    • You cannot go to the restricted section.
    • So, you ring a bell (SVC instruction) with a code number saying which book you want.
    • The librarian (SVC handler) checks your request and fetches the book on your behalf.

    When Is It Used in RTOS?

    • Thread switching or task management
    • Requesting kernel services from user apps
    • Accessing hardware securely
    • System calls in embedded systems without a full-fledged OS

    Summary

    ✅ SVC is a software interrupt used to safely access system-level services
    ✅ Switches from unprivileged user mode to privileged kernel mode
    ✅ The SVC handler reads the SVC number and executes the requested action
    ✅ Helps in security, task isolation, and controlled hardware access

    The SVC (Supervisor Call) exception is a mechanism used in ARM Cortex-M processors to transition from unprivileged to privileged mode or to request OS services (like system calls) from the application layer. There are two methods to trigger an SVC exception:

    1. Direct Execution of the SVC Instruction

    This is the standard and most efficient way to trigger an SVC exception.

    How it works:

    • The CPU executes an SVC instruction with an immediate value (which usually indicates the specific service requested).
    • This causes the processor to immediately enter the SVC handler, switching to Handler mode.

    Example:

    SVC #0x04   ; Assembly instruction to trigger SVC exception with immediate value 0x04
    

    In C (using inline assembly or CMSIS):

    __asm("SVC #0x04");
    

    Use Cases:

    • Used in RTOS for system calls
    • Switching from Thread mode (unprivileged) to Handler mode (privileged)

    Advantages:

    • Low latency
    • Immediate and deterministic triggering
    • Directly supported by the CPU instruction set

    2. Setting the Exception Pending Bit in SHCSR (System Handler Control and State Register)

    This is a less common and non-standard method used mainly for testing or simulation.

    How it works:

    • The System Handler Control and State Register (SHCSR) contains a bit for SVC pending (SVCALLPENDED).
    • Manually setting this bit to 1 via software tricks the processor into thinking an SVC is pending.
    • When conditions allow, the SVC handler will be called.

    Example:

    #define SCB_SHCSR (*((volatile uint32_t*)0xE000ED24))
    SCB_SHCSR |= (1 << 15);  // Set SVCALLPENDED bit manually
    
    • Bit 15 in SHCSR is SVCALLPENDED.

    Important Notes:

    • This does not immediately trigger the SVC handler.
    • The exception must be enabled, and priority levels must allow it to be serviced.
    • Not a common practice — typically used in test environments, fault injection, or debugging.

    Summary Table:

    MethodDescriptionEfficiencyUse CaseNotes
    SVC #immDirect instruction✅ HighSystem calls, privilege switchStandard and efficient
    SHCSR bitSet pending bit❌ LowTesting, debugUncommon and delayed execution

    What is SVC?

    • SVC is an instruction used in ARM Cortex-M to request a privileged system service.
    • The syntax is: SVC #<number> Example: SVC #0x20 ; Here, 0x20 is the SVC number

    Goal

    When an SVC instruction is executed, it causes a SVC exception, and the processor jumps to the SVC_Handler.
    Your task is to:

    1. Get the address of the SVC instruction that caused the exception.
    2. Read the SVC opcode at that address.
    3. Extract the SVC number from that opcode.

    What Happens During SVC?

    1. The CPU runs a line like SVC #0x05.
    2. This triggers an SVC exception.
    3. The CPU automatically saves some context (like registers) on the stack — this includes the Program Counter (PC) where it stopped, i.e., the instruction after the SVC.

    Step-by-Step Breakdown

    Step 1: Understand Stack Frame Format

    When an exception like SVC occurs, ARM Cortex-M pushes the following registers onto the stack in this order:

    OffsetRegister
    0x00R0
    0x04R1
    0x08R2
    0x0CR3
    0x10R12
    0x14LR
    0x18PC (🟢 Points to next instruction after SVC)
    0x1CxPSR

    Step 2: Get the Stack Pointer in the Handler

    void SVC_Handler(void)
    {
        __asm volatile
        (
            "TST lr, #4 \n"               // Test bit 2 of LR to know which stack (MSP or PSP)
            "ITE EQ \n"
            "MRSEQ r0, MSP \n"           // If 0: Main Stack Pointer
            "MRSNE r0, PSP \n"           // If 1: Process Stack Pointer
            "B SVC_Handler_C \n"         // Branch to C handler and pass r0
        );
    }
    

    Step 3: In C, Extract the SVC Number

    Here is the C function that receives the stack frame pointer:

    void SVC_Handler_C(uint32_t *stack_frame)
    {
        // PC is at offset 6 (index 6), because each register is 4 bytes
        uint32_t return_address = stack_frame[6];
    
        // SVC instruction is at (return_address - 2)
        // because PC points to instruction AFTER SVC
        uint16_t *svc_instruction_address = (uint16_t *)(return_address - 2);
    
        uint8_t svc_number = (uint8_t)(*svc_instruction_address & 0xFF); // SVC number is in the lower byte
    
        // Now you can use svc_number for your logic
    }
    

    Why return_address - 2?

    • On Thumb instruction set (which Cortex-M uses), SVC is a 16-bit instruction.
    • The saved PC points to the next instruction, so subtract 2 to get the SVC instruction itself.

    Example

    Suppose user code runs:

    SVC #0x23
    

    Then in the handler:

    • PC = address after SVC = 0x08000102
    • SVC instruction is at 0x08000100
    • At that memory: 0xDF23
      • 0xDF is opcode for SVC
      • 0x23 is the SVC number
    • Extract using: uint8_t svc_number = *svc_instruction_address & 0xFF; // svc_number = 0x23

    Final Summary

    StepAction
    1Determine active stack (MSP/PSP) in assembly
    2Pass stack frame pointer to C function
    3Extract PC from stack (offset 6)
    4Subtract 2 to get SVC instruction address
    5Read 16-bit value, extract lower byte for SVC number

    Full Example: Execute SVC, extract number, increment by 4 and return

    #include <stdio.h>
    #include <stdint.h>
    
    uint32_t svc_result = 0;
    
    void SVC_Handler_Main(uint32_t *stack_frame);
    
    __attribute__((naked)) void SVC_Handler(void) {
        __asm volatile (
            "TST lr, #4 \n"             // Test bit 2 of LR to find stack pointer (MSP or PSP)
            "ITE EQ \n"
            "MRSEQ r0, MSP \n"          // If 0, use MSP
            "MRSNE r0, PSP \n"          // Else, use PSP
            "B SVC_Handler_Main \n"     // Branch to handler in C
        );
    }
    
    // This function is called with the pointer to the stack frame
    void SVC_Handler_Main(uint32_t *stack_frame) {
        // Stack frame: R0, R1, R2, R3, R12, LR, PC, xPSR
        uint16_t *pc_ptr = (uint16_t *)stack_frame[6]; // PC points to next instruction after SVC
        uint8_t svc_number = ((uint8_t *)pc_ptr)[-1];  // SVC immediate is 1 byte before PC
    
        printf("SVC number: %d\n", svc_number);
    
        svc_result = svc_number + 4;
    }
    
    uint32_t call_svc(uint8_t svc_num) {
        __asm volatile (
            "mov r0, %[num]     \n"   // Move svc_num to r0 (optional for general use)
            "svc %[immediate]   \n"   // Trigger SVC
            :
            : [num] "r" (svc_num), [immediate] "I" (0x05) // SVC #5 hardcoded for demo
            : "r0"
        );
        return svc_result;
    }
    
    int main(void) {
        printf("Calling SVC now...\n");
        uint32_t result = call_svc(5);
        printf("Returned value from SVC handler: %u\n", result);
        return 0;
    }
    

    Explanation:

    • SVC_Handler: Naked function with inline assembly that determines which stack pointer was used (MSP or PSP), then passes stack pointer to SVC_Handler_Main.
    • SVC_Handler_Main: Extracts SVC number from instruction that caused the exception (using PC - 1), prints it, increments by 4, and stores in svc_result.
    • call_svc(5): Executes the svc #0x5 instruction and later returns the modified result from the handler.

    Output:

    Calling SVC now...
    SVC number: 5
    Returned value from SVC handler: 9
    

  • Master ARM Cortex-M4 Interrupt Handling (2026)

    ARM Cortex-M4 Interrupt Handling : In embedded systems, handling asynchronous events like incoming data from external devices is crucial for responsive and efficient software design. One powerful mechanism used for this purpose is interrupts. Instead of continuously polling a peripheral, the microcontroller (MCU) can be configured to automatically respond to specific events, such as data arrival in a UART (USART) buffer.

    This article walks you through the step-by-step interrupt handling process using a USART peripheral as an example. You’ll learn how the data flow, NVIC (Nested Vectored Interrupt Controller), and CPU work together to handle interrupts — from the moment a data packet arrives, to executing the interrupt service routine (ISR) that processes the data.

    Whether you’re working with ARM Cortex-M microcontrollers or just beginning your journey into embedded development, this guide will help you build a clear mental model of how peripheral interrupts operate under the hood.

    ARM Cortex-M4 Interrupt Handling

    Core Peripheral Register Regions (ARM Cortex-M)

    Address RangeCore PeripheralDescription
    0xE000E008 – 0xE000E00FSystem Control Block (SCB)Contains control and status registers like ACTLR, used for system configuration.
    0xE000E010 – 0xE000E01FSystem Timer (SysTick)A 24-bit timer that provides a simple way to generate delays or time slices.
    0xE000E100 – 0xE000E4EFNested Vectored Interrupt ControllerManages external and internal interrupt handling with programmable priorities.
    0xE000ED00 – 0xE000ED3FSystem Control Block (Extended)Additional system control and status registers including CPUID, ICSR, etc.
    0xE000ED90 – 0xE000ED93MPU Type RegisterUsed to detect if MPU is implemented. If value reads 0, then MPU is not present.
    0xE000ED90 – 0xE000EDB8Memory Protection Unit (MPU)Defines memory regions and their attributes to prevent invalid memory access.
    0xE000EF00 – 0xE000EF03NVIC (Software Trigger Interrupt Reg)Used to trigger interrupts through software.
    0xE000EF30 – 0xE000EF44Floating Point Unit (FPU)Registers and controls for the floating-point coprocessor (if supported).

    NVIC (Nested Vectored Interrupt Controller) registers in ARM Cortex-M microcontrollers.

    Explanation of Each Row

    FieldMeaning
    AddressMemory range for the register(s)
    NameName of the register
    TypeRW = Read/Write, WO = Write-Only
    Required privilegeAccess level needed (Privileged or Configurable)
    Reset valueDefault value after reset (usually all 0s = disabled)
    DescriptionPurpose and detailed usage of the register

    Registers and Their Roles

    Register NameFunction
    NVIC_ISER0 – NVIC_ISER7 (Interrupt Set-Enable Registers)Enables interrupts. Writing a 1 to a bit enables the corresponding interrupt.
    NVIC_ICER0 – NVIC_ICER7 (Interrupt Clear-Enable Registers)Disables interrupts. Writing a 1 clears (disables) the corresponding interrupt.
    NVIC_ISPR0 – NVIC_ISPR7 (Interrupt Set-Pending Registers)Sets an interrupt as pending (as if it was triggered). Used for software-triggered interrupts.
    NVIC_ICPR0 – NVIC_ICPR7 (Interrupt Clear-Pending Registers)Clears the pending status of interrupts.
    NVIC_IABR0 – NVIC_IABR7 (Interrupt Active Bit Registers)Shows which interrupts are currently active (being serviced).
    NVIC_IPR0 – NVIC_IPR59 (Interrupt Priority Registers)Sets priority for each interrupt (lower number = higher priority).
    STIR (Software Trigger Interrupt Register)Lets software trigger an interrupt manually. Write the interrupt number to trigger it.

    Privilege Levels

    • Privileged: Requires the code to run in privileged mode (usually kernel/system code).
    • Configurable: Can be accessible depending on system setup and access permissions.

    Example Use Case (Enable Interrupt #5):

    NVIC_ISER[0] = (1 << 5);  // Enable interrupt 5
    

    Example Use Case (Set Interrupt 5 as Pending):

    NVIC_ISPR[0] = (1 << 5);  // Set pending flag
    

    Example Use Case (Set Priority of Interrupt 5):

    NVIC_IPR[1] = (3 << 6);  // Priority level (varies by implementation)

    Steps to Program an MCU Peripheral Interrupt

    1. Identify the IRQ Number

    • Look up the IRQ number of the peripheral in the MCU’s vector table.
    • Example: For USART3, the IRQ number might be 39 (vendor-specific).

    📌 This IRQ number maps to an entry in the NVIC interrupt table, and it’s essential to configure it correctly.

    2. Enable the IRQ in the Processor

    • Use the NVIC_ISERx (Interrupt Set-Enable Register) to enable the IRQ number.
    • Optionally, use the NVIC_IPRx (Interrupt Priority Register) to set its priority.
    NVIC_ISER1 |= (1 << (39 % 32));       // Enable IRQ39
    NVIC_IPR9 = (3 << 6);                 // Optional: Set priority for IRQ39 (lower value = higher priority)
    

    📘 The processor won’t recognize interrupts unless they’re enabled in NVIC.

    3. Configure the Peripheral

    • Set up the peripheral (e.g., USART3) to generate an interrupt.
    • This is done through its own control/status registers (e.g., USART_CR1 for enabling RXNEIE — RX Not Empty Interrupt Enable).
    USART3->CR1 |= USART_CR1_RXNEIE;      // Enable RX interrupt for USART3
    

    4. Pending Register Behavior

    • When USART3 receives data, it automatically issues an interrupt on IRQ 39.
    • This interrupt gets logged (pended) in the NVIC_ISPRx (Interrupt Set-Pending Register).

    5. NVIC Checks Priority Before Serving

    • NVIC checks:
      • Is the IRQ enabled?
      • Is the priority of this interrupt higher than the one currently being served?
    • If yes, it triggers the Interrupt Service Routine (ISR).
    • If no, the interrupt stays pending until it becomes the highest-priority pending interrupt.

    6. Interrupt Behavior When IRQ is Disabled

    • Even if you haven’t enabled the IRQ in NVIC, the peripheral can still issue the interrupt.
    • It gets stored in the pending state.
    • When you later enable the IRQ:
      • If its priority is high enough, the ISR will execute immediately.

    Summary Flow:

    Peripheral event (e.g., USART3 receives data) -->
    Peripheral asserts IRQ (e.g., IRQ39) -->
    NVIC pends the IRQ (ISPRx) -->
    If enabled and high-priority, NVIC dispatches ISR -->
    Your code executes the ISR (Interrupt Service Routine)
    

    Interrupt Handling Flow for USART RX Data

    Step 1: Data Arrival

    • What happens: A data packet comes in from the external world and is received by the USART RX buffer.
    • Where: In the USART peripheral (e.g., USART3).
    • Why: Because a device (e.g., another MCU, terminal, etc.) is sending data over the serial line.

    Step 2: Interrupt Request Issued

    • What happens: The USART peripheral detects new data in its RX buffer and triggers an interrupt.
    • How: It asserts its IRQ line (in this case, IRQ number 39) to notify the processor.

    📌 This step depends on the fact that RX interrupt is enabled in the peripheral control register (USART_CR1).

    Step 3: NVIC Registers the Interrupt

    • What happens:
      • The IRQ 39 becomes pending in the NVIC’s pending register (ISPRx).
      • If the IRQ is enabled and has sufficient priority, NVIC prepares to handle it.
    • Visual: This is shown as the yellow box inside NVIC with a 39 marked line going into the pending register.

    Step 4: CPU Handles Interrupt

    • What happens:
      1. CPU fetches the ISR address from the vector table based on IRQ number 39.
      2. CPU jumps to the ISR (Interrupt Service Routine).
    • Note: The Program Counter (PC) is updated with the ISR address.

    Step 5: ISR Executes

    • What happens: The ISR (Interrupt Service Routine) runs.
    • What it does: It typically copies the received data from the USART RX buffer into SRAM (main memory) or processes it accordingly.

    Summary Flowchart:

    External Data → USART RX Buffer
           ↓
    USART Issues IRQ (e.g., 39)
           ↓
    NVIC Marks IRQ as Pending (if enabled)
           ↓
    CPU Fetches ISR from Vector Table
           ↓
    ISR Executes (e.g., copy data to SRAM)
    

    Developer Notes:

    • This entire flow is hardware-assisted and efficient, allowing the CPU to react quickly to events without polling.
    • You must:
      1. Enable RX interrupt in USART.
      2. Enable IRQ in NVIC.
      3. Write the correct ISR function in your firmware.

    Interrupt Priority, Preempt Priority & Sub Priority

    In embedded systems, interrupts help your program quickly respond to important events (like a button press or sensor signal) even while it’s doing something else. But what happens when two or more interrupts occur at the same time?

    That’s where priority comes in!

    What is Interrupt Priority?

    Every interrupt is assigned a priority to help the microcontroller decide which interrupt to serve first.

    👉 Higher priority interrupts get serviced before lower priority ones.

    For example:

    • If Timer1 (priority 2) and USART1 (priority 1) occur at the same time, USART1 will be handled first.

    What is Preempt Priority?

    Preempt Priority decides whether one interrupt can interrupt another that’s already running.

    🔁 If a new interrupt with higher preempt priority comes while another is running, it will preempt (pause) the running one and start executing.

    👉 Think of it like a teacher calling a more urgent student to speak even if another student is already speaking.

    What is Sub Priority?

    Sub Priority helps decide which interrupt runs first when two interrupts have the same preempt priority.

    ⚠️ Sub-priority does not cause preemption — it only helps resolve the order when two interrupts are pending with the same level.

    Example Analogy:

    InterruptPreempt PrioritySub PriorityMeaning
    USART111Medium importance
    Timer200Highest importance
    EXTI0 (button)10Medium but slightly more urgent

    Example Code: STM32 Interrupt Priority

    Let’s use STM32CubeIDE and configure priorities for 3 interrupts:

    • EXTI0 (button)
    • TIM2 (timer)
    • USART1 (serial communication)

    NVIC Priority Configuration

    // main.c or user init function
    HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2); // 2 bits for preemption, 2 for sub-priority
    
    // Set TIM2 interrupt: Highest priority
    HAL_NVIC_SetPriority(TIM2_IRQn, 0, 0); // Preempt: 0, Sub: 0
    HAL_NVIC_EnableIRQ(TIM2_IRQn);
    
    // Set EXTI0 interrupt: Mid priority
    HAL_NVIC_SetPriority(EXTI0_IRQn, 1, 0); // Preempt: 1, Sub: 0
    HAL_NVIC_EnableIRQ(EXTI0_IRQn);
    
    // Set USART1 interrupt: Lowest priority
    HAL_NVIC_SetPriority(USART1_IRQn, 1, 1); // Preempt: 1, Sub: 1
    HAL_NVIC_EnableIRQ(USART1_IRQn);
    

    ISR (Interrupt Service Routines)

    void TIM2_IRQHandler(void)
    {
        HAL_TIM_IRQHandler(&htim2);
        HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13); // Toggle LED
    }
    
    void EXTI0_IRQHandler(void)
    {
        HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
        HAL_UART_Transmit(&huart1, (uint8_t*)"EXTI0 triggered\n", 16, HAL_MAX_DELAY);
    }
    
    void USART1_IRQHandler(void)
    {
        HAL_UART_IRQHandler(&huart1);
        // Maybe echo back received data
    }
    

    Summary

    TermControlsCan Interrupt Others?Purpose
    Preempt PriorityWhether one ISR interrupts another✅ YesPreemption behavior
    Sub PriorityOrder if same preempt level❌ NoResolves conflict silently

    Notes

    • HAL_NVIC_SetPriority uses (preempt, sub) as inputs.
    • Lower number = Higher priority.
    • Priority grouping sets how bits are divided between preempt and sub.

    NVIC Interrupt Priority Configuration and Manual Triggering on STM32

    #if !defined(__SOFT_FP__) && defined(__ARM_FP)
      #warning "FPU is not initialized, but the project is compiling for an FPU. Please initialize the FPU before use."
    #endif#define IRQNO_TIMER2  28
    #define IRQNO_I2C1    31
    
    #include <stdint.h>
    #include <stdio.h>
    
    // NVIC Register Base Addresses (Cortex-M processor specific)
    uint32_t *pNVIC_IPRBase  = (uint32_t*)0xE000E400; // Priority Register
    uint32_t *pNVIC_ISERBase = (uint32_t*)0xE000E100; // Interrupt Set-Enable
    uint32_t *pNVIC_ISPRBase = (uint32_t*)0xE000E200; // Interrupt Set-Pending
    
    // Function to configure priority for a given IRQ number
    void configure_priority_for_irqs(uint8_t irq_no, uint8_t priority_value)
    {
        uint8_t iprx = irq_no / 4;
        uint32_t *ipr = pNVIC_IPRBase + iprx;
    
        uint8_t pos = (irq_no % 4) * 8;
    
        *ipr &= ~(0xFF << pos);                // Clear existing priority
        *ipr |=  ((priority_value & 0xFF) << pos);  // Set new priority
    }
    
    int main(void)
    {
        // Configure priorities
        configure_priority_for_irqs(IRQNO_TIMER2, 0x80);
        configure_priority_for_irqs(IRQNO_I2C1,  0x70);
    
        // Set TIM2 interrupt as pending
        *pNVIC_ISPRBase |= (1 << IRQNO_TIMER2);
    
        // Enable IRQs
        *pNVIC_ISERBase |= (1 << IRQNO_I2C1);
        *pNVIC_ISERBase |= (1 << IRQNO_TIMER2);
    
        while(1); // Wait here forever
    }
    
    // Timer 2 Interrupt Handler
    void TIM2_IRQHandler(void)
    {
        printf("[TIM2_IRQHandler] - Triggering I2C1 IRQ...\n");
    
        // Manually pend I2C1 interrupt from within TIM2 handler
        *pNVIC_ISPRBase |= (1 << IRQNO_I2C1);
    
        while(1); // Stay here to simulate nested interrupt scenario
    }
    
    // I2C1 Event Interrupt Handler
    void I2C1_EV_IRQHandler(void)
    {
        printf("[I2C1_EV_IRQHandler] - Nested interrupt handled.\n");
    }