外部中断实验
- 外部中断首先需要进行中断初始化以及使用NVIC设置中断优先级
- 设置中断响应函数
void EXTIX_Init (void){
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
KEY_INit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
//将中断线2与GPIOE进行映射连接起来
GPIO_EXTILineConfig(GPIO_PortSourceGPIOE,GPIO_PinSource2);
//那这个IO口的中断该怎么触发呢,由EXTI_Init()进行实现
EXTI_InitStructure.EXTI_Line = EXTI_Line2;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = EMABLE;
EXTI_Init(&EXTI_InitStructure);
//将中断线3与GPIOE进行映射连接起来
GPIO_EXTILineConfig(GPIO_PortSourceGPIOE,GPIO_PinSource3);
//配置这个IO口的中断初始化
EXTI_InitStructure.EXTI_Line=EXTI_Line3;
EXTI_Init(&EXTI_InitStructure);
//将中断线4与GPIOE进行映射连接起来
GPIO_EXTILineConfig(GPIO_PortSourceGPIOE,GPIO_PinSource4);
//配置这个IO口的中断初始化
EXTI_InitStructure.EXTI_Line=EXTI_Line4;
EXTI_Init(&EXTI_InitStructure);
//将中断线0与GPIOA进行映射连接起来
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource0);
//配置这个IO口的中断初始化
EXTI_InitStructure.EXTI_Line=EXTI_Line0;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
EXTI_Init(&EXTI_InitStructure);
//中断配置完成后需要配置中断优先级,首先进行中断优先级分组,设置2位抢占优先级
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
//设置中断线0的中断优先级
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x03;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//设置中断线2中断优先级
NVIC_InitStructure.NVIC_IRQChannel = EXTI2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//设置中断线3中断优先级
NVIC_InitStructure.NVIC_IRQChannel = EXTI3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//设置中断线4中断优先级
NVIC_InitStructure.NVIC_IRQChannel = EXTI4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
到这里中断的配置以及完成,接下来需要配置中断响应函数:
首先是中断线0的响应函数:
void EXTI0_IRQHandler (void){
delay_ms(10);//消抖
if (WK_UP==1){
BEEP =! BEEP;
}
EXTI_ClearITPendingBit(EXTI_Line0); //清除LINE0上的中断标志位
}
中断线2的响应函数:
void EXTI2_IRQHandler (void){
delay_ms(10);//消抖
if (KEY2==0){
LED0=!LED0;
}
EXTI_ClearITPendingBit(EXTI_Line2); //清除LINE2上的中断标志位
}
中断线3的响应函数:
void EXTI3_IRQHandler (void){
delay_ms(10);//消抖
if (KEY1==0){
LED1=!LED1;
}
EXTI_ClearITPendingBit(EXTI_Line3); //清除LINE3上的中断标志位
}
中断线4的响应函数:
void EXTI4_IRQHandler(void)
{
delay_ms(10);//消抖
if (KEY0==0){
LED0=!LED0;
LED1=!LED1;
}
EXTI_ClearITPendingBit(EXTI_Line4); //清除LINE4上的中断标志位
}