参考:
【黑金原创教程】【FPGA那些事儿-驱动篇I 】实验二:按键模块① - 消抖
源码如下:
key_funcmod.v
1 module key_funcmod(clk, rst, key, led, debug_led);
2
3 input clk, rst, key;
4
5 `define DEG
6
7 `ifndef DEG
8 output reg [1:0] led;
9 `else
10 output [1:0] led;
11 `endif
12
13 output reg debug_led;
14
15 //`define DEBUG debug_led <= 1'b1;
16
17 parameter T10MS=32'd500_000;
18
19 reg F1, F2;
20
21 always @(posedge clk or negedge rst)
22 begin
23 if (!rst)
24 {F2, F1} <= 2'b11;
25 else
26 {F2, F1} <= {F1, key};
27 end
28
29 wire isH2L;
30 wire isL2H;
31
32 assign isH2L = (F2 == 1'b1 && F1 == 1'b0);
33 assign isL2H = (F2 == 1'b0 && F1 == 1'b1);
34
35 reg[3:0] i;
36 reg[31:0] C1;
37 reg isPress, isRelease;
38
39 always @(posedge clk or negedge rst)
40 begin
41 if (!rst)
42 begin
43 i <= 4'd0;
44 {isPress, isRelease} <= 2'b00;
45 C1 <= 32'd0;
46 end
47 else
48 begin
49 case(i)
50 0:
51 begin
52 if (isH2L)
53 i <= i + 1'b1;
54 //`DEBUG
55 end
56 1:
57 begin
58 if (C1 == T10MS) begin C1 <= 32'd0; i <= i + 1'b1; end
59 else begin C1 <= C1 + 1'b1; end
60 end
61 2:
62 begin
63 isPress <= 1'b1;
64 i <= i + 1'b1;
65 end
66 3:
67 begin
68 isPress <= 1'b0;
69 i <= i + 1'b1;
70 end
71 4:
72 begin
73 if(isL2H)
74 i <= i + 1'b1;
75 end
76 5:
77 begin
78 if (C1 == T10MS) begin C1 <= 32'd0; i <= i + 1'b1; end
79 else begin C1 <= C1 + 1'b1; end
80 end
81 6:
82 begin
83 isRelease <= 1'b1;
84 i <= i + 1'b1;
85 end
86 7:
87 begin
88 isRelease <= 1'b0;
89 i <= 4'd0;
90 //`DEBUG
91 end
92 endcase
93 end
94 end
95
96 reg[1:0] D1;
97
98 99
100 always @(posedge clk or negedge rst)
101 begin
102 if (!rst)
103 `ifdef DEG
104 D1 <= 2'b00;
105 `else
106 led <= 2'b00;
107 `endif
108 else
109 if (isPress)
110 begin
111 `ifdef DEG
112 D1[0] <= ~D1[0];
113 `else
114 led[0] <= ~led[0];
115 `endif
116 //`DEBUG
117 end
118 else if (isRelease)
119 `ifdef DEG
120 D1[1] <= ~D1[1];
121 `else
122 led[1] <= ~led[1];
123 `endif
124 end
125
126 `ifdef DEG
127 assign led = D1;
128 `endif
129
130 endmodule
下载: http://files.cnblogs.com/files/pengdonglin137/key_demo1.zip
学到的知识:
1、Verilog下条件编译以及宏定义的使用;
2、一种调试方法:判断代码是不是执行到了,可以在关键位置加一个点灯的语句;
3、刚开始我把led设置为了 output reg [1:0] led,然后再最后assign led = D1,结果不管怎么按键,灯不亮。问题是:assign 语句后的led的类型应该是wire,而不应该是reg类型;
4、{isPress, isRelease} <= 2'b00; 其中, 不能写成 2'd11