博主从硬件方面和软件方面进行讲解。
硬件方面,我们先来看看按键模块的物理连接。
我们很容易的发现,当我们按下按键的时候,NK1(ps以这个按键为例)电平将会被拉低。试想如果这个与NK1相连的的管脚如果在没有按下按键的时候保持高电平,我们只需要检测管脚信号的变化既可以知道有无按键按下。
还有一个关于硬件方面的特性,就是按键的抖动。这个方面博主就不仔细讲解了。
软件方面
#include"stm32f10X.h"
#include"key.h"
/***按键初始化函数***/
/*
无返回值;
无参数;
KEY1-GPIOA_Pin_0
KEY2-GPIOA_Pin_8
KEY3-GPIOB_Pin_1
KEY4-GPIOB_Pin_2
*/
void Key_Init()
{
GPIO_InitTypeDef GOIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOA,ENABLE);
GOIO_InitStructure.GPIO_Pin=GPIO_Pin_0|GPIO_Pin_8;
GOIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GOIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;//上拉输入,为让按键在没有按下的时候保持高电平
GPIO_Init(GPIOA,&GOIO_InitStructure);
GOIO_InitStructure.GPIO_Pin=GPIO_Pin_1|GPIO_Pin_2;
GPIO_Init(GPIOB,&GOIO_InitStructure);
}
/***按键扫描函数***/
u8 Key_scan()
{
u8 key_value=0;
if(key1!=1)
{
systick_delay_ms(4);//消除抖动期的影响
if(key1!=1)key_value=1;
}
if(key2!=1)
{
systick_delay_ms(4);
if(key2!=1)key_value=2;
}
if(key3!=1)
{
systick_delay_ms(4);
if(key3!=1)key_value=3;
}
if(key4!=1)
{
systick_delay_ms(4);
if(key4!=1)key_value=4;
}
return key_value;
}
上面的代码当中key1,是宏定义在key.h当中的。
#ifndef __KEY_H
#define __KEY_H
#define key1 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)
#define key2 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_8)
#define key3 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)
#define key4 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)
void Key_Init();
u8 Key_scan();
#endif