Search code examples
verilogadditionsigned

Verilog Signed Addition Subtraction error


I've been working on a Verilog program that is supposed to add a signed 8-bit input to the 16-bit output on every clock increment and reset on receiving a reset signal. The addition portion is working fine, and even adding the negative 1 value works, but I'm getting strange results in the simulation for numbers less than that. It's been about a year since I last used Verilog, and despite trying everything I can think of, I'm uncertain what the problem is. Here's what I have as far as code:

module varcount (clk, reset, in, out);
input clk, reset;
input [7:0] in;
output reg [15:0] out;
reg [15:0] temp;
reg [15:0]count;
parameter X=1000000;
always @ (posedge clk)
   begin
    if (in[7] == 1)
    begin
    temp = 16'b00000000000000001 + !in;
    count = count - temp;
    if (reset)
    begin
        count = 0;
        out = 0;
    end
    out = count;
end
    else
    begin
        count = count + in;
        if (reset)
        begin
            count = 0;
            out = 0;
        end
        out = count;
    end
end
endmodule

Here's my simulation input:

enter image description here

And here's the output that I get.

enter image description here

It seems like a straight-forward error in my program, but I can't identify it.


Solution

  • The problem is you are doing a logical negation of in versus a bitwise negation.

    Your code could be greatly simplified by

    • moving the reset conditional branch to the top level
    • using signed data types
    • using Verilog-2001 style port declarations

    For example:

    module varcount (input clk, reset, 
              wire signed [7:0] in, 
       output reg signed [15:0] out);
     always @ (posedge clk)
                if (reset)
                  out = 0;
                else
                  out = out + in;
    endmodule