按键消抖

本文最后更新于 2024年8月31日 中午

按键消抖通常的按键所用开关为机械弹性开关,当机械触点断开、闭合时, 由于机械触点的弹性作用,
一个按键开关在闭合时不会马上稳定地接通,在断开时也不会一下子断开。 因而在闭合及断开的瞬间均
伴随有一连串的抖动, 为了不产生这种现象而作的措施就是按键消抖。

1、按键消抖原理图

按键消抖原理图按键消抖原理图

2、代码编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module key_debounce(
input sys_clk,
input sys_rst_n,

input key,

output reg key_filter
);

//parameter define
parameter CNT_MAX = 20'd100_0000; //消抖时间 20ms

//reg define
reg [19:0] cnt ;
reg key_d0; //将按键信号延迟一个时钟周期
reg key_d1; //将按键信号延迟两个时钟周期

always @(posedge sys_clk or negedge sys_rst_n) begin
if (!sys_rst_n) begin
key_d0 <= 1'b1;
key_d1 <= 1'b1;
end
else begin
key_d0 <= key;
key_d1 <= key_d0;
end
end

always @(posedge sys_clk or negedge sys_rst_n) begin
if (!sys_rst_n) begin
cnt <= CNT_MAX;
end
else if (key_d0 != key_d1) begin
cnt <= CNT_MAX;
end
else begin
if(cnt > 20'd0) begin
cnt <= cnt -1'd1;
end
else begin
cnt <= 20'd0;
end
end
end

always @(posedge sys_clk or negedge sys_rst_n) begin
if (!sys_rst_n) begin
key_filter <= 1'b1;
end
else if (cnt == 20'd0) begin
key_filter <= key_d1;
end
else begin
key_filter <= key_filter;
end
end
endmodule

本文作者: zhangJinLong
本文链接: https://zhang426fly.github.io/2025/07/05/fpga/按键消抖原理图/
版权声明: 本博客所有文章除特别声明外,均采用BY-NC-SA许可协议。转载请注明出处!


按键消抖
https://zhang426fly.github.io/2025/07/05/fpga/按键消抖原理图/
作者
zhangJinLong
发布于
2025年7月5日
许可协议