- 一、开发板 与 电路图
- 二、STM32CubeMX工程
- 1、复制 1_LED_BEEP 重命名为 2_KEY;
- 2、打开STM32CubeMX 文件进行配置
- 三、代码编写
正点原子 潘多拉 STM32L475VET6
- 根据电路图可知,WK_UP 为下拉输入,KEY0、KEY1、KEY2为上拉输入;
- 因为直接复制的工程,STM32CubeMX 文件名字可以不改,如果修改了名字的话,之后会生成新的项目文件。
- 直接生成代码;
- 新建key.c、key.h文件保存到Hardware/2_key
- 添加文件;
- 添加头文件路径
- 记得包含头文件
key.h
#ifndef _KEY_H #define _KEY_H #include "main.h" #define KEY0 0 #define KEY1 1 #define KEY2 2 #define WK_UP 3 #define KB0 HAL_GPIO_ReadPin(GPIOD,GPIO_PIN_10) #define KB1 HAL_GPIO_ReadPin(GPIOD,GPIO_PIN_9) #define KB2 HAL_GPIO_ReadPin(GPIOD,GPIO_PIN_8) #define KB_UP HAL_GPIO_ReadPin(GPIOC,GPIO_PIN_13) #define KEYPORT KB0 | (KB1<<1) | (KB2<<2) | ((!KB_UP)<<3) | 0xf0 extern unsigned char Trg; extern unsigned char Cont; void Key_Read( void ); short Key(_Bool); #endif
key.c
#include "key.h"
unsigned char Trg;
unsigned char Cont;
unsigned char Trg2; //中间变量
void Key_Read( void )
{
unsigned char ReadData = (KEYPORT)^0xff; // 1. Read KEYPORT ^(xor)
Trg = ReadData & (ReadData ^ Cont); // 2
Cont = ReadData; // 3
}
//m = 0;不支持连按------长按只触发一次
//m = 1;支持连按 ------长按触发多次
short Key(_Bool m)
{
static _Bool mode = 1;
Key_Read();
if(m) mode = 1;
if(mode == 1 && Trg != 0)
{
mode = 0;
if(Trg != 0)
{
Trg2 = Trg;
Trg = 0; //可以使用 定时器 决定长按多次触发的时间间隔
Cont = 0; //清除按键记录
}
if(Trg2 == 0x01) //KB0
{
return KEY0;
}
else if(Trg2 == 0x02) //KB1
{
return KEY1;
}
else if(Trg2 == 0x04) //KB2
{
return KEY2;
}
else if(Trg2 == 0x08) //KB_UP
{
return WK_UP;
}
}
else if(KB0 == 1 && KB1 == 1 &&KB2 == 1 &&KB_UP == 0)
{
mode = 1;
}
return -1;
}
main.c(部分)
int main(void)
{
short key = -1;
//………………………………………………
//此处省略一些代码,不需要自己修改
//………………………………………………
while (1)
{
key = Key(1);
if(key == KEY1)
{
LED_B_TogglePin;
LED_G_TogglePin;
LED_R_TogglePin;
}
HAL_Delay(100);
}
}
在支持连续按键时,长按KEY1,LED连续闪烁呢!



