给我写一个STM32按键控制LED
时间: 2024-05-14 09:16:25 浏览: 17
好的,下面是一个基本的示例代码,可以让按键控制LED:
```c
#include "stm32f10x.h"
void delay(int count)
{
int i;
for(i = 0; i < count; i++);
}
int main(void)
{
// 初始化GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
while (1)
{
// 读取按键
int key1 = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);
int key2 = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1);
if (key1 == RESET)
{
// 按下按键1,点亮LED
GPIO_SetBits(GPIOB, GPIO_Pin_5);
}
else if (key2 == RESET)
{
// 按下按键2,熄灭LED
GPIO_ResetBits(GPIOB, GPIO_Pin_5);
}
delay(50000);
}
}
```
这个示例代码使用PA0和PA1作为按键输入,PB5作为LED输出。按下PA0会点亮LED,按下PA1会熄灭LED。需要注意的是,示例代码中使用了GPIO上拉输入模式,需要接相应的电路才能正常使用。