Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 201 of 9363. Microcontroller Fundamentals and Bare-Metal CFree lesson

Implementing Interrupt Nesting with Priority Grouping

Configure the NVIC to allow higher-priority interrupts to preempt currently executing lower-priority interrupt service routines safely.

In this lesson, you will learn how to configure the NVIC to allow higher-priority interrupts to interrupt (preempt) lower-priority interrupts currently being serviced.

The Concept of Preemption

By default, when an Interrupt Service Routine (ISR) is running, the processor might ignore other incoming interrupts. However, in real-time systems, some tasks are more critical than others—for example, a motor emergency stop must take precedence over a periodic temperature sensor read. To achieve this, we use Priority Grouping.

The NVIC uses a split-priority system:

  1. Group Priority (Preemption Priority): Determines if an interrupt can preempt another active ISR.
  2. Sub-Priority: If two interrupts with the same Group Priority arrive simultaneously, the one with the higher sub-priority runs first.

Configuring the AirCR Register

To enable nesting, you must define the "split" point between these two fields using the Application Interrupt and Reset Control Register (AIRCR). The PRIGROUP field determines how many bits of the priority register are allocated to group priority versus sub-priority.

Once you have set this grouping, the processor automatically handles preemption. If a new interrupt arrives with a higher Group Priority than the current ISR, the NVIC suspends the current routine, saves the context, and executes the new, higher-priority task.

Example: Setting Priority Grouping

Imagine you have an 8-bit priority register. If you want 3 bits for group priority (allowing 8 levels of preemption) and 5 bits for sub-priority, you would configure the PRIGROUP value in the AIRCR register:

// Define the PRIGROUP constant for 3 bits of preemption priority
#define PRIGROUP_3_BITS_GROUP  0x05FA0400  // Example value for AIRCR register

void setup_priority_grouping(void) {
    // Writing to AIRCR requires a specific unlock key in the upper bits
    SCB->AIRCR = PRIGROUP_3_BITS_GROUP;
}

By ensuring that your critical system interrupts are assigned higher group priorities than your background tasks, you guarantee that the most important events are handled immediately, even if the system is busy processing routine data.

Key Takeaway: Priority Grouping allows you to define a hierarchy of importance, enabling the NVIC to pause low-priority work to execute time-critical tasks instantly.