(转帖) 如何將值delay n個clock? (SOC) (Verilog)
来源:http://www.cnblogs.com/oomusou/archive/2009/06/15/verilog_dly_n_clk.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 (C) OOMusou 2009 http://oomusou.cnblogs.com 3 4 Filename : delay_3t.v 5 Compiler : NC-Verilog 5.4 6 Description : delay 3t method 1 7 Release : 06/15/2009 1.0 8 */ 9 10 module delay_3t ( 11 clk, 12 rst_n, 13 d, 14 q 15 ); 16 17 input clk; 18 input rst_n; 19 input d; 20 output q; 21 22 reg d_dly_1t; 23 reg d_dly_2t; 24 reg d_dly_3t; 25 26 assign q = d_dly_3t; 27 28 always@(posedge clk or negedge rst_n) begin 29 if (!rst_n) begin 30 d_dly_1t <= 0; 31 d_dly_2t <= 0; 32 d_dly_3t <= 0; 33 end 34 else begin 35 d_dly_1t <= d; 36 d_dly_2t <= d_dly_1t; 37 d_dly_3t <= d_dly_2t; 38 end 39 end 40 41 endmodule
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 (C) OOMusou 2009 http://oomusou.cnblogs.com 3 4 Filename : delay_3t.v 5 Compiler : NC-Verilog 5.4 6 Description : delay 3t method 2 7 Release : 06/15/2009 1.0 8 */ 9 10 module delay_3t ( 11 clk, 12 rst_n, 13 d, 14 q 15 ); 16 17 input clk; 18 input rst_n; 19 input d; 20 output q; 21 22 reg d_dly_1t; 23 reg d_dly_2t; 24 reg d_dly_3t; 25 26 assign q = d_dly_3t; 27 28 always@(posedge clk or negedge rst_n) begin 29 if (!rst_n) 30 {d_dly_3t, d_dly_2t, d_dly_1t} <= 0; 31 else 32 {d_dly_3t, d_dly_2t, d_dly_1t} <= {d_dly_2t, d_dly_1t, d}; 33 end 34 35 endmodule
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 (C) OOMusou 2009 http://oomusou.cnblogs.com 3 4 Filename : delay_nt.v 5 Compiler : NC-Verilog 5.4 6 Description : delay 3t method 3 7 Release : 06/15/2009 1.0 8 */ 9 10 module delay_nt ( 11 clk, 12 rst_n, 13 d, 14 q 15 ); 16 17 parameter n = 1; 18 19 input clk; 20 input rst_n; 21 input d; 22 output q; 23 24 reg [n-1:0] r; 25 26 assign q = r[n-1]; 27 28 integer i; 29 30 always@(posedge clk or negedge rst_n) begin 31 if (!rst_n) 32 r <= 0; 33 else begin 34 for(i=0; i<n-1; i=i+1) 35 r[i+1] <= r[i]; 36 37 r[0] <= d; 38 end 39 end 40 41 endmodule
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 (C) OOMusou 2009 http://oomusou.cnblogs.com 3 4 Filename : delay_nt.v 5 Compiler : NC-Verilog 5.4 6 Description : delay 3t method 4 7 Release : 06/15/2009 1.0 8 */ 9 10 module delay_nt ( 11 clk, 12 rst_n, 13 d, 14 q 15 ); 16 17 parameter n = 3; 18 19 input clk; 20 input rst_n; 21 input d; 22 output q; 23 24 reg [n-1:0] r; 25 26 assign q = r[n-1]; 27 28 always@(posedge clk or negedge rst_n) begin 29 if (!rst_n) 30 r <= 0; 31 else 32 r <= {r, d}; 33 end 34 35 endmodule
{}写法是Verilog的独门绝技,这样就不再需要for,这也是为什么Verilog宁愿从C语言抢走{}换来begin, end,因为{}这种合并的写法非常的好用。Testbench与模拟波型图也与Method 1与Method 2一样,再次省略。这种写法使用了parameter,无论要delay几个clk,只需修改n即可,而且与Quartus II优化后的硬件一样,我们再次将编译过的RTL Viewer打开做验证。
Conclusion
这4种写法最后合出来的硬件都一样,表示现在的合成器都够聪明,差别只是在哪种coding style较好,将来比较好维护。另外也是开开眼界,若将来阅读其他人的code,马上就知道对方想表达的意思。