module counter#(parameter cnt_begin =0 , cnt_max =24999_999 ,width =25 )(
input clk,
input rst_n,
input enable,
output [width-1:0] cnt_out
);
reg [width-1:0] cnt;
wire cnt_set;
always @(posedge clk or negedge rst_n)begin
if(!rst_n)
cnt <= cnt_begin;
else if(enable)begin
if(cnt_set)begin
cnt <= cnt_begin;
end
else begin
cnt <= cnt + 1'b1;
end
end
end
assign cnt_set = (cnt == cnt_max);
assign cnt_out = cnt;
endmodule
可作为计数器模板使用。只需要改cnt_begin、cnt_max、width的值,就能得到自己所需要的计数器。
另一种计数0.5s时间的最简单的写法
module counter1(
input clk,
input rst_n,
output [24:0]cnt_out
);
reg [24:0] cnt ;
always @(posedge clk or negedge rst_n)
if(!rst_n)
cnt <= 1'd0;
else if(cnt == 24999_999)
cnt <= 1'd0;
else
cnt <= cnt + 1'd1;
assign cnt_out = cnt ;
endmodule
这种写法在级联中更有优势,只写了中间主要的部分逻辑
always@(posegdge clk or negedge rst_n)
if(!rst_n)
cnt <= 'd0;
else if (add_cnt)begin
if(end_cnt)
cnt <= 'd0;
end
else
cnt <= cnt + 1'b1;
else
cnt <= 'd0;
assign add = ;
assign end_cnt = add_cnt&&cnt == cnt_max -1