标签:信号 inpu 方便 always initial 高电平 details assign under
基于basys2的按键消抖模块,basys2的按键是高电平“1”表示按下.
`module key_filter( clk,sys_rst_n,key_en,key_in);
input clk;
input sys_rst_n;
input key_in;
output key_en;
//这两段代码前面分别进行计数和在计数满产生一个高脉冲信号cnt_full
//20ms计数器
reg cnt_full;
reg [19:0] cnt;
always@(posedge clk or negedge sys_rst_n)
begin
if(!sys_rst_n)
cnt <= 20‘d0;
else if(cnt == 20‘d1000000-1) //20ms/20ns=1000_000
cnt <= 20‘d0;
else
cnt <= cnt + 1‘b1;
end
//计数满信号
always@(posedge clk or negedge sys_rst_n)
begin
if(!sys_rst_n)
cnt_full <= 1‘b0;
else if(cnt == 20‘d1000000-1)
cnt_full <= 1‘b1;
else
cnt_full <= 1‘b0;
end
//这两段代码就是来用实现取前后按键信号的
reg key_in_r;
reg key_in_r_next;
always@(posedge clk or negedge sys_rst_n)
begin
if(!sys_rst_n)
key_in_r_next <= 0;
else if(cnt_full)
key_in_r_next <= key_in;
else
key_in_r_next <= key_in_r_next;
end
always@(posedge clk or negedge sys_rst_n)
begin
if(!sys_rst_n)
key_in_r <= 0;
else
key_in_r <= key_in_r_next;
end
assign key_en = ~key_in_r & (key_in_r_next);
endmodule`
Testbench
`module key_filter_tb;
// Inputs
reg clk;
reg sys_rst_n;
reg key_in;
// Outputs
wire key_en;
// Instantiate the Unit Under Test (UUT)
key_filter uut (
.clk(clk),
.sys_rst_n(sys_rst_n),
.key_en(key_en),
.key_in(key_in)
);
initial clk = 1;
always #10 clk <= ~clk;
//开始测试
initial begin
sys_rst_n <= 0; //系统复位
key_in <= 1; //按键处于空闲状态
#20;
sys_rst_n <= 1;
#10_000_000; //延时10ms,方便观察按键按下现象
//开始模拟按键按下抖动
key_in <= 0; #1000;
key_in <= 1; #2000;
key_in <= 0; #1400;
key_in <= 1; #2600;
key_in <= 0; #1300;
key_in <= 1; #200;
//产生一个稳定的低电平大于20ms,代表按键稳定
key_in <= 0; #30_000_000;
//模拟释放抖动
key_in <= 1; #2000;
key_in <= 0; #1000;
key_in <= 1; #2600;
key_in <= 0; #1400;
key_in <= 1; #200;
key_in <= 0; #1300;
//产生一个稳定的高电平大于20ms,代表释放稳定
key_in <= 1; #30_000_000;
end
endmodule`
仿真时序图如下:
本篇随笔为学习记录所用,如有侵权请联系作者。
代码原出处:https://blog.csdn.net/qq_23103023/article/details/104241923
标签:信号 inpu 方便 always initial 高电平 details assign under
原文地址:https://www.cnblogs.com/zqh1126/p/14406822.html