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:第一次发随笔,代码中很多地方都是跟其他大佬学习,如有侵权,请及时联系,多多包涵
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了