|
新近写的,水平有限,欢迎拍砖。
参考了特权的代码。http://group.ednchina.com/1375/21132.aspx
-------------------------------------------------
module key_debounce(
input i_clk,
input i_rst_n,
input [4:1] i_key, // 按下为0,松开为1
output reg [4:1] o_key_val // 键值
);
//++++++++++++++++++++++++++++++++++++++
reg [4:1] key_samp1, key_samp1_locked;
// 将i_key采集至key_samp1
always @ (posedge i_clk, negedge i_rst_n)
begin
if(!i_rst_n)
key_samp1 <= 4'hF;
else
key_samp1 <= i_key;
end
// 将key_samp1锁存至key_samp1_locked
always @ (posedge i_clk, negedge i_rst_n)
begin
if(!i_rst_n)
key_samp1_locked <= 4'hF;
else
key_samp1_locked <= key_samp1;
end
//--------------------------------------
//++++++++++++++++++++++++++++++++++++++
wire [4:1] key_changed1;
// 当key_samp1由1变为0时
// key_changed1由0变为1,且维持一个时钟周期
assign key_changed1 = key_samp1_locked & (~key_samp1);
//--------------------------------------
//++++++++++++++++++++++++++++++++++++++
reg [19:0] cnt;
// 一旦有按键按下,cnt立即被清零
always @ (posedge i_clk, negedge i_rst_n)
begin
if(!i_rst_n)
cnt <= 20'h0;
else if(key_changed1)
cnt <= 20'h0;
else
cnt <= cnt + 1'b1;
end
//--------------------------------------
//++++++++++++++++++++++++++++++++++++++
reg [4:1] key_samp2, key_samp2_locked;
// 只有当按键不变化(不抖动),且维持20ms以上时
// 才将i_key采集至key_samp2
always @ (posedge i_clk, negedge i_rst_n)
begin
if(!i_rst_n)
key_samp2 <= 4'hF;
else if(cnt == 20'hF_FFFF) // 0xFFFFF/50M = 20.9715ms
key_samp2 <= i_key;
end
// 将key_samp2锁存至key_samp2_locked
always @ (posedge i_clk, negedge i_rst_n)
begin
if(!i_rst_n)
key_samp2_locked <= 4'hF;
else
key_samp2_locked <= key_samp2;
end
//--------------------------------------
//++++++++++++++++++++++++++++++++++++++
wire [4:1] key_changed2;
// 当key_samp2由1变为0时
// key_changed2由0变为1,且维持一个时钟周期
assign key_changed2 = key_samp2_locked & (~key_samp2);
//--------------------------------------
//++++++++++++++++++++++++++++++++++++++
// 每次按键稳定后,都将键值取反
always @ (posedge i_clk, negedge i_rst_n)
begin
if(!i_rst_n)
o_key_val <= 4'hF;
else
begin
if(key_changed2[1])
o_key_val[1] <= ~o_key_val[1];
if(key_changed2[2])
o_key_val[2] <= ~o_key_val[2];
if(key_changed2[3])
o_key_val[3] <= ~o_key_val[3];
if(key_changed2[4])
o_key_val[4] <= ~o_key_val[4];
end
end
//--------------------------------------
endmodule
------------------------------------------------- |
阿莫论坛20周年了!感谢大家的支持与爱护!!
曾经有一段真挚的爱情摆在我的面前,我没有珍惜,现在想起来,还好我没有珍惜……
|