stm32按键控制led
时间: 2023-09-17 13:15:06 浏览: 24
以下是基于STM32的按键控制LED的代码示例:
```
#include "stm32f4xx.h"
#define LED_PIN GPIO_Pin_12
#define LED_PORT GPIOD
#define BUTTON_PIN GPIO_Pin_0
#define BUTTON_PORT GPIOA
int main(void)
{
// Enable clock for GPIOD and GPIOA
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD | RCC_AHB1Periph_GPIOA, ENABLE);
// Configure LED pin as output
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
// Configure button pin as input
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
GPIO_Init(BUTTON_PORT, &GPIO_InitStructure);
while (1)
{
// If button is pressed, turn on LED
if (GPIO_ReadInputDataBit(BUTTON_PORT, BUTTON_PIN) == Bit_SET)
{
GPIO_SetBits(LED_PORT, LED_PIN);
}
else
{
GPIO_ResetBits(LED_PORT, LED_PIN);
}
}
}
```
在这个示例中,我们使用了GPIO库来初始化GPIO口。我们首先启用了GPIOD和GPIOA的时钟,并将LED引脚配置为输出和按键引脚配置为输入。在while循环中,我们检测按键引脚的状态。如果它被按下,我们将LED引脚置为高电平,否则我们将LED引脚置为低电平。