stm32 G431RBTX 扫描按键、识别按键上升沿下降沿,识别按键短按,长按

复制代码
uint8_t Key_Scan(void)    //按键扫描,获取按键按下的键值
{
    uint8_t Key_val = 0;
  if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0) == GPIO_PIN_RESET)
    {
        HAL_Delay(10);
        if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0) == GPIO_PIN_RESET)
            Key_val = 1;
    }
    else if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1) == GPIO_PIN_RESET)
    {
        HAL_Delay(10);
   if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1) == GPIO_PIN_RESET)
            Key_val = 2;
    }
  else if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2) == GPIO_PIN_RESET)
    {
        HAL_Delay(10);
        if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2) == GPIO_PIN_RESET)
            Key_val = 3;
    }
  else if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == GPIO_PIN_RESET)
    {
        HAL_Delay(10);
        if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == GPIO_PIN_RESET)
            Key_val = 4;
    }
    return Key_val;
}

复制代码
void Key_Proc(void)    //按键服务程序,获取按键状态(上升沿,下降沿,长按,短按)
{
   static _Bool Key_Down_Flag = 0; static _Bool Key_Up_Flag = 0; Key_Tick = uwTick; uint8_t Key_L_Down = 0; uint32_t Key_Plus_Tick = 0; static uint32_t Key_Up_Tick_Start = 0; uint32_t Key_Up_Tick_End = 0; uint8_t Key_Value = Key_Scan(); uint8_t Key_S_Down = 0; static uint8_t Key_Down = 0; static uint8_t Key_Up = 0; static uint8_t Key_Old = 0; Key_Down = Key_Value & (Key_Value ^ Key_Old);    //获取按键上升沿,下降沿 Key_Up = ~Key_Value & (Key_Value ^ Key_Old); Key_Old = Key_Value; if(Key_Down)      //判断长按,短按 { Key_Down_Flag = 1; Key_Up_Tick_Start = uwTick; } if(Key_Up) { Key_Down_Flag = 0; }S if(Key_Down_Flag || Key_Up)    //key_S_Down为按键短按——Short { if((uwTick - Key_Up_Tick_Start) < 1000) Key_S_Down = Key_Up; else Key_L_Down = Key_Value;//key_L_Down为按键长按——LongL

  }
}
复制代码
PS:第一次发随笔,代码中很多地方都是跟其他大佬学习,如有侵权,请及时联系,多多包涵
 
复制代码

 

posted @   北纬小白  阅读(558)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示