计数器作为verilog语言时序逻辑接触到的最简单的时序逻辑程序,在学习时序逻辑的时候有是很好的入手程序
计数器的逻辑并不复杂,废话不多说直接上代码,该代码是基于50Mhz的1S来写的,晶振的频率不同,程序需要微调。
module counter(
input clk ,
input rst_n ,
output [13:0] sum
);
parameter TIME_1S =50_000_000 ;
reg [13:0] count;
always @(posedge clk or negedge rst_n) begin
if(~rst_n) begin
count <= 'd0;
end
else if(count == TIME_1S) begin
count <= 'd0;
end
else begin
count <= count + 1'd1;
end
end
assign sum = count;
endmodule
测试文件:
`timescale 1ns/1ns
module counter_tb();
reg clk_tb ;
reg rst_n_tb ;
wire [13:0] sum_tb;
//parameter CLOCK_CYCLE = 20;//时钟周期参数定义
initial begin
clk_tb <= 0;
forever begin
#5 clk_tb <= !clk_tb;
end
#500 $finish;
end
initial begin
#10 rst_n_tb <= 0;
repeat(10) @(posedge clk_tb);
rst_n_tb <= 1;
end
counter u_counter(
.clk(clk_tb) ,
.rst_n(rst_n_tb) ,
.sum(sum_tb)
);
endmodule