What is the NVIC?
Short answer: The Nested Vectored Interrupt Controller is the interrupt controller built into every Cortex-M core. It enables and disables each external interrupt, records pending interrupts, assigns programmable priorities, lets higher-priority interrupts pre-empt lower ones (nesting), and fetches the handler address directly from the vector table (vectored), with hardware optimisations such as tail-chaining and late arrival.
What it provides
- Enable/disable per IRQ:
NVIC_EnableIRQ(USART2_IRQn),NVIC_DisableIRQ()(registersISER/ICER). - Pending state: set or clear by software (
NVIC_SetPendingIRQ,NVIC_ClearPendingIRQ), useful for testing or deferring work to a software-triggered interrupt. - Active state: which interrupts are currently running (nesting).
- Priorities: 2 bits on Cortex-M0/M0+ (4 levels), typically 3–8 bits on M3/M4/M7/M33 (e.g. 16 levels on STM32), set with
NVIC_SetPriority(). - Priority grouping into pre-emption priority and sub-priority (not on v6-M).
- Number of interrupts: up to 32 on Armv6-M, up to 240 on Armv7-M, up to 480 on Armv8-M Mainline, depending on the chip.
Typical set-up
NVIC_SetPriority(USART2_IRQn, 5); /* CMSIS shifts into the implemented bits */
NVIC_ClearPendingIRQ(USART2_IRQn); /* drop anything pending from before */
NVIC_EnableIRQ(USART2_IRQn);
USART2->CR1 |= USART_CR1_RXNEIE; /* and enable the source inside the peripheral */
An interrupt reaches the CPU only if it is enabled both in the peripheral and in the NVIC (and not masked by PRIMASK/BASEPRI).
Level vs pulse interrupts: most peripheral interrupts are level-sensitive: the line stays asserted until the peripheral's flag is cleared. If the handler does not clear it, the interrupt is taken again immediately after return.
Related: system exceptions (SysTick, PendSV, SVC, faults) are configured in the SCB (SCB->SHPR), not the NVIC. WIC (wake-up interrupt controller) lets interrupts wake the core from deep sleep when the NVIC clock is stopped. Cortex-A systems use the GIC instead.