Search code examples
logicveriloghdl

Four Bit Ripple Carry Adder Failing on Specific Inputs


I am implementing a four bit ripple carry adder and I am getting an error for the following tests:

input1 = 1000; input2 = 0110; carry_in = 1
input1 = 1000; input2 = 0001; carry_in = 1

Here is my code:

four-bit-adder.v

`include "one-bit-adder.v"
module four_bit_adder(input [0:3] x, input [0:3] y, input carry_in, output [0:3] sum, output carry_out, output overflow);
    wire c1, c2, c3;
    one_bit_adder add1(x[0], y[0], carry_in, sum[0], c1);
    one_bit_adder add2(x[1], y[1], c1, sum[1], c2);
    one_bit_adder add3(x[2], y[2], c2, sum[2], c3);
    one_bit_adder add4(x[3], y[3], c3, sum[3], carry_out);
    assign overflow = c3 ^ carry_out;
endmodule

one-bit-adder.v

module one_bit_adder (input a, input b, input cin, output s, output cout);
    assign s = (a ^ b) ^ cin;
    assign cout = (a && b) || (a && cin) || (b && cin);
endmodule

four-bit-adder-test.v

`include "four-bit-adder.v"
module four_bit_adder_test;
    reg [0:3]x;
    reg [0:3]y;
    reg carry_in;
    wire [0:3]sum;
    wire carry_out;
    wire overflow;
    four_bit_adder adder(x, y, carry_in, sum, carry_out, overflow);

    initial begin
        if (!$value$plusargs("x=%b", x)) begin
            $display("ERROR: please specify +x=<value> to start.");
            $finish;
        end   
        if (!$value$plusargs("y=%b", y)) begin
            $display("ERROR: please specify +y=<value> to start.");
            $finish;
        end
        if (!$value$plusargs("carry_in=%b", carry_in)) begin
            $display("ERROR: please specify +carry_in=<value> to start.");
            $finish;
        end
        
        $display("Expected: %b + %b + %b = %b", x, y, carry_in, {x + y + carry_in});
        #1 // let output propagate
        if ( {carry_out, sum} == x + y + carry_in ) // concatentates carry_out to the left of sun
            $display("PASSED: sum=%b, carry_out=%b", sum, carry_out);
        else    
            $display("FAILED: sum=%b, carry_out=%b", sum, carry_out);
    end

endmodule

I double checked all my circuits and they look fine.


Solution

  • Replace [0:3] with [3:0] everywhere in your code (design and testbench), and it will pass.

    The four_bit_adder treats [0] as the LSB, which means your bus signals should do so as well.

    Also, it is more customary to declare signals as [3:0].