源代码
module counter_999(clk,rst_n,en,count,dout);
input clk,rst_n,en;
output dout;
output[10:0]count;
wire[3:0]count_9;
wire[6:0]count_111;
wire dout,dout_9,dout_111;
wire dout_9_1;
counter_9 u1(.clk(clk),.rst_n(rst_n),.en(en),.count(count_9),.dout(dout_9_1));
counter_111 u2(.clk(clk),.rst_n(rst_n),.en(dout_9),.count(count_111),.dout(dout_111));//利用使能端信号完成记录一个9周期的计数,并在模111计数器中计1,即通过9×111,实现模为999的计数器
assign dout_9=en&&dout_9_1;//最不理解的一句,感觉有无区别不大
assign dout=dout_9&&dout_111;//检测是否达到999个状态
assign count={count_111,count_9};//总的输出状态
endmodule
module counter_9(clk,rst_n,en,count,dout);
input clk,rst_n,en;
output [3:0]count;
output dout;
reg[3:0]count;
always@(posedge clk or negedge rst_n)
begin
if(!rst_n) count<=4'b0000;//实现异步复位效果
else if(en)
if(count==4'b1000) count<=4'b0000;//实现计数9个(0~8)
else count<=count+1'b1;
end
assign dout=count[3];
endmodule
module counter_111(clk,rst_n,en,count,dout);
input clk,rst_n,en;
output [6:0]count;
output dout;
reg[6:0]count;
always@(posedge clk or negedge rst_n)
begin
if(!rst_n) count<=7'b000_0000;
else if(en)
if(count==7'b110_1110) count<=7'b000_0000;
else count<=count+1'b1;
end
assign dout=count[6]&count[5]&count[3]&count[2]&count[1];
endmodule
测试代码
`timescale 1ns/1ns
module counter_999_tb;
reg clk,rst_n,en;
wire [10:0]count;
wire dout;
counter_999 u1(clk,rst_n,en,count,dout);
always #2 clk=~clk;
initial
begin
clk=1'b0;rst_n=1'b1;en=1'b1;
#1 rst_n=1'b0;
#1 rst_n=1'b1;
end
endmodule
在本次测试中,当时间来到3990ns时,标志着一个999计数周期完成。