Pages

Sunday, October 18, 2015

Verilog Code for 2:1 MUX using if statements

This post is for Verilog beginners. 2:1 MUX is a very simple digital block with 2 data inputs, one select input and one data output.

The code follows Behavioral modelling. There are many ways you can write a code for 2:1 mux. I have used simple 'if .. else ..' statement here.

2:1 MUX:

//declare the Verilog module - The inputs and output signals.
module mux2to1(
    Data_in_0,
    Data_in_1,
    sel,
    Data_out
    );

    //what are the input ports.
    input Data_in_0;
    input Data_in_1;
    input sel;
    //What are the output ports.
    output Data_out;
    //Internal variables.
    reg Data_out;

    //Always block - the statements inside this block are executed when the given sensitivity list 
    //is satidfied. for example in this case the block is executed when any changes occur in the three signals 
    //named 'Data_in_0','Data_in_1' or 'sel'.
    always @(Data_in_0,Data_in_1,sel)
    begin
        if(sel == 0) 
            Data_out = Data_in_0;  //when select signal to the mux is low
        else
            Data_out = Data_in_1;  //when select signal to the mux is high
    end
    
endmodule


Testbench for 2:1 MUX:

module tb_mux;

    // Declaring Inputs
    reg Data_in_0;
    reg Data_in_1;
    reg sel;

    // Declaring Outputs
    wire Data_out;

    // Instantiate the Unit Under Test (UUT)
    mux2to1 uut (
        .Data_in_0(Data_in_0), 
        .Data_in_1(Data_in_1), 
        .sel(sel), 
        .Data_out(Data_out)
    );

    initial begin
        // Apply Inputs
        Data_in_0 = 0;
        Data_in_1 = 0;
        sel = 0;
        // Wait 100 ns
        #100;
        
        //Similarly apply Inputs and wait for 100 ns
        Data_in_0 = 0;      Data_in_1 = 0;      sel = 1;      #100;
        Data_in_0 = 0;      Data_in_1 = 1;      sel = 0;      #100;
        Data_in_0 = 0;      Data_in_1 = 1;      sel = 1;      #100;
        Data_in_0 = 1;      Data_in_1 = 0;      sel = 0;      #100;
        Data_in_0 = 1;      Data_in_1 = 0;      sel = 1;      #100;
        Data_in_0 = 1;      Data_in_1 = 1;      sel = 0;      #100;
        Data_in_0 = 1;      Data_in_1 = 1;      sel = 1;      #100;
    end
      
endmodule


Simulation waveform:

When the codes are correctly simulated you should be able to get the following waveform:



The code was tested on Xilinx ISE 13.1. But it should work on almost all compilers and simulators.

2 comments: