Clock inversion loop

67 views Asked by At

I see this code written in a testbench. But, I do not understand why we need to do it like this. The clock period is 2.034ns. I did not wrote this code. The person who wrote this is not here.

`timescale 1ps/1ps
 module tb();
  initial begin
    #0
    forever begin
      for (int x=0; x<95; x++) begin
        #(1017) clk_491p52 = ~clk_491p52;
        #(1017) clk_491p52 = ~clk_491p52;
        #(1017) clk_491p52 = ~clk_491p52;
        #(1018) clk_491p52 = ~clk_491p52;
      end
      #(1017) clk_491p52 = ~clk_491p52;
      #(1018) clk_491p52 = ~clk_491p52;
      #(1017) clk_491p52 = ~clk_491p52;
      #(1018) clk_491p52 = ~clk_491p52;
    end
  end
endmodule

Why are we inverting the clock with this particular pattern? Can't we just do it like this?

initial clk_491p52=0;
always #(2034/2) clk_491p52=~clk_491p52;
2

There are 2 answers

0
toolic On

There is a difference between the 2 code examples you showed.

The example with the always block produces a 50% duty cycle.

The example with the forever block does not produce a 50% duty cycle.

In the always block, every half-cycle is 1017ps.

In the forever block, some half-cycles are 1017ps, whereas other half-cycles are 1018ps: 1017 vs. 1018

This all assumes that clk_491p52 is declared as a single bit signal.


The always block is the traditional way to generate a simple testbench clock. However, the person who used the forever block must have seen a need to create a more complex clock waveform.

0
Greg On

Look like who ever wrote the code was going above and beyond to model the exact frequency. The clock name is clk_491p52 which implies a 491.52 MHz clock. That translates to a period of 2.03450520833ns

When you calculate the average period from the Verilog code, it is also 2.03450520833ns: ( (1.017ns+1.017ns+1.017ns+1.018ns)*95 + (1.017ns+1.018ns+1.017ns+1.018ns) )/96/2

The timescale is set to 1ps, which is not enough to perfectly model the clock frequency. The smallest timescale Verilog supports is 1fs, which is still to big perfectly model the clock frequency. The workaround this person implemented was to round down to the 1ps and add periodically add an extra 1ps to compensate rounding. It is the same rounding concept used for determining leap year (1 year = ~365.2425 days).

Needing this level of accuracy depends on design requirements. The clock spec might be 491.52 MHz, but would ~491.642 MHz make a difference? That depends on the requirements.