stm32f405rgt6按键控制led灯亮灭
时间: 2023-09-18 10:07:20 浏览: 114
以下是基于STM32F405RGT6的按键控制LED灯亮灭的示例代码:
首先,需要引入STM32F4xx的头文件和宏定义:
```
#include "stm32f4xx.h"
#define LED_PIN GPIO_Pin_13
#define LED_PORT GPIOA
#define KEY_PIN GPIO_Pin_0
#define KEY_PORT GPIOA
#define KEY_EXTI_LINE EXTI_Line0
#define KEY_EXTI_PORT_SOURCE EXTI_PortSourceGPIOA
#define KEY_EXTI_PIN_SOURCE EXTI_PinSource0
#define KEY_EXTI_IRQn EXTI0_IRQn
```
然后,需要进行GPIO和EXTI的初始化:
```
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = KEY_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
GPIO_Init(KEY_PORT, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
SYSCFG_EXTILineConfig(KEY_EXTI_PORT_SOURCE, KEY_EXTI_PIN_SOURCE);
EXTI_InitStructure.EXTI_Line = KEY_EXTI_LINE;
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 = KEY_EXTI_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
```
在中断处理函数中,可以通过读取按键状态来控制LED灯的亮灭:
```
void EXTI0_IRQHandler(void)
{
if (EXTI_GetITStatus(KEY_EXTI_LINE) != RESET)
{
if (GPIO_ReadInputDataBit(KEY_PORT, KEY_PIN) == Bit_SET)
{
GPIO_SetBits(LED_PORT, LED_PIN);
}
else
{
GPIO_ResetBits(LED_PORT, LED_PIN);
}
EXTI_ClearITPendingBit(KEY_EXTI_LINE);
}
}
```
最后,在main函数中调用GPIO_Configuration函数进行初始化即可:
```
int main(void)
{
GPIO_Configuration();
while(1)
{
}
}
```
阅读全文