Menu
Coddy logo textTech

Writing The Testbench

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

challenge icon

Challenge

In this lesson, you will create a testbench to verify that the traffic light controller works correctly.

What to do:

Create a testbench that:

  1. Declares signals (reg for clk and reset, wire for red, yellow, green)
  2. Instantiates the traffic_light module with name uut
  3. Generates a clock that toggles every 1 time unit
  4. Applies reset for 2 time units, then releases it
  5. Runs the simulation for 100 time units

Try it yourself

module traffic_light (
  input clk,
  input reset,
  output reg red,
  output reg yellow,
  output reg green
);

  reg [1:0] state;
  reg [5:0] counter;

  // Output assignments
  always @(*) begin
    case (state)
      0: begin green = 1; yellow = 0; red = 0; end
      1: begin green = 0; yellow = 1; red = 0; end
      2: begin green = 0; yellow = 0; red = 1; end
      default: begin green = 0; yellow = 0; red = 1; end
    endcase
  end

  // State machine with timing
  always @(posedge clk or posedge reset) begin
    if (reset) begin
      state <= 2;
      counter <= 0;
    end else begin
      if (counter == 0) begin
        case (state)
          0: begin
            state <= 1;
            counter <= 10;
          end
          1: begin
            state <= 2;
            counter <= 40;
          end
          2: begin
            state <= 0;
            counter <= 30;
          end
        endcase
      end else begin
        counter <= counter - 1;
      end
    end
  end

endmodule

module testbench;
  // TODO: Declare reg for clk and reset
  
  // TODO: Declare wire for red, yellow, green
  

  // TODO: Instantiate traffic_light module with name uut
  // Connect clk, reset, red, yellow, green
  

  // TODO: Generate clock (toggle every 1 time unit)
  

  initial begin
    $display("Traffic Light Test");
    
    // TODO: Initialize clk to 0
    
    // TODO: Apply reset (reset=1 for 2 time units, then reset=0)
    
    
    // TODO: Run simulation for 100 time units
    
    
    $display("Test complete");
    $finish;
  end
endmodule

All lessons in Fundamentals