中断初始化配置的五个步骤
1.初始化RCC和GPIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource0);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource1);
2.配置EXTILine
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource0);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource1);
3.初始化EXTI
EXTI_InitTypeDef EXTI_InitStructure;
EXTI_InitStructure.EXTI_Line = EXTI_Line0 | EXTI_Line1;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; // 选择中断触发或者事件触发:中断触发
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; // 触发边沿:上升沿
EXTI_Init(&EXTI_InitStructure);
4.选择中断组
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); // 选择中断组2 (0-3响应,0-3抢占)
5.初始化NVIC
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStructure);
2.编写中断函数
void EXTI0_IRQHandler(void)
{
/* 判断触发中断触发 */
if (EXTI_GetITStatus(EXTI_Line0) == SET)
{
/* 读取指定引脚电平 */
if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == 0)
{
/* 判断反转 */
if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 0)
{
Encoder_Count--;
}
}
/* 清除中断标志位,避免一直在中断函数中跳转 */
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
注意:系统识别中断触发是靠寄存器,这里的库函数用于读取寄存器的状态和清除寄存器的状态。