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

Combinational Logic with assign: Testbench

Verilog Examples

Runnable example from the Combinational Logic with assign tutorial (Testbench)

Open in IDE
design.v
module mux_2x1 (input 	a, b, sel,
								output 	c);

	// Ternary operator: sel ? true_value : false_value
	// When sel=1, output c gets input a
	// When sel=0, output c gets input b
	// Synthesizes to a 2:1 mux gate or equivalent logic
	assign c = sel ? a : b;
endmodule
testbench.v
module tb;
	// Declare testbench variables
	reg a, b, sel; // Two data inputs and one select
	wire c; // Multiplexer output
	integer i;

	// Instantiate the design and connect design inputs/outputs with
	// testbench variables
	mux_2x1 u0 ( .a(a), .b(b), .sel(sel), .c(c));

	initial begin
		// At the beginning of time, initialize all inputs of the design
		// to a known value, in this case we have chosen it to be 0.
		a = 0;
		b = 0;
		sel = 0;

		$monitor("a=%0b b=%0b sel=%0b c=%0b", a, b, sel, c);

		// Test all 8 input combinations
		for (i = 0; i < 8; i = i + 1) begin
			{a, b, sel} = i;
			#10;
		end
	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.