Appearance
用稳定时间过滤按键抖动
每轮把原始电平和毫秒计数交给状态机。候选电平持续 20 ms 后才报告边沿。可用同一状态机在天空星按键翻灯。
完整源码
c
#ifndef KB_DEBOUNCE_H
#define KB_DEBOUNCE_H
#include <stdbool.h>
#include <stdint.h>
typedef enum { KEY_IDLE, KEY_PRESSED, KEY_RELEASED } KeyEvent;
typedef struct
{
bool stable;
bool candidate;
uint32_t changed_at;
} Debounce;
// 用已知的初始稳定电平初始化。每轮传入按键原始值和毫秒计数,间隔须小于时基完整回绕周期。
static inline KeyEvent debounce_update(Debounce *key, bool raw, uint32_t now, uint32_t stable_ms)
{
// 1. 每次观察到原始电平变动,就重新记候选电平及起点。
if (raw != key->candidate)
{
key->candidate = raw;
key->changed_at = now;
}
// 2. 只有候选电平持续够久且不同于旧稳定值,才交给调用者一个边沿事件。
if (key->candidate != key->stable && (uint32_t)(now - key->changed_at) >= stable_ms)
{
key->stable = key->candidate;
return key->stable ? KEY_PRESSED : KEY_RELEASED;
}
return KEY_IDLE;
}
#endifc
#include <assert.h>
#include <stdio.h>
#include "debounce.h"
int main(void)
{
Debounce key = {0};
// 1. 模拟按下时抖动,并跨过时基回绕。最后一次上升才开始 20 ms 的确认。
assert(debounce_update(&key, true, UINT32_MAX - 16U, 20U) == KEY_IDLE);
assert(debounce_update(&key, false, UINT32_MAX - 12U, 20U) == KEY_IDLE);
assert(debounce_update(&key, true, UINT32_MAX - 9U, 20U) == KEY_IDLE);
assert(debounce_update(&key, true, 9U, 20U) == KEY_IDLE);
assert(debounce_update(&key, true, 10U, 20U) == KEY_PRESSED);
// 2. 持续按住只产生一次事件。松开稳定 20 ms 后才报告释放。
assert(debounce_update(&key, true, 50U, 20U) == KEY_IDLE);
assert(debounce_update(&key, false, 51U, 20U) == KEY_IDLE);
assert(debounce_update(&key, false, 71U, 20U) == KEY_RELEASED);
puts("debounce: bounce, tick wrap, one press, one release");
return 0;
}运行和观察
powershell
New-Item -ItemType Directory -Force .work | Out-Null
gcc -std=c11 -Wall -Wextra -Werror -pedantic examples/c/debounce/main.c -o .work/debounce.exe
& ./.work/debounce.exe自测把最后一次抖动放在时基回绕之前。候选状态跟踪每次观察到的变化,并用无符号差计算等待时间。
预测题 保持高电平继续调用,会一直收到按下事件吗?
核对预测
候选已和稳定值一致,继续返回 KEY_IDLE。等到稳定松开后,才可能报告下一次按下。
改动题 把等待时间改成 10 ms,预测回绕后首次有效报告。
核对改法
最后一次上升设在 UINT32_MAX - 9。回绕时刻 0 正好经过 10 ms,此时再次调用可收到 KEY_PRESSED。
验证记录
已在 Windows 上用 GCC 15.2.0 严格编译并运行,验证抖动、计数回绕、单次按下和单次释放。