04_按键处理

按键会有抖动,现在记录较简单的处理方法:
1. 硬件去抖动, 加电容, 充放电
2. 软件去抖动, 延时 10ms 去除前抖动; 然后通过 flag标记 去除后抖动

// 判断按键是否按下
// 返回按下按键的键值
// KEY0 - 返回: KEY0_PRESS 1 // key0 键值
u8 KEY_Sacn(void) {
    // 0, 按键没有被按下; 1, 按键被按下
    static u8 ispressed = 0;

    if ((ispressed == 0) && (KEY_UP || !KEY0 || !KEY1 || !KEY2)) {

        // 一旦检测到有按键被按下, ispressed = 1
        ispressed = 1;
        // 软件去抖动
        delay_ms(10);

        if (KEY_UP) {
            return KEY_UP_PRESS;
        } else if (!KEY0) {
            return KEY0_PRESS;
        } else if (!KEY1) {
            return KEY1_PRESS;
        } else if (!KEY2) {
            return KEY2_PRESS;
        }
    } else if (!KEY_UP && KEY0 && KEY1 && KEY2){ // 按键都松开
        ispressed = 0;
    }

    return 0;
}

注: 如果不用ispressed , 一次按键过程中, 可能检测到两次按键被按下

posted @ 2025-05-07 19:35  靖意风  Views(32)  Comments(0)    收藏  举报