module key2(clk,rst_n,key,led);
//programmed by haohaolinux
input clk,rst_n,key;
output led;
reg key_rst;
always @(posedge clk or negedge rst_n)
if(!rst_n)
key_rst=1'b1;
else
key_rst=key;
reg key_rst_r;
always @(posedge clk or negedge rst_n)
if(!rst_n)
key_rst_r=1'b1;
else
key_rst_r=key_rst;
//key_an捕捉key的下降沿,当有按键按下时,key_an置高
wire key_an=key_rst_r & (~key_rst);
//计数,当有按键按下时,从0开始计数。。
reg [19:0] cnt;
always@(posedge clk or negedge rst_n)
if(!rst_n)
cnt=20'b0;
else if(key_an)
cnt=20'b0;
else
cnt=cnt+1;
//当计数器满的时候,再次捕捉按键是否被按下,如果被按下,则led_ctrl置高。
reg low_sw;
always@(posedge clk or negedge rst_n)
if(!rst_n)
low_sw=1'b1;
else if(cnt==20'hfffff)
low_sw=key;
reg low_sw_r;
always@(posedge clk or negedge rst_n)
if(!rst_n)
low_sw_r=1'b1;
else
low_sw_r=low_sw;
//捕捉low sw的下降沿
wire led_ctrl=low_sw_r & (~low_sw);
reg d1;
always@(posedge clk or negedge rst_n)
if(!rst_n)
d1=0;
else
if(led_ctrl) d1=~d1;
assign led=d1?1:0;
endmodule