embedded config_error ai_generated true

NVIC: priority grouping mismatch between ISR and main code

ID: embedded/nvic-priority-group-mismatch

Also available as: JSON · Markdown · 中文
82%Fix Rate
85%Confidence
1Evidence
2024-03-15First Seen

Root Cause

NVIC priority grouping (e.g., group vs. subpriority bits) is configured differently in interrupt handlers and the main initialization path, causing undefined behavior when nesting interrupts.

generic

中文

NVIC优先级分组(如组优先级与子优先级位数分配)在中断处理函数与主初始化路径中配置不一致,导致中断嵌套时行为未定义。

Official Documentation

https://developer.arm.com/documentation/dui0552/a/cortex-m3-peripherals/nested-vectored-interrupt-controller/priority-grouping

Workarounds

  1. 90% success Ensure NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4) is called exactly once at the start of main(), before any peripheral initialization. Example: void main(void) { NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); /* 4 bits for pre-emption, 0 for subpriority */ HAL_Init(); SystemClock_Config(); ... }
    Ensure NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4) is called exactly once at the start of main(), before any peripheral initialization. Example: void main(void) { NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); /* 4 bits for pre-emption, 0 for subpriority */ HAL_Init(); SystemClock_Config(); ... }
  2. 85% success Use a static assert to check that all modules use the same grouping. For example, in FreeRTOS, ensure configPRIO_BITS matches the hardware grouping.
    Use a static assert to check that all modules use the same grouping. For example, in FreeRTOS, ensure configPRIO_BITS matches the hardware grouping.

中文步骤

  1. Ensure NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4) is called exactly once at the start of main(), before any peripheral initialization. Example: void main(void) { NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); /* 4 bits for pre-emption, 0 for subpriority */ HAL_Init(); SystemClock_Config(); ... }
  2. Use a static assert to check that all modules use the same grouping. For example, in FreeRTOS, ensure configPRIO_BITS matches the hardware grouping.

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Disabling all interrupts globally does not fix the grouping mismatch; interrupts still fire with inconsistent priority logic.

  2. 80% fail

    Changing the grouping value inside an ISR leads to immediate hard fault or priority inversion because the NVIC state is inconsistent.