用Verilog编一个计数器的程序

2025-03-09 10:25:37
推荐回答(3个)
回答1:

举个简单点的例子,如下。

设计一个4bit的计数器,在记到最大值时输出一个信号

module counter_16 ( input clk, input rst_n, input cnt_in ,output reg cnt_out );

reg [3:0] cnt;

always @ (posedge clk or negedge rst_n) begin

if (~rst_n)  cnt <= 4'b0;

else if (cnt_in) cnt <= cnt +1'b1;

else cnt <= cnt;

end

always @ (posedge clk or negedge rst_n) begin

if (~rst_n) cnt_out <= 1'b0;

else if (cnt_in && cnt == 4'b1111) cnt_out <= 1'b1;

else cnt_out <= 1'b0;

end

endmodule

这实际上设计了一个16进制计数器其中的一位,你可以例化多个相同模块,将低位的cnt_out连接到高位的cnt_in,级联成一个任意位数的16进制计数器。

回答2:

module cnt(
input wire rst_n,
input wire clk,
input wire cnt_clr,
input wire cnt_en,
output reg [31:0] cnt
);

// counter range = 0~CNT_END
parameter CNT_END = 9999;

always @(posedge clk or negedge rst_n) begin
if(~rst_n) cnt <= 32'd0;
else if(cnt_clr) cnt <= 32'd0;
else if(cnt_en) cnt <= (cntend

endmodule

回答3:

if-else,试问你的always块里面如果cnt_clr和cnt_en同时为0时,cnt??