Appearance
26 按键消抖 · 连续三次一致才切换
每次调用代表一次等间隔采样。返回值只报告稳定电平发生变化的那一次。
源码
main.c
c
#include <stdio.h>
#include <stdbool.h>
typedef struct {
bool stable;
unsigned different;
} Button;
static bool update(Button *b, bool level)
{
if (level == b->stable) {
b->different = 0;
return false;
}
if (++b->different < 3) {
return false;
}
b->stable = level;
b->different = 0;
return true;
}
int main(void)
{
Button b = {0};
bool input[] = {1, 0, 1, 1, 1};
for (size_t i = 0; i < 5; ++i) {
if (update(&b, input[i])) {
printf("%zu:%d\n", i + 1, b.stable);
}
}
return 0;
}主机运行
在仓库根目录执行。Windows 可以将输出名写成 reading-26.exe,再从终端运行。
sh
gcc -std=c11 -Wall -Wextra -pedantic examples/c-reading/26/main.c -o reading-26
./reading-26先沿 main() 预测打印结果,再展开核对。
主机输出与手推
text
5:1输入 1、0、1、1、1,在第 5 次采样才稳定按下。
练习
继续输入三个 0,判断何时报告释放。
关联模板
验证记录
主机版使用 GCC 编译运行,输出与跟读材料逐项核对。