使用GD32 MCU的過程中,大家可能會有以下疑問:中斷優先級如何配置和使用?
本文將會為大家解析中斷優先級分組以及中斷優先級的配置使用:
- 中斷優先級分組配置
一個GD32 MCU系統需要大家明確系統中使用的中斷優先級分組,避免中斷優先級配置越界導致一些不符合預期的中斷現象。
中斷優先級分組可采用以下函數接口,其中有4個bit可用于中斷優先級分組,如果全用于搶占優先級,則可以配置0-15的優先級,如果2位用于搶占,2位用于次優先級,則搶占優先級可以配置0-3,此優先級可以配置0-3。
C
/*!\brief set the priority group\param[in] nvic_prigroup: the NVIC priority group\arg NVIC_PRIGROUP_PRE0_SUB4:0 bits for pre-emption priority 4 bits for subpriority\arg NVIC_PRIGROUP_PRE1_SUB3:1 bits for pre-emption priority 3 bits for subpriority\arg NVIC_PRIGROUP_PRE2_SUB2:2 bits for pre-emption priority 2 bits for subpriority\arg NVIC_PRIGROUP_PRE3_SUB1:3 bits for pre-emption priority 1 bits for subpriority\arg NVIC_PRIGROUP_PRE4_SUB0:4 bits for pre-emption priority 0 bits for subpriority\param[out] none\retval none
*/
void nvic_priority_group_set(uint32_t nvic_prigroup)
{/* set the priority group value */SCB->AIRCR = NVIC_AIRCR_VECTKEY_MASK | nvic_prigroup;
}
注意:如果中斷優先級配置為2位搶占和2位此優先級的話,搶占優先級配置為4(二進制為100b),優先級配置越界,實際配置進去的優先級為0,最高優先級,因而明確中斷優先級分組非常重要。 |
- 中斷優先級配置
中斷優先級配置采用以下函數。
C
/*!\brief enable NVIC request\param[in] nvic_irq: the NVIC interrupt request, detailed in IRQn_Type\param[in] nvic_irq_pre_priority: the pre-emption priority needed to set\param[in] nvic_irq_sub_priority: the subpriority needed to set\param[out] none\retval none
*/
void nvic_irq_enable(uint8_t nvic_irq, uint8_t nvic_irq_pre_priority, uint8_t nvic_irq_sub_priority)
{uint32_t temp_priority = 0x00U, temp_pre = 0x00U, temp_sub = 0x00U;/* use the priority group value to get the temp_pre and the temp_sub */if(((SCB->AIRCR) & (uint32_t)0x700U)==NVIC_PRIGROUP_PRE0_SUB4){temp_pre=0U;temp_sub=0x4U;}else if(((SCB->AIRCR) & (uint32_t)0x700U)==NVIC_PRIGROUP_PRE1_SUB3){temp_pre=1U;temp_sub=0x3U;}else if(((SCB->AIRCR) & (uint32_t)0x700U)==NVIC_PRIGROUP_PRE2_SUB2){temp_pre=2U;temp_sub=0x2U;}else if(((SCB->AIRCR) & (uint32_t)0x700U)==NVIC_PRIGROUP_PRE3_SUB1){temp_pre=3U;temp_sub=0x1U;}else if(((SCB->AIRCR) & (uint32_t)0x700U)==NVIC_PRIGROUP_PRE4_SUB0){temp_pre=4U;temp_sub=0x0U;}else{nvic_priority_group_set(NVIC_PRIGROUP_PRE2_SUB2);temp_pre=2U;temp_sub=0x2U;}/* get the temp_priority to fill the NVIC->IP register */temp_priority = (uint32_t)nvic_irq_pre_priority << (0x4U - temp_pre);temp_priority |= nvic_irq_sub_priority &(0x0FU >> (0x4U - temp_sub));temp_priority = temp_priority << 0x04U;NVIC->IP[nvic_irq] = (uint8_t)temp_priority;/* enable the selected IRQ */NVIC->ISER[nvic_irq >> 0x05U] = (uint32_t)0x01U << (nvic_irq & (uint8_t)0x1FU);
}
?nvic_irq為中斷號,中斷號可以通過gd32f30x.h獲取,如下圖所示,nvic_irq_pre_priority為搶占優先級配置,nvic_irq_sub_priority為此優先級配置,注意優先級配置要根據優先級分組進行配置,不要越界哦。
GD32MCU技術交流群:859440462
更多GD32 MCU相關咨詢:單片機開發板_國產mcu視頻_GD32 - 蘇州聚沃電子科技有限公司