user2956338
user2956338

Reputation: 23

how to re-write this code using generate statement?

I have a Verilog code which looks something like this.

module top (
    .
    .
    input a_2;
    input a_1;
    input a_0;
);
    bottom I_bottom(
                    .
                    .
                   .a(a_2);
                   );
    bottom I_bottom_2(
                       .
                       .
                       .a(a_2);
                      );
    bottom I_bottom_1(
                       .
                       .
                       .a(a_1);
                     );
    bottom I_bottom_0(
                      .
                      .
                      .a(a_0)
                     );
endmodule

How do I write this code using a generate statement? Please note that the inputs in top are fixed in top. I cannot change that to an array like a[2:0].

Upvotes: 0

Views: 318

Answers (2)

jskroch
jskroch

Reputation: 343

Just to make explicit the suggestion @toolic made in a comment, you could write an array of instances like so:

module top (
    input a_3,
    input a_2,
    input a_1,
    input a_0
);

    bottom I_bottom[3:0] (
                      .a({a_3,a_2,a_1,a_0})
                     );
endmodule

Note that I've renamed your instance I_bottom to I_bottom[3] and connected it to input a_3, not a_2. I'm not sure if you intended to break the pattern there.


I realize that this doesn't answer the question as asked, as it doesn't use the generate statement. I think I like the solution that does use generate better.

Upvotes: 1

Anders
Anders

Reputation: 2316

Create vector to equate with the individual port wires. Then use generate and index the vector to get at each signal. This works equally for inputs or outputs.

You do have to build the vector manually, but there is no escape from converting somewhere due to the original requirement to keep the individual port names. At least it is done only once, and done succinctly.

module top (
    .
    .
    input a_2;
    input a_1;
    input a_0;
);

wire [4:0]vec_a = {a_4, a_3, a_2, a_1, a_0};
generate genvar i;
    for(i=0; i<5; i=i+1) begin
        bottom I_bottom(
                .
                .
               .a(vec_a[i]);
        );
    end
endgenerate

endmodule

Upvotes: 4

Related Questions