verilogsystem-verilog

Output not updated as expected


I have been playing with Verilog, and I am just starting. I have implemented several logic gates from NAND which are working, but now I have hit a dead-end when trying to perform on OR on several bits.

The module in Verilog outputs wrong value (either 0 or X), the goal is to perform on OR on all the bits; however, the code is not working even when only the 1st bit is evaluated.

Inputs: in_a = 1
Output: out = x
Inputs: in_a = 0
Output: out = 0
Inputs: in_a = 25
Output: out = x
Inputs: in_a = 32
Output: out = 0
Inputs: in_a = 4180
Output: out = 0
Inputs: in_a = 0
Output: out = 0
module Or8Way( input [7:0] in_a, output out);
    reg tmp_in = 0;
    or(out, in_a[0], tmp_in);  
    // etc, 
endmodule

module OR8;
    reg  [7:0] in_a;
    wire out = 0; 
    
    Or8Way or8_gate(in_a,out);

    initial begin       
        $display("Inputs: in_a = 1");
        in_a = 1;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 0");
        in_a = 0;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 25");
        in_a = 25;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 32");
        in_a = 32;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 4180");
        in_a = 4180;
        #20 $display("Output: out = %b", out);
        $display("Inputs: in_a = 0");
        in_a = 0;
        #20 $display("Output: out = %b", out);
    end
endmodule

Solution

  • There are 2 bugs in your code.

    This line produces X on your output because of driver contention:

    wire out = 0; 
    

    It continuously drives 0 on the out net. When the or8_gate instance drives a 1, there is contention, resulting in the unknown value X. To fix it, simply declare the wire as:

    wire out; 
    

    Refer to IEEE Std 1800-2023, section 6.5 Nets and variables to understand the difference between net types and variable types.

    The 2nd bug is how you model the OR function. You can simply use the reduction-OR operator (|) to produce the bitwise-OR of all 8 input bits:

    module Or8Way( input [7:0] in_a, output out);
        assign out = |in_a;
    endmodule
    

    Output:

    Inputs: in_a = 1
    Output: out = 1
    Inputs: in_a = 0
    Output: out = 0
    Inputs: in_a = 25
    Output: out = 1
    Inputs: in_a = 32
    Output: out = 1
    Inputs: in_a = 4180
    Output: out = 1
    Inputs: in_a = 0
    Output: out = 0