Skip to content
systemcoding.dev
Hardware

Generate a testbench clock with always (#5 clk = ~clk)

Drive a 100 MHz testbench clock with a one-line always block, and see why the initial value and the timescale decide whether it works.

1 min read
Summarize in AI

The shortest testbench clock is one line, and it needs two things around it. The always block inverts clk every 5 time units, so the period is 10. The register must start at a known value, because an x inverted is still x and the clock never ticks.

tb.vverilog
`timescale 1ns/1ps
module tb;
    reg clk = 1'b0;
    always #5 clk = ~clk;

    initial begin
        repeat (3) @(posedge clk) $display("posedge at %0d ns", $time);
        $finish;
    end
endmodule
Text
posedge at 5 ns
posedge at 15 ns
posedge at 25 ns

The simulator also prints its own finish line after $finish, which varies by tool. With 1ns/1ps the #5 means 5 ns, so the period is 10 ns, a 100 MHz clock. The first rising edge comes at 5 ns because the register starts low and the first toggle is a rise.

Without a timescale directive the delay unit depends on the tool's default, and Icarus Verilog 12 uses 1 s. That does not change the edge ordering, but the times you read in a waveform mean nothing. For an odd period, such as 12 MHz, write the half period in the right unit, for example #41.667 under 1ns/1ps, since integer delays truncate to the time unit.

Taggedverilog
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.