1 `timescale 1ns / 1ps 2 module ctr_mod_16( 3 clk, 4 rst_n, 5 count 6 ); 7 input clk, rst_n; 8 output [3:0] count; 9 wire clk, rst_n; 10 reg [3:0] count; 11 12 always @ (posedge rst_n or negedge clk) 13 begin 14 if(rst_n == 0) 15 count = 4'b0000;//这里也要符合4比特的格式 16 else 17 count <= (count + 1) % 16; 18 end 19 endmodule
testbench:
1 `timescale 1ns / 1ps 2 module ctr_mod_16_tb; 3 reg clk, rst_n; 4 wire [3:0] count; 5 initial 6 $monitor ("count = %b", count); 7 initial 8 begin 9 #0 rst_n = 1'b0; 10 #20 rst_n = 1'b1; 11 end 12 initial 13 begin 14 #0 clk = 1'b0; 15 forever 16 #10 clk = ~clk; 17 end 18 initial 19 begin 20 #320 $stop; 21 end 22 23 ctr_mod_16 inst( 24 .clk(clk), 25 .rst_n(rst_n), 26 .count(count) 27 ); 28 endmodule
结果为:
这里需要注意的是:initial后的#延时是相对于零时刻了,而且,这里新接触了一个关键字forever,这里是实现无线次数的操作。
这里的时钟clk取反,很巧妙,实现的clk的01变化。
另一个注意点就是always括号中的敏感变量必须是输入信号!!