STM32f103rct6开发板按键控制LED闪烁
时间: 2023-08-18 07:08:46 浏览: 131
STM32控制LED闪烁
以下是一个简单的按键控制 LED 闪烁的示例代码,供参考:
```c
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_8
#define LED_PORT GPIOA
#define BUTTON_PIN GPIO_Pin_0
#define BUTTON_PORT GPIOC
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
}
void BUTTON_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(BUTTON_PORT, &GPIO_InitStructure);
}
int BUTTON_GetState(void)
{
return GPIO_ReadInputDataBit(BUTTON_PORT, BUTTON_PIN);
}
void LED_SetState(int state)
{
if (state) {
GPIO_SetBits(LED_PORT, LED_PIN);
} else {
GPIO_ResetBits(LED_PORT, LED_PIN);
}
}
int main(void)
{
SystemInit();
LED_Init();
BUTTON_Init();
int led_state = 0;
int button_state = 0;
int last_button_state = 0;
while (1) {
button_state = BUTTON_GetState();
if (button_state && !last_button_state) {
led_state = !led_state;
}
LED_SetState(led_state);
last_button_state = button_state;
for (int i = 0; i < 1000000; i++) {
__NOP();
}
}
}
```
这个示例代码中在 `main` 函数中使用了一个死循环,不断检查按键状态并控制 LED 闪烁。其中使用了一个 `last_button_state` 变量来记录上一次按键的状态,以避免连续触发按键。在每次循环结束后,使用了一个简单的延时来降低 LED 闪烁频率。
阅读全文