消抖部分code
`timescale 1ns / 1ps
//
// Company:
// Engineer:
//
// Create Date: 2025/01/19 20:58:44
// Design Name:
// Module Name: key_filter
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//
module key_filter
#(
parameter CNT_MAX = 20'd999_999
)
(
input wire sys_clk ,
input wire sys_rst_n ,
input wire key_in ,
output reg key_flag
);
reg [19:0] cnt_20ms ;
always@( posedge sys_clk or negedge sys_rst_n )
begin
if( sys_rst_n == 1'b0 )
begin
cnt_20ms <= 20'd0 ;
end
else if( key_in == 1'b1 )
begin
cnt_20ms <= 20'd0 ;
end
else if( cnt_20ms == CNT_MAX && key_in == 1'b0 )
begin
cnt_20ms <= cnt_20ms ;
end
else
begin
cnt_20ms <= cnt_20ms + 1'b1 ;
end
end
always@( posedge sys_clk or negedge sys_rst_n )
begin
if( sys_rst_n == 1'b0 )
begin
key_flag <= 1'b0 ;
end
else if( cnt_20ms == CNT_MAX - 1'b1 )
begin
key_flag <= 1'b1 ;
end
else
begin
key_flag <= 1'b0 ;
end
end
endmodule
tb
`timescale 1ns / 1ps
//
// Company:
// Engineer:
//
// Create Date: 2025/01/19 21:28:47
// Design Name:
// Module Name: tb_key_filter
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//
module tb_key_filter();
parameter CNT_1MS = 20'd19 ,
CNT_11MS = 20'd69 ,
CNT_41MS = 20'd149 ,
CNT_51MS = 20'd199 ,
CNT_60MS = 20'd249 ;
wire key_flag ;
reg sys_clk ;
reg sys_rst_n ;
reg key_in ;
reg [21:0] tb_cnt ;
initial
begin
sys_clk = 1'b1 ;
sys_rst_n <= 1'b0 ;
#20 ;
sys_rst_n <= 1'b1 ;
end
always #10 sys_clk = ~sys_clk ;
//tb_cnt模拟抖动
always@(posedge sys_clk or negedge sys_rst_n )
begin
if( sys_rst_n == 1'b0 )
begin
tb_cnt <= 22'd0 ;
end
else if( tb_cnt == CNT_60MS )
begin
tb_cnt <= 22'd0 ;
end
else
begin
tb_cnt <= tb_cnt + 1'b1 ;
end
end
// key_in 模拟案件输入
always@( posedge sys_clk or negedge sys_rst_n )
begin
if( sys_rst_n == 1'b0 )
begin
key_in <= 1'b1 ;
end
else if( (tb_cnt >= CNT_1MS && tb_cnt <= CNT_11MS)
||
(tb_cnt >= CNT_41MS && tb_cnt <= CNT_41MS)
)
begin
key_in <= {$random}%2 ;
end
else if( tb_cnt >= CNT_11MS && tb_cnt <= CNT_41MS )
begin
key_in <= 1'b0 ;
end
else
begin
key_in <= 1'b1 ;
end
end
key_filter
#(
.CNT_MAX (20'd24)
)
key_filter_inst
(
.sys_clk (sys_clk) ,
.sys_rst_n (sys_rst_n) ,
.key_in (key_in) ,
.key_flag (key_flag)
);
endmodule
结果