STM32将中断分为5个组,组0~4。配置代码如下:
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
在标准库里,分组的定义如下:
/** @defgroup Preemption_Priority_Group * @{*/#define NVIC_PriorityGroup_0 ((uint32_t)0x700) /*!< 0 bits for pre-emption priority4 bits for subpriority */
#define NVIC_PriorityGroup_1 ((uint32_t)0x600) /*!< 1 bits for pre-emption priority3 bits for subpriority */
#define NVIC_PriorityGroup_2 ((uint32_t)0x500) /*!< 2 bits for pre-emption priority2 bits for subpriority */
#define NVIC_PriorityGroup_3 ((uint32_t)0x400) /*!< 3 bits for pre-emption priority1 bits for subpriority */
#define NVIC_PriorityGroup_4 ((uint32_t)0x300) /*!< 4 bits for pre-emption priority0 bits for subpriority */
翻译过来就是:
分组0为0位抢占优先级,4位响应优先级;
分组1为1位抢占优先级,3位响应优先级;
分组2为2位抢占优先级,2位响应优先级;
分组3为3位抢占优先级,1位响应优先级;
分组4为4位抢占优先级,0位响应优先级;
假设使用分组3,可以使用的抢占优先级为2^3=8,即0~7,代码可配置如下:
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
//NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
//NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
//NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
//NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 4;
//NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 5;
//NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 6;
//NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 7;
可以使用的响应优先级为2^1=2,即0~1,代码可配置如下:
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
//NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
优先级逻辑:
1、抢占优先级的级别高于响应优先级。即抢占优先级高的中断可以打断正在执行的优先级低的中断。
2、数值越小所代表的优先级就越高,即0为最高优先级。
3、当抢占优先级相同时,响应优先级高的不可以打断优先级低的。
4、如果两个中断的抢占优先级和响应优先级都一样,哪个中断先发生就先执行。
NVIC配置示例:
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);