Writing The Testbench
Part of the Fundamentals section of Coddy's Verilog journey. Lesson 45 of 90.
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 andwire 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
- Inside
testbench, add aninitial beginblock - 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);
- Add
$finish;to end the test - Add
endto close the initial block, thenendmoduleto closetestbench
Try it yourself
module half_adder (
input a,
input b,
output sum,
output carry
);
assign sum = a ^ b;
assign carry = a & b;
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 LogicPractice on your own: Online Verilog compiler