按键检测
按键注意消抖,机械按下和松开时均伴随有一连串的抖动,一般为5ms~10ms。可通过软件或硬件消抖。
void Key_Init()
{
//开启时钟,GPIOB
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
//定义结构体变量
GPIO_InitTypeDef GPIO_InitStructure;
//设置GPIO模式,上拉输入
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
//设置GPIO引脚pin1和pin11
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_11;
//设置GPIO速度
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//传入结构体,初始化GPIO
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
uint8_t key_GetNum()
{
uint8_t KeyNum = 0;
//读取PB1的值等于0时代表按下按钮
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)==0)
{
Delay_ms(20);//消抖
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)==0);//松手检测
Delay_ms(20);//消抖
KeyNum=1;//赋键值
}
//读取PB11的值等于0时代表按下按钮
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_11)==0)
{
Delay_ms(20);//消抖
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_11)==0);//松手检测
Delay_ms(20);//消抖
KeyNum=2;//赋键值
}
return KeyNum;//返回键值
}