Which interrupt runs next?
Decide which pending interrupt the NVIC takes, given priorities and what is running. A medium embedded C problem (The Cortex-M exception model), run and…
medium · The Cortex-M exception model · interrupts · nvic · priorities
The Cortex-M NVIC decides which pending interrupt runs next:
- a lower priority number means more urgent,
- a pending interrupt preempts the running one only if its priority number is strictly lower than the running priority; equal priority waits,
- among pending interrupts with the same priority, the lowest IRQ number wins.
Write next_irq(prio, pending, running): prio[i] is IRQ i's priority (IRQs 0 to 31), pending has bit i set if IRQ i is pending, and running is the priority of what is executing now (256 for thread mode, when no interrupt runs). Return the IRQ that is taken now, or -1 if none can run yet.
Starter code
int next_irq(const uint8_t *prio, uint32_t pending, int running) {
(void)prio; (void)running;
for (int i = 0; i < 32; i++) if (pending & (1u << i)) return i;
return -1;
}Example tests
From thread mode
uint8_t prio[32] = {0};
prio[3] = 5; prio[7] = 2; prio[9] = 2;
show(prio, (1u << 3) | (1u << 7) | (1u << 9), 256);Expected output:
pending 0x00000288, running 256: 7Preemption needs a lower number
uint8_t prio[32] = {0};
prio[4] = 3; prio[6] = 1;
show(prio, 1u << 4, 3);
show(prio, 1u << 6, 3);Expected output:
pending 0x00000010, running 3: -1
pending 0x00000040, running 3: 6Learn it first
- The Cortex-M exception model · Faults, SVC and PendSV, MSP and PSP, EXC_RETURN and fault handlers.