一、配置步骤
1.外部中断配置
- GPIO口初始化
- 开启IO口复用时钟
- 配置中断结构体成员
- 配置NVIC分组,并使能中断
代码如下(示例):
EXTI_InitTypeDef EXTI_InitStructure = {0};
NVIC_InitTypeDef NVIC_InitStructure = {0};
Key_Init();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); //②使能 AFIO 时钟
GPIO_EXTILineConfig(GPIO_PortSourceGPIOD,GPIO_PinSource4); //中断线与IO口映射
EXTI_InitStructure.EXTI_Line = EXTI_Line4; //中断线4
EXTI_InitStructure.EXTI_LineCmd = ENABLE; //使能中断中断
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; //下降沿触发
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI4_IRQn; //中断通道2
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; //优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_Init(&NVIC_InitStructure);
2.编写中断服务函数
外部中断需要手动清除中断标志位。
代码如下(示例):
void EXTI4_IRQHandler( void )
{
if( EXTI_GetITStatus( EXTI_Line4 ) != RESET )
{
Delay_Ms(10);
if(KEY1==0)
{
LED1=!LED1;
}
EXTI_ClearITPendingBit( EXTI_Line4 ); /* Clear Flag */
}
}
总结
外部中断线0~4有单独的中断线,5-9和10-15分别公用两个中断线。系统初始化要定义一次中断优先级分组.
工程源码
PE5->LED
PD4->KEY
PA6->WCH-LINK(RX)