硬件
正点原子探索者STM32F407ZGT6
软件
1、Keil uVision5
代码
1、key.c中关键代码
//按键初始化函数
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
//使能GPIOA,GPIOE时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE|RCC_AHB1Periph_GPIOA,ENABLE);
//输入不配置GPIO_OType
//KEY0 KEY1 KEY2对应引脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4;
//普通输入模式
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
//100M
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
//上拉 外部无上下拉电阻,且接GND,所以设置为上拉
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
//初始化GPIOE2,3,4
GPIO_Init(GPIOE,&GPIO_InitStructure);
//WK_UP对应引脚PA0
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
//下拉 外部无上下拉电阻,且接3.3V,所以设置为下拉
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
//初始化GPIOA0
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
//按键处理函数
u8 Key_Scan(u8 mode)
{
static u8 key_up =1;
if(mode) key_up =1;
if(key_up && (key0 == 0 || key1 == 0 || key2 == 0 || wk_up == 1))
{
delay_ms(10);
key_up =0;
if(key0 == 0) return key0_value;
else if(key1 == 0) return key1_value;
else if(key2 == 0) return key2_value;
else if(wk_up == 1) return wk_up_value;
}else if(key0 == 1 && key1 ==1 && key2 ==1 && wk_up ==0) key_up =1;
return 0;
}
2、key.h中关键代码
//#define key0 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4)
//#define key1 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3)
//#define key2 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_2)
//#define wk_up GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)
#define key0 PEin(4)
#define key1 PEin(3)
#define key2 PEin(2)
#define wk_up PAin(0)
#define key0_value 10
#define key1_value 11
#define key2_value 12
#define wk_up_value 13
3、main.c中关键代码
int main(void)
{
u8 key; //保存键值
delay_init(168); //初始化延时函数
LED_Init(); //初始化LED端口
BEEP_Init(); //初始化蜂鸣器端口
KEY_Init(); //初始化与按键连接的硬件接口
LED0=0; //点亮红灯
LED1=0;
while(1)
{
key = Key_Scan(0);
if(key)
{
switch(key)
{
case wk_up_value: BEEP = !BEEP; break;
case key0_value: LED0 = !LED0; break;
case key1_value: LED1 = !LED1; break;
case key2_value: LED0 = !LED0; LED1 = !LED1; break;
}
}else delay_ms(10);
}
}
知识补充
1、static变量是声明全局变量,在局部函数退出的时候,全局变量的值还是保存在函数中,直到主函数的结束!
2、上拉下拉配置