本例程通过GPIO外部中断控制LED的电平翻转。每一次按键按下都会产生一个中断,在中断服务子程序中的代码去控制LED电平的翻转。与循环扫描按键不同,外部中断方式占用更小的CPU开销。
1 外部中断的初始化
void EXTIX_Init(void)
{
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
KEY_Init();
SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource5);
EXTI_InitStructure.EXTI_Line = EXTI_Line0;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
2 中断服务子程序
void EXTI0_1_IRQHandler(void)
{
for(EXTI_DELAY = 0; EXTI_DELAY < 1000; EXTI_DELAY++);
if(KEY1 == 0) {
LED1_TOGGLE();
}
EXTI_ClearFlag(EXTI_Line0);
}
3 main函数
int main(void)
{
delay_init();
LED_Init();
KEY_Init();
EXTIX_Init();
while(1) {
}
}