Menu
Coddy logo textTech

Clock Generation

Part of the Fundamentals section of Coddy's Verilog journey — lesson 71 of 90.

A clock is a signal that continuously toggles between 0 and 1 at regular intervals. Clocks are essential for sequential logic like flip-flops and counters.

Why Generate a Clock

In testbenches, you need a clock to test sequential circuits. The clock drives the behavior of flip-flops, registers, and state machines.

Methods to Generate a Clock

MethodDescription
always with # delayMost common method
forever loopAlternative method
repeat loopFor fixed number of cycles

Method 1: Always Block with Delay

reg clk;

initial begin
  clk = 0;
end

always #5 clk = ~clk;
  • clk = 0 at time 0
  • Every 5 time units, clk toggles
  • Period = 10 time units
  • Frequency = 1/10 = 0.1 per time unit

Method 2: Forever Loop

reg clk;

initial begin
  clk = 0;
  forever begin
    #5 clk = ~clk;
  end
end

Same result as the always method.

Method 3: Repeat for Fixed Cycles

reg clk;

initial begin
  clk = 0;
  repeat (10) begin
    #5 clk = ~clk;
  end
end

Generates exactly 10 clock edges (5 complete cycles), then stops.

challenge icon

Challenge

Add the missing code to generate a clock that toggles every 4 time units (period = 8 time units).

What to do:

  1. Initialize clk to 0 at time 0 using an initial block
  2. Use an always block with a delay to toggle clk every 4 time units

Cheat sheet

A clock toggles between 0 and 1 at regular intervals. Period = 2 × delay.

Method 1: Always block (most common)

reg clk;

initial begin
  clk = 0;
end

always #5 clk = ~clk; // Period = 10

Method 2: Forever loop

initial begin
  clk = 0;
  forever #5 clk = ~clk;
end

Method 3: Repeat (fixed number of edges)

initial begin
  clk = 0;
  repeat(10) #5 clk = ~clk; // 10 edges = 5 cycles
end

Try it yourself

module clock_challenge;
  reg clk;
  
  // TODO: Step 1 - Add initial block to set clk = 0
  
  
  // TODO: Step 2 - Add always block to toggle clk every 4 time units
  

  initial begin
    $monitor("Time %0t: clk = %b", $time, clk);
    #20;
    $display("Clock generated for 20 time units");
    $finish;
  end
endmodule
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals