verilogmodelsimalu

Wrong output value in 8-bit ALU


I want to design an 8-bit ALU. I have written this code, but when I simulate it, the output has x value. Why did it happen?

module eightBitAlu(clk, a, b,si,ci, opcode,outp);
input clk;
input [7:0] a, b;
input [2:0] opcode;
input si;
input ci;
output reg [7:0] outp;

always @(posedge clk)
begin

case (opcode)
3'b000: outp <= a - b;
3'b000 : outp <= a + b;
3'b001 : outp =0;
3'b010 : outp <= a & b;
3'b011 : outp <= a | b;
3'b100 : outp <= ~a;
endcase
end
endmodule

This is my test module:

module test_8bitAlu();

reg clk=0,a=3,b=1,si=0,ci=0,opcode=1;

eightBitAlu alu(clk, a, b,si,ci, opcode,outp);

initial begin
    #200 clk=1;
    #200 opcode=0;
    #200 opcode=2;
    #200 opcode=3;
    #200 opcode=4;
    #200;
end

endmodule

Solution

  • a and b are only 1 bit wide leaving the top 7 bits of your input ports un-driven.

    reg clk=0,a=3,b=1,si=0,ci=0,opcode=1;
    

    is equivalent to :

    reg clk    = 0;
    reg a      = 3;
    reg b      = 1;
    reg si     = 0;
    reg ci     = 0;
    reg opcode = 1;
    

    What you need is:

    reg        clk    = 0;
    reg  [7:0] a      = 3;
    reg  [7:0] b      = 1;
    reg        si     = 0;
    reg        ci     = 0;
    reg  [2:0] opcode = 1;
    wire [7:0] outp; 
    

    Further improvemnets would be to include the width on the integer assignment ie:

    reg        clk    = 1'd0;
    reg  [7:0] a      = 8'd3;
    

    b for binary, d for decimal, o for octal and h for hexadecimal in width'formatValue

    Note

    outp if not defined will be an implicit 1 bit wire.

    Your clock in the testharness also only has 1 positive edge. You may prefer to define your clock as:

    initial begin
      clk = 1'b0;
      forever begin
        #100 clk = ~clk;
      end
    end
    

    A complete version of the above is demonstrated at EDAplayground.