I am unable to understand the error in this code that is preventing an output to be displayed

Viewed 26
module Calculator(out,a,b,op);
  input [3:0] a,b;
  input [1:0] op;
  output [4:0] out;

  reg [32:0] out;
  
  initial
  begin
    case(op)
      2'b00: out <= a+b;
      2'b01: out <= a-b;
      2'b10: out <= a*b;
      2'b11: out <= a/b;
    endcase
    out = a+b;
  end
endmodule

module test_Calci;
      reg [3:0]a,b;
      reg [1:0] op;
      wire [32:0] out;
      
Calculator ca1 (out,a,b,op);

initial
begin
    #40 a=32'b1; b=32'b1; op = 2'b00;
end
endmodule

The code is successfully compiling, but the output is not being displayed.

The attached image is of the simulation.

1 Answers

The initial block inside the Calculator module only executes once at time 0. At that time, the last statement which is executed (out = a+b) assigns out to the value X because a and b are X. out never gets assigned again.

You want out to be assigned every time any of the inputs change value. To do that, use an always block:

module Calculator(out,a,b,op);
  input [3:0] a,b;
  input [1:0] op;
  output reg [32:0] out;
  
  always @* begin
    case(op)
      2'b00: out = a+b;
      2'b01: out = a-b;
      2'b10: out = a*b;
      2'b11: out = a/b;
    endcase
  end
endmodule

I made other changes to your code as well. For combinational logic, it is a good practice to use blocking assignments (=) instead of nonblocking (<=).

You should not have the assignment to out outside of the case statement since it will override the value assigned in the case.

You declare out with 2 different bit widths, which is a little strange. I merged them into one declaration.

Related