用STM32F407使用外部中断按键控制LED亮灭
时间: 2023-06-15 07:06:03 浏览: 108
外部中断实验_定时器_stm32f407_
首先,需要将按键接到STM32F407的外部中断输入引脚上。假设按键连接到了GPIOE的第0位引脚。
接下来,需要进行如下配置:
1. 使能GPIOE时钟
```c
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
```
2. 配置GPIOE.0为输入模式
```c
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOE, &GPIO_InitStructure);
```
3. 配置外部中断 EXTI0
```c
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_EXTILineConfig(GPIO_PortSourceGPIOE, GPIO_PinSource0);
EXTI_InitStructure.EXTI_Line = EXTI_Line0;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
```
4. 在EXTI0_IRQHandler中实现按键控制LED亮灭
```c
void EXTI0_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line0) != RESET)
{
// 读取按键状态,如果按键按下,则点亮LED
if(GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_0) == Bit_RESET)
{
GPIO_SetBits(GPIOA, GPIO_Pin_5);
}
// 否则熄灭LED
else
{
GPIO_ResetBits(GPIOA, GPIO_Pin_5);
}
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
```
在上述代码中,我们假设将LED连接到了GPIOA的第5位引脚上。在按下按键时,点亮LED;松开按键时,熄灭LED。
阅读全文