Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

4 to 1 Multiplexer/Mux: Testbench

Verilog Examples

Runnable example from the Verilog 4 to 1 Multiplexer/Mux tutorial (Testbench)

Open in IDE
design.v
module mux_4to1_case (
  input      [3:0] a,     // Data input, selected when sel = 2'b00
  input      [3:0] b,     // Data input, selected when sel = 2'b01
  input      [3:0] c,     // Data input, selected when sel = 2'b10
  input      [3:0] d,     // Data input, selected when sel = 2'b11
  input      [1:0] sel,   // 2-bit select
  output reg [3:0] out    // reg because it is assigned in an always block
);

  // @(*) re-evaluates the block whenever any input it reads changes,
  // which is exactly the behavior of combinational hardware
  always @(*) begin
    case (sel)
      2'b00 : out = a;   // Blocking (=) assignments for combinational logic
      2'b01 : out = b;
      2'b10 : out = c;
      2'b11 : out = d;   // All 4 sel values covered, so no latch is inferred
    endcase
  end

endmodule
testbench.v
module tb_4to1_mux;

   // Testbench regs drive the design inputs; a wire collects the output
   reg [3:0] a;
   reg [3:0] b;
   reg [3:0] c;
   reg [3:0] d;
   wire [3:0] out;
   reg [1:0] sel;
   integer i;

   // Instantiate the case-based design; any of the four versions works here
   // because they all have the same ports
   mux_4to1_case  mux0 (   .a (a),
                           .b (b),
                           .c (c),
                           .d (d),
                           .sel (sel),
                           .out (out));

   initial begin
      // Print a line whenever sel, a, b, c, d or out changes
      $monitor ("[%0t] sel=0x%0h a=0x%0h b=0x%0h c=0x%0h d=0x%0h out=0x%0h", $time, sel, a, b, c, d, out);

      // 1. At time 0, drive random values to a/b/c/d and keep sel = 0
      sel <= 0;
      a <= $random;
      b <= $random;
      c <= $random;
      d <= $random;

      // 2. Step sel through 1, 2 and 3, one value every 5ns
      for (i = 1; i < 4; i=i+1) begin
         #5 sel <= i;
      end

      // 3. Wait 5ns after the last select change, then end the simulation
      #5 $finish;
   end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.