中断扫描
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == TIM4)
{
static uint16_t tmr100ms = 0;
static uint16_t tmr200ms = 0;
static uint16_t tmr500ms = 0;
static uint16_t tmr1s = 0;
KeyScan();
tmr100ms++;
tmr200ms++;
tmr500ms++;
tmr1s++;
if(tmr100ms >= 50)
{
tmr100ms = 0;
flag100ms = 1;
}
if(tmr200ms >= 100)
{
tmr200ms = 0;
flag200ms = 1;
}
if(tmr500ms >= 250)
{
tmr500ms = 0;
flag500ms = 1;
}
if(tmr1s >= 500)
{
tmr1s = 0;
flag1s = 1;
}
}
}
读取KEY引脚
#define KEY1 HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) /* 读取KEY引脚 */
#define KEY2 HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin)
#define KEY3 HAL_GPIO_ReadPin(KEY3_GPIO_Port, KEY3_Pin)
#define KEY4 HAL_GPIO_ReadPin(KEY4_GPIO_Port, KEY4_Pin)
按键扫描
void KeyScan(void)
{
uint8_t i;
static uint8_t keybuf[4] = {0xFF, 0xFF, 0xFF, 0xFF};
keybuf[0] = (keybuf[0] << 1) | KEY1;//循环中按会多次左移最终可能就=0了
keybuf[1] = (keybuf[1] << 1) | KEY2;
keybuf[2] = (keybuf[2] << 1) | KEY3;
keybuf[3] = (keybuf[3] << 1) | KEY4;
for(i=0; i<4; i++)
{
if(keybuf[i] == 0xFF)
{
KeySta[i] = 1;
KeyDownTime[i] = 0;
}
else if(keybuf[i] == 0x00)
{
KeySta[i] = 0;
KeyDownTime[i] += 4;
}
else
{}
}
}
按键驱动while(1)
uint8_t KeySta[4] = {1, 1, 1, 1};
uint16_t KeyDownTime[4] = {0, 0, 0, 0};//注意是uint16_t
void KeyDriver(void)
{
uint8_t i;
static uint8_t backup[4] = {1, 1, 1, 1};
static uint16_t TimeThr[4] = {1000, 1000, 1000, 1000};//注意是static uint16_t
for(i=0; i<4; i++)
{
if(backup[i] != KeySta[i])
{
if(backup[i] != 0)
{
KeyAction(i+1, 0);//第2个参数0表示短按动作
}
backup[i] = KeySta[i];
}
//长按键的加入
if(KeyDownTime[i] > 0)
{
if(KeyDownTime[i] > TimeThr[i])
{
KeyAction(i+1, 1);//第2个参数1表示长按动作
TimeThr[i] += 200;
}
}
else
{
TimeThr[i] = 1000;
}
}
}
长按和短按动作
void KeyAction(int code, uint8_t sta)
{
/*短按对应的动作*/
if(sta == 0)
{
if(code == 1)//按下B1切换界面
{
flagMode++;
if(flagMode > 2)
{
flagMode = 0;
}
LCD_Clear(Blue);
}
else if(code == 2)//B2选择按键
{
if(flagMode == 0)//是数据界面
{
setMode ^= 1;//高低频率切换
N++;
}
if(flagMode == 1)//是参数界面
{
RKIndex ^= 1;//RK索引切换
}
}
else if(code == 3)//B3加按键
{
if(flagMode == 1)//是参数界面
{
IncValue();
}
}
else if(code == 4)//B4减按键
{
if(flagMode == 0)
{
Locking = 0;
}
if(flagMode == 1)
{
DecValue();
}
}
}
/*长按对应的动作*/
else if(sta == 1)
{
if(code == 4)//长按B4
{
if(flagMode == 0)//处于数据界面 锁定占空比不受R37影响
{
Locking = 1;
}
}
}
}