
`timescale1ns/1ps
//当三个独立按键的某一个被按下后,相应的LED被点亮;再次按下后,LED熄灭,按键控制LED亮灭
modulesw_debounce(
clk,rst_n,
sw1_n,sw2_n,sw3_n,
led_d1,led_d2,led_d3
);
inputclk; //主时钟信号,50MHz
inputrst_n; //复位信号,低有效
inputsw1_n,sw2_n,sw3_n; //三个独立按键,低表示按下
outputled_d1,led_d2,led_d3; //发光二极管,分别由按键控制
//---------------------------------------------------------------------------
reg[2:0]key_rst;/////
always@(posedgeclkornegedgerst_n)
if(!rst_n)key_rst<=3'b111;
elsekey_rst<={sw3_n,sw2_n,sw1_n};
reg[2:0]key_rst_r;//每个时钟周期的上升沿将low_sw信号锁存到low_sw_r中
always@(posedgeclkornegedgerst_n)
if(!rst_n)key_rst_r<=3'b111;
elsekey_rst_r<=key_rst;
//当寄存器key_rst由1变为0时,led_an的值变为高,维持一个时钟周期
wire[2:0]key_an=key_rst_r&(~key_rst);
/*
key_rst111001
~key_rst000110
key_rst_n111001
key_an00100
*/
//---------------------------------------------------------------------------
reg[19:0]cnt; //计数寄存器
always@(posedgeclkornegedgerst_n)
if(!rst_n)cnt<=20'd0; //异步复位
elseif(key_an)cnt<=20'd0;
elsecnt<=cnt+1'b1;
reg[2:0]low_sw;
always@(posedgeclkornegedgerst_n)
if(!rst_n)low_sw<=3'b111;
elseif(cnt==20'hfffff) //满20ms,将按键值锁存到寄存器low_sw中 cnt==20'hfffff
low_sw<={sw3_n,sw2_n,sw1_n};
//---------------------------------------------------------------------------
reg[2:0]low_sw_r;//每个时钟周期的上升沿将low_sw信号锁存到low_sw_r中
always@(posedgeclkornegedgerst_n)
if(!rst_n)low_sw_r<=3'b111;
elselow_sw_r<=low_sw;
/*
low_sw 111111111110110110
~low_sw000000000001001001
low_sw_r111111111110110110
led_ctrl 000000000001000000
*/
//当寄存器low_sw由1变为0时,led_ctrl的值变为高,维持一个时钟周期
wire[2:0]led_ctrl=low_sw_r[2:0]&(~low_sw[2:0]);
regd1;
regd2;
regd3;
always@(posedgeclkornegedgerst_n)
if(!rst_n)begin
d1<=1'b0;
d2<=1'b0;
d3<=1'b0;
end
elsebegin //某个按键值变化时,LED将做亮灭翻转
if(led_ctrl[0])d1<=~d1;
if(led_ctrl[1])d2<=~d2;
if(led_ctrl[2])d3<=~d3;
end
assignled_d3=d1?1'b1:1'b0; //LED翻转输出
assignled_d2=d2?1'b1:1'b0;
assignled_d1=d3?1'b1:1'b0;
endmodule