Search code examples
verilogsystem-verilog

Module output becomes "x"


I'm writing a 3-way comparator which takes two inputs, a and b, and returns output 0 if a<b, 1 if a==b, 2 if a<b

I have written code of the comparator, but I came across its incomprehensible behavior. Its output is always "x". I would appreciate if someone help me find out what is wrong with my code.

This is my code.

module test_bench;
  logic a, b, out;

  compare compare (
      .a  (a),
      .b  (b),
      .out(out)
  );

  initial begin
    a = 1;
    b = 0;
    $display("a>b => out=%d", out);

    a = 1;
    b = 1;
    $display("a=b => out=%d", out);

    a = 1;
    b = 2;
    $display("a<b => out=%d", out);
  end
endmodule

// maybe something is wrong in this module?
module compare (
    input  logic a,
    b,
    output logic out
);

  always_comb begin
    if (a > b) out = 0;
    else if (a == b) out = 1;
    else out = 2;
  end

endmodule

and this is what I got in display.

a>b => out=x
a=b => out=x
a<b => out=x

Solution

  • The problem is with your test_bench stimulus. You apply values to the inputs with 0 delay and that does not give any chance for the values to propagate through the compare module.

    Add some delay between each group of stimulus.

     initial begin
        a = 1;
        b = 0;
        #5  $display("a>b => out=%d", out);
    
        a = 1;
        b = 1;
        #5 $display("a=b => out=%d", out);
    
        a = 1;
        b = 2;
        #5 $display("a<b => out=%d", out);
      end
    endmodule