Abhinav kumar
Abhinav kumar

Reputation: 11

My if and else statements in verilog are not giving expected results

I am trying a simple code to compare an input to some value(threshold) and tried using the if and else condition statements to assign a variable to either 0 or 1 depending of the variable crossing the threshold or not. But, in this case I am always getting same single value for different inputs. I am new to verilog and trying to write an algorithm for a different application, in which this is my first step. Thanks in advance.

module makebig(a,z);
input signed [15:0]  a;
output reg z;
initial
begin
if (a<16'b0000000000000000) begin
 z<=1;
end
else  begin
 z<=0;
end

end
endmodule

Now the test bench of it.

module makebig_tb();

reg  signed [15:0] a;

wire z;

makebig uut(.a(a),.z(z));
initial
begin
a=16'b0100000000000000;
#5 a=16'b000000000000101;
#5 a=-2;
end
initial
begin
$monitor("a=%b,z=%b",a,z);
end
end module

I don't understand why it is not working. The output for this is something like this...

a=0100000000000000,z=0;
a=0000000000000101,z=0;
a=1111111111111110,z=0;

Upvotes: 1

Views: 882

Answers (1)

sjw
sjw

Reputation: 102

There are two errors here, and both of them have been pointed out in the comments:

  1. You are only running the comparison once (initial begin). Replace this with always @(*) begin to run it each time one of the inputs changes

  2. A comparison with an unsigned constant will result in the whole comparison being unsigned. Replace 16'b0000000000000000 with $signed(16'b0000000000000000)

This produces the expected output

a=0100000000000000,z=0;
a=0000000000000101,z=0;
a=1111111111111110,z=1;

Upvotes: 2

Related Questions