写一个stm32按键控制流水灯的代码
时间: 2024-09-21 20:07:57 浏览: 162
可以参考以下代码实现stm32按键控制流水灯:
引用:key.h 中:
```
#ifndef __KEY_H
#define __KEY_H
#include "sys.h"
#define KEY0 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4)//读取按键0
#define KEY1 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3)//读取按键1
#define WK_UP GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)//读取按键3(WK_UP)
#define KEY0_PRES 1 //KEY0按下
#define KEY1_PRES 2 //KEY1按下
#define WKUP_PRES 3 //KEY_UP按下(即WK_UP/KEY_UP)
void KEY_Init(void);//IO初始化
u8 KEY_Scan(u8); //按键扫描函数
#endif
```
引用:main.c中:
```
#include "led.h"
#include "delay.h"
#include "key.h"
#include "sys.h"
#include "usart.h"
#include "exti.h"
#include "beep.h"
int main(void)
{
delay_init(); //延时函数初始化
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
uart_init(115200); //串口初始化为115200
LED_Init(); //初始化与LED连接的硬件接口
BEEP_Init(); //初始化蜂鸣器IO
EXTIX_Init(); //初始化外部中断输入
LED0=0; //先点亮红灯
while(1)
{
if(KEY_Scan(0) == KEY0_PRES) //按键0按下
{
LED0 = 0;
LED1 = 1;
LED2 = 0;
LED3 = 0;
}
else if(KEY_Scan(0) == KEY1_PRES) //按键1按下
{
LED0 = 0;
LED1 = 0;
LED2 = 1;
LED3 = 0;
}
else if(KEY_Scan(0) == WKUP_PRES) //按键WK_UP按下
{
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 1;
}
}
}
```
其中,KEY_Scan函数用于扫描按键是否按下,代码如下:
```
u8 KEY_Scan(u8 mode)
{
static u8 key_up = 1; //按键松开标志
if(mode == 1) key_up = 1; //支持连按
if(key_up && (KEY0 == 0 || KEY1 == 0 || WK_UP == 1))
{
delay_ms(10); //去抖动
key_up = 0;
if(KEY0 == 0) return KEY0_PRES;
else if(KEY1 == 0) return KEY1_PRES;
else if(WK_UP == 1) return WKUP_PRES;
}
else if(KEY0 == 1 && KEY1 == 1 && WK_UP == 0) key_up = 1;
return 0; //无按键按下
}
```
阅读全文