1.短按键
定时器调为定时10ms
#include "fun.h"
struct keys key[4]={0,0,0};
void key_scan()
{
key[0].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0);
key[1].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1);
key[2].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2);
key[3].key_sta=HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0);
for(int i=0;i<4;i++)
{
switch(key[i].judge_sta)
{
case 0:
{
if(key[i].key_sta==0)key[i].judge_sta=1;
}
break;
case 1:
{
if(key[i].key_sta==0)
{
key[i].judge_sta=2;
key[i].single_sta=1;
}
else{
key[i].judge_sta=0;
}
}
break;
case 2:
{
if(key[i].key_sta==1)key[i].judge_sta=0;
}
break;
}
}
}
#include "fun.h"//该段代码在定义fun.h的头文件中
struct keys{
uchar judge_sta;
bool key_sta;
bool single_sta;
};
#include "inter.h"
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==TIM3)
{
key_scan();
}
}
2.长按键
struct keys{
uchar judge_sta;
bool key_sta;
bool single_sta;
bool long_sta;
uint16_t key_time;
};
struct keys key[4]={0,0,0,0,0};
void key_scan()
{
key[0].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0);
key[1].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1);
key[2].key_sta=HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2);
key[3].key_sta=HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0);
for(int i=0;i<4;i++)
{
switch(key[i].judge_sta)
{
case 0:
{
if(key[i].key_sta==0)
{
key[i].judge_sta=1;
key[i].key_time=0;
}
}
break;
case 1:
{
if(key[i].key_sta==0)
{
key[i].judge_sta=2;
}
else{
key[i].judge_sta=0;
}
}
break;
case 2:
{
if(key[i].key_sta==1)
{
key[i].judge_sta=0; //很关键,必须放在if的外面
if(key[i].key_time<70)
{
key[i].single_sta=1;
}
}
else{
key[i].key_time++;
if(key[i].key_time>70)
{
key[i].long_sta=1;
}
}
}
break;
}
}
}