Menu
Coddy logo textTech

Testbench

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

challenge icon

Challenge

A testbench provides inputs to your design and creates a waveform file. It has no ports of its own.

Your Task

Create a testbench that:

  1. Declares reg for clk, start, and data_in (8 bits)
  2. Declares wire for tx and wire [3:0] for cnt
  3. Instantiates the uart_tx module, connecting all ports: .clk, .start, .data_in, .tx, .cnt
  4. Generates a clock (toggle every 5 time units)
  5. Inside an initial block:
    • Creates a waveform file named uart.vcd using $dumpfile and $dumpvars
    • Sets clk = 0, start = 1, data_in = 8'b01000001 at time 0
    • Releases start after 10 time units (start = 0)
    • Runs for 200 time units

After running the testbench, open the waveform to verify the tx signal.

Try it yourself

module uart_tx (
  input clk,
  input start,
  input [7:0] data_in,
  output reg tx,
  output reg [3:0] cnt
);

  reg [9:0] shift_reg;

  initial begin
    cnt = 0;
    tx = 1;
    shift_reg = 0;
  end

  always @(posedge clk) begin
    if (cnt == 0 && start) begin
      shift_reg <= {1'b1, data_in, 1'b0};
      cnt <= 1;
    end
    else if (cnt > 0 && cnt < 9) begin
      tx <= shift_reg[0];
      shift_reg <= shift_reg >> 1;
      cnt <= cnt + 1;
    end
    else if (cnt == 9) begin
      tx <= shift_reg[0];
      shift_reg <= shift_reg >> 1;
      cnt <= 0;
    end
  end

endmodule

All lessons in Fundamentals