Writing The Testbench
Part of the Fundamentals section of Coddy's Verilog journey — lesson 82 of 90.
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:
- Declares signals (
regfor clk and reset,wirefor red, yellow, green) - Instantiates the
traffic_lightmodule with nameuut - Generates a clock that toggles every 1 time unit
- Applies reset for 2 time units, then releases it
- 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
endmoduleAll lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorComparison OperatorsRecap - Simple MathBitwise Operators7Assign And Gates
Continuous AssignmentAssign With OperatorsBuilt In Gate PrimitivesAND OR NOT GatesXOR XNOR GatesRecap - Logic Gate Circuit10Decision Making
If StatementIf - ElseRecap - Simple ComparatorCase StatementCasex And CasezRecap - ALU Design5Operators Part 2
Logical OperatorsReduction OperatorsShift OperatorsConcatenation OperatorConditional OperatorRecap - Operator Challenge3Number System
Binary RepresentationSized NumbersUnsized NumbersNegative NumbersSpecial Values X And ZRecap - Number Formats6Modules
Module StructureInput And Output PortsInout PortsModule InstantiationPort Mapping By NamePort Mapping By OrderRecap - Build A Module9Procedural Blocks
Always BlockInitial BlockSensitivity ListBlocking AssignmentNon Blocking AssignmentRecap - Always vs Initial15Traffic Light Controller
Defining The StatesState Machine Logic