Legend Lee
Legend Lee

Reputation: 64

Using verilog to generate a ripple-carry-adder with all output X

I am a beginner and I wanted to write a ripple-carry-adder using the generate block. So I write the following module:

module ripple_carry_adder(ia, ib,  ci,  so,  co);

parameter N = 32;
input[N-1:0] ia;
input[N-1:0] ib;
input ci;
output[N-1:0] so;
output co;

wire [N:0] carry;
assign carry[0] = ci;

genvar j;
generate for(j = 0; j < N; j = j + 1) 
begin:r_loop
    wire t1, t2, t3;
    xor g1(t1, ia[i], ib[j]);
    xor g2(so[j], t1, carry[j]);
    and g3(t2, ia[i], ib[j]);
    and g4(t3, t1, carry[j]);
    or g5(carry[j+1], t2, t3);
end
endgenerate

assign co = carry[N];
endmodule

And the testbench module:

`include "ripple_carry_adder.v"
`timescale 1ns/1ps
module ripple_carry_adder_tb;

parameter N = 32;

reg clk;
reg[N-1:0] a, b;
wire[N-1:0] sum;
reg cin;
wire cout;

ripple_carry_adder rca(.ia(a), .ib(b), .ci(cin), .so(sum), .co(cout));
initial begin
    #10;
    a = 0;
    b = 0;
    cin = 0;
    clk = 0;
    #10;
end

always @(posedge clk)
begin
    #50;
    #1 a <= $random() % 1000000;
    #1 b <= $random() % 1000000;
end

always @(a or b)
    #5 $display("%d + %d = %d", a, b, sum);

always #5 clk = ~clk;

endmodule

But I got the result with all bits unknown: result

I have spent 1 hour in vain trying to find the mistake. Can you help me?

Upvotes: 0

Views: 2887

Answers (1)

Greg
Greg

Reputation: 19122

As stated in my comment, the i in ia[i] is undefined. Changing it to j should get the desired functionality.

Verilog will treat any undeclared variable as a single bit wire, it is considered normal benavior and you will rarely get warnings. Some simulators have options to flag undeclared variables. There is a univeral option as well that was added in IEEE Std 1364-2001 (aka Verilog-2001). You can override the default net type with the `define_nettype macro. By setting it to none all nets after the macro declaration must be explicitly declared. You can get more details on default_nettype by reading IEEE Std 1364-2001 § 19.2 `default_nettype or IEEE Std 1800-2012 § 22.8 `default_nettype

Upvotes: 1

Related Questions