module sw_debounce(clk,rst_n,sw1_n,sw2_n,sw3_n,sw4_n,led_d1,led_d2,led_d3,led_d4);
input clk,rst_n;
input wire sw1_n,sw2_n,sw3_n,sw4_n;
output wire led_d1,led_d2,led_d3,led_d4;
reg[3:0] key_rst;
always@(posedge clk or negedge rst_n)
if(!rst_n) key_rst<=4'b1111;
else
key_rst<={sw4_n,sw3_n,sw2_n,sw1_n};
reg[3:0] key_rst_r;
always@(posedge clk or negedge rst_n)
if(!rst_n) key_rst_r<=4'b1111;
else key_rst_r<=key_rst;
wire[3:0]key_an=key_rst_r&(~key_rst);
reg[19:0] cnt;
always@(posedge clk or negedge rst_n)
if(!rst_n) cnt<=20'd0;
else if (key_an) cnt<=20'd0;
else cnt<=cnt+1'b1;
reg[3:0] low_sw;
always@(posedge clk or negedge rst_n)
if(!rst_n) low_sw<=4'b1111;
else if (cnt==20'hfffff)
low_sw<={sw4_n,sw3_n,sw2_n,sw1_n};
reg [3:0] low_sw_r; //每个时钟周期的上升沿将low_sw信号锁存到low_sw_r中
always @ ( posedge clk or negedge rst_n )
if (!rst_n) low_sw_r <= 4'b1111;
else low_sw_r <= low_sw;
wire[3:0] led_ctrl=low_sw_r[3:0]&(~low_sw[3:0]);
reg d1,d2,d3,d4;
always @(posedge clk or negedge rst_n)
if(!rst_n)begin
d1<=1'b0;
d2<=1'b0;
d3<=1'b0;
d4<=1'b0;
end
else begin
if(led_ctrl[0]) d1<=~d1;
if(led_ctrl[1]) d2<=~d2;
if(led_ctrl[2]) d3<=~d3;
if(led_ctrl[3]) d4<=~d4;
end
assign led_d4=d1?1'b1:1'b0;
assign led_d3=d2?1'b1:1'b0;
assign led_d2=d3?1'b1:1'b0;
assign led_d1=d4?1'b1:1'b0;
endmodule
可以参考这个写 |