(原創) 哪一個計數器才會出現9呢? (SOC) (Verilog)
Abstract
一個很簡單的題目,考驗你的觀念清不清楚...
Introduction
廢話不多說,直接看code吧,哪個計數器才會數到9呢?
counter9_v1.v / Verilog
1 /*
2 (C) OOMusou 2008 http://oomusou.cnblogs.com
3
4 Filename : counter9_v1.v
5 Compiler : Quartus II 7.2 SP3
6 Description : count to 9?
7 Release : 07/18/2008 1.0
8 */
9 module counter9_v1 (
10 input clk,
11 input rst_n,
12 output reg [3:0] q
13 );
14
15 reg [3:0] p;
16
17 always@(posedge clk or negedge rst_n) begin
18 if (!rst_n)
19 p <= 0;
20 else
21 p <= p + 1;
22 end
23
24 always@(p) begin
25 if (p == 9)
26 q = 0;
27 else
28 q = p;
29 end
30 endmodule
2 (C) OOMusou 2008 http://oomusou.cnblogs.com
3
4 Filename : counter9_v1.v
5 Compiler : Quartus II 7.2 SP3
6 Description : count to 9?
7 Release : 07/18/2008 1.0
8 */
9 module counter9_v1 (
10 input clk,
11 input rst_n,
12 output reg [3:0] q
13 );
14
15 reg [3:0] p;
16
17 always@(posedge clk or negedge rst_n) begin
18 if (!rst_n)
19 p <= 0;
20 else
21 p <= p + 1;
22 end
23
24 always@(p) begin
25 if (p == 9)
26 q = 0;
27 else
28 q = p;
29 end
30 endmodule
counter9_v2.v / Verilog
1 /*
2 (C) OOMusou 2008 http://oomusou.cnblogs.com
3
4 Filename : counter9_v2.v
5 Compiler : Quartus II 7.2 SP3
6 Description : count to 9?
7 Release : 07/18/2008 1.0
8 */
9 module counter9_v2 (
10 input clk,
11 input rst_n,
12 output [3:0] q
13 );
14
15 reg [3:0] p;
16
17 assign q = p;
18
19 always@(posedge clk or negedge rst_n) begin
20 if (!rst_n)
21 p <= 0;
22 else if (p == 9)
23 p <= 0;
24 else
25 p <= p + 1;
26 end
27
28 endmodule
2 (C) OOMusou 2008 http://oomusou.cnblogs.com
3
4 Filename : counter9_v2.v
5 Compiler : Quartus II 7.2 SP3
6 Description : count to 9?
7 Release : 07/18/2008 1.0
8 */
9 module counter9_v2 (
10 input clk,
11 input rst_n,
12 output [3:0] q
13 );
14
15 reg [3:0] p;
16
17 assign q = p;
18
19 always@(posedge clk or negedge rst_n) begin
20 if (!rst_n)
21 p <= 0;
22 else if (p == 9)
23 p <= 0;
24 else
25 p <= p + 1;
26 end
27
28 endmodule
Conclusion
由模擬的波形圖得知,counter_v2才會數到9,你答對了嗎?
從block diagram中,可以發現兩者合成出來的電路是差異甚大,v1的reg q後面接了一個組合電路,經過一個比較器與多工器後『馬上』輸出結果,所以還沒數到9就被『攔胡』了,v2是個典型的循序電路,由比較器判斷的p,是從D-FF所提供的p,而這個p早已經輸出到q了,要攔也攔不下來,且9已經存在於D-FF中1個clock,要讓p = 0也是下一個clock的事情,所以在下一個clock出現q = 0。
多多觀察RTL Viewer所合成的電路與ModelSim模擬結果是增加Verilog功力的不二法門,共勉之。