Menu
CoddyTech

Writing The Testbench

Part of the Fundamentals section of Coddy's Verilog journey. Lesson 45 of 90.

challenge icon

Challenge

Now we need to test if the half adder is working correctly. A testbench is a separate module that drives the inputs of your design and prints its outputs. Keep your half_adder module as it is and add the testbench below its endmodule.

What to do:

Step 1: Create the testbench module

  • Start a new module with no ports: module testbench;
  • Declare reg a, b; for the inputs and wire sum, carry; for the outputs
  • Connect them to your design: half_adder uut (.a(a), .b(b), .sum(sum), .carry(carry));

Step 2: Add the test code

  1. Inside testbench, add an initial begin block
  2. Inside the block, add:
$display("a b | sum carry"); 
a = 0; b = 0; #1 $display("%d %d |  %d    %d", a, b, sum, carry); 
a = 0; b = 1; #1 $display("%d %d |  %d    %d", a, b, sum, carry); 
a = 1; b = 0; #1 $display("%d %d |  %d    %d", a, b, sum, carry); 
a = 1; b = 1; #1 $display("%d %d |  %d    %d", a, b, sum, carry);
    
  1. Add $finish; to end the test
  2. Add end to close the initial block, then endmodule to close testbench

Try it yourself

module half_adder (
  input a,
  input b,
  
  output sum,
  output carry
);
  assign sum = a ^ b;
  assign carry = a & b;
  
endmodule

All lessons in Fundamentals

Practice on your own: Online Verilog compiler