Verilog Coding Tips and Tricks: Verilog Code for 4 bit Comparator

Monday, October 19, 2015

Verilog Code for 4 bit Comparator

There can be many different types of comparators. Here, I have designed, a simple comparator with two 4 bit inputs and three output bits which says, whether one of the input is less,greater or equal to the second input.

The code is written in behavioral model. Even though it checks for 4 bit inputs, the code can be extended for other input sizes with very small changes.

4 bit Comparator:

//declare the Verilog module - The inputs and output signals.
module comparator(
    Data_in_A,  //input A
    Data_in_B,  //input B
    less,       //high when A is less than B
    equal,       //high when A is equal to B
     greater         //high when A is greater than B    
    );

    //what are the input ports.
    input [3:0] Data_in_A;
    input [3:0] Data_in_B;
    //What are the output ports.
    output less;
     output equal;
     output greater;
     //Internal variables
     reg less;
     reg equal;
     reg greater;

    //When the inputs and A or B are changed execute this block
    always @(Data_in_A or Data_in_B)
     begin
        if(Data_in_A > Data_in_B)   begin  //check if A is bigger than B.
            less = 0;
            equal = 0;
            greater = 1;    end
        else if(Data_in_A == Data_in_B) begin //Check if A is equal to B
            less = 0;
            equal = 1;
            greater = 0;    end
        else    begin //Otherwise - check for A less than B.
            less = 1;
            equal = 0;
            greater =0;
        end 
    end
endmodule

Testbench for Comparator:

module tb_tm;

    // Inputs
    reg [3:0] Data_in_A;
    reg [3:0] Data_in_B;

    // Outputs
    wire less;
    wire equal;
    wire greater;

    // Instantiate the Unit Under Test (UUT)
    comparator uut (
        .Data_in_A(Data_in_A), 
        .Data_in_B(Data_in_B), 
        .less(less), 
        .equal(equal), 
        .greater(greater)
    );

    initial begin
        //Apply inputs
        Data_in_A = 10;
        Data_in_B = 12;
        #100;
        Data_in_A = 15;
        Data_in_B = 11;
        #100;
        Data_in_A = 10;
        Data_in_B = 10;
        #100;
    end
      
endmodule

Simulation waveform:

The codes when correctly simulated, will show you the following waveform in Xilinx ISE 13.1.


9 comments:

  1. module comparator(G, L, E, a, b)
    input [0: 3]a, b;
    output G, L, E;

    assign G= a>b;
    assign L= a<b;
    assign E= (a==b) ;
    endmodule

    ReplyDelete
    Replies
    1. Can u provide testbench for this program

      Delete
    2. Testbench is same as above one
      Testbench is same same for all styles

      Delete
  2. how to write it in gate level? i want gate level code for 4 bit comparator.

    ReplyDelete