Mod-16 计数器设计

huangapple go评论50阅读模式
英文:

Mod-16 counter design

问题

该代码是一个16位的计数器模块,但在每个时钟周期内,输出不应该变成15。这是因为在always块中,计数器从0开始,在16个时钟周期内逐次增加,最终达到15,然后再次从0开始。这是因为for循环在每个时钟上升沿时执行,每次将q加1,直到达到16次循环后,计数器重置为0。

让我解释一下always块中的for循环的工作原理:

  1. 首先,在时钟信号的上升沿(posedge clk)发生时,always块开始执行。

  2. 首先,q被设置为0(q <= 0),以确保计数器从0开始。

  3. 接下来,检查是否存在复位信号(reset)。如果复位信号为高电平(1),则将q重置为0(q <= 4'd0)。

  4. 如果没有复位信号,就会进入for循环。循环从0开始(i=0),然后在每个时钟周期内逐次递增q的值(q <= q + 1),并将i递增1(i = i + 1)。

  5. i达到16时,循环结束,q的值将保持在15,因为它在第16次时钟上升沿时增加了1,然后在下一个时钟周期内被重置为0。

这就是为什么计数器的输出在每个时钟周期内不会变成15,而是在0到15之间循环变化的原因。希望这可以帮助你理解代码的工作方式。

英文:
module counter_16 (
    input clk,
    input reset,      // Synchronous active-high reset
    output reg [3:0] q);
    integer i;
    
    always @(posedge clk)
        begin
            q&lt;=0;
            if (reset)
                q &lt;= 4&#39;d0;
            else 
            	 for (i=0; i&lt;16; i=i+1)
                	begin
                	    q &lt;= q+1;
                	end
        end
endmodule

I was trying to make a mod16 counter. This code is working fine. But, at every clock, should the output become 15? Please explain the working of a for loop in this always block.

答案1

得分: 1

这是代码部分的翻译:

如果您想要一个4位计数器,这是编写它的通常方式:

always @(posedge clk)
    begin
        if (reset)
            q <= 4'd0;
        else 
            q <= q+1;
    end

您的代码中存在多个非阻塞赋值(使用<=),这不是一个好的编程实践。不需要使用for循环。

输出是否应该变为16?

由于您将q声明为4位宽度,它将取值0到15。它不能具有值16;这将需要至少5位。

英文:

If you want a 4-bit counter, this is the customary way to code it:

always @(posedge clk)
    begin
        if (reset)
            q &lt;= 4&#39;d0;
        else 
            q &lt;= q+1;
    end

Your code has multiple nonblocking assignments (using &lt;=), which is not a good coding practice. There is no need for a for loop.

> should the output become 16?

Since you declared q as 4 bits wide, it will take on the values 0 to 15. It can not have the value 16; that would require at least 5 bits.

huangapple
  • 本文由 发表于 2023年5月25日 02:31:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定