独立按键消抖FPGA模块

View Code
1 module keyxiaodou (
2 input clk,//the freq or clk is 50M
3 input rst,//use key3 for rst button
4 input key1,key2,//use key1 to light led,use key2 to turn off led
5 output led);
6 //--------------------------------------------------
7 reg [1:0] key_r;//the first time check the key
8 always @ (posedge clk or negedge rst)
9 if (!rst) key_r <= 2'b11;
10 else key_r <= {key2,key1};
11
12 reg [1:0] key_rb;
13 always @ (posedge clk or negedge rst)
14 if (!rst) key_rb <= 2'b11;
15 else key_rb <= key_r;
16
17 wire [1:0] key_an = key_rb & (~key_r);//if the key[?] is pressed,key_an[?] become 1'b1
18 //--------------------------------------------------
19 reg [19:0] cnt;//divice the freq 1/50m*2^20=20ms
20 always @ (posedge clk or negedge rst)
21 if (!rst) cnt <= 20'd0;
22 else if (key_an) cnt <= 20'd0;
23 else cnt <= cnt+1'b1;
24 //--------------------------------------------------
25 reg [1:0] keyn_r;//the second time check the key
26 always @ (posedge clk or negedge rst)
27 if (!rst) keyn_r <= 2'b11;
28 else if(cnt ==20'hfffff) keyn_r <= {key2,key1};//relay 20ms for debounce
29
30 reg [1:0] keyn_rb;
31 always @ (posedge clk or negedge rst)
32 if (!rst) keyn_rb <= 2'b11;
33 else keyn_rb <= keyn_r;
34
35 wire [1:0] key_p = keyn_rb & (~keyn_r);
36 //--------------------------------------------------
37 reg led_r;
38 always @ (posedge clk or negedge rst)
39 if (!rst) led_r <= 1'b0;
40 else if (key_p[0]) led_r <= 1'b1;
41 else if (key_p[1]) led_r <= 1'b0;
42
43 assign led=~led_r;
44 endmodule

posted on 2011-07-10 04:45  万好好  阅读(714)  评论(0编辑  收藏  举报

导航