Search code examples
undefinedverilogcomparatortest-bench

8 bit comparator from 4 bit comparator - undefined outputs


I have the following code that correctly compares numbers when they are equal to or greater than one another. It does not however generate a less than output. It always pops out as undefined.

What am I missing here?

module FourBitComparator (input [3:0]a, 
                          input [3:0]b, 
                          output eq, 
                          output gt, 
                          output lt);
    assign eq = a == b;
    assign gt = a > b;
    assign lt = a < b;

endmodule


module EightBitComparator(input [7:0]a,
                          input [7:0]b,
                          output eq,
                          output gt,
                          output lt);
    wire [3:0]a1;
    wire [3:0]a2;
    wire [3:0]b1;
    wire [3:0]b2;
    assign a1 = {a[3:0]};
    assign a2 = {a[7:4]};
    assign b1 = {b[3:0]};
    assign b2 = {b[7:4]};
    FourBitComparator BC_2( a2, b2, eq, gt, lt);
    FourBitComparator BC_1( a1, b1, eq, gt, lt);
endmodule

Testbench

module EightBitCompTB;

    // Variables
    reg [7:0] a, b;
    wire eq, gt, lt;

    // Call comaparator
    EightBitComparator BC_1(a, b, eq, gt, lt);

    // Test inputs
    initial begin
        $monitor("%d a=%b, b=%b, eq=%b, gt=%b, lt=%b",
                 $time,
                 a, b, eq, gt, lt);
        #10 
        a = 15;
        b = 15;
        #10 
        a = 255;
        b = 0;
        #10
        a = 74;
        b = 80;
        #10
        a = 65;
        b = 50;
    end

endmodule

Solution

  • You have contention: two drivers are driving the same signal. In EightBitComparator, the two FourBitComparator lt outputs are driving the same lt signal. When BC_1.lt=0 and BC_2.lt=1, or vice versa, you get an x (unknown). A good debugging tool can detect this situation for you.

    The same is true for gt.

    You need to redesign your logic.

    Why can't you just simplify?

    module EightBitComparator(input [7:0]a,
                              input [7:0]b,
                              output eq,
                              output gt,
                              output lt);
        assign eq = a == b;
        assign gt = a > b;
        assign lt = a < b;
    endmodule