Home / Learn Chip Programming / Parameters, Generate and Reusable Modules
Parameters, Generate and Reusable Modules
Write one module and reuse it with different widths and counts.
Theory in plain words
What it is
parameter and localparam configure modules at compile time (data width, depth). generate for/if creates repeated hardware. Functions and tasks help with constants (clog2).
Why we use it
Reusable parametrised modules (FIFO, counter, adder) are how professionals avoid copy-paste bugs.
How it works
Define module #(parameter WIDTH = 8) (...). Instantiate with #(.WIDTH(16)). Use $clog2 to compute address widths. Use generate to create arrays of identical blocks.
Where it is used
- Parametrised FIFO or UART
- N-bit adders and shifters
- Arrays of LEDs or PWM channels
Width and ripple adder
The same module works for 2, 4 or 64 bits just by changing WIDTH.
module add_n #(parameter W = 8) (input [W-1:0] a, b, input cin, output [W-1:0] s, output cout);
wire [W:0] c;
assign c[0] = cin;
genvar i;
generate
for (i = 0; i < W; i = i + 1) begin : fa
assign s[i] = a[i] ^ b[i] ^ c[i];
assign c[i+1] = (a[i] & b[i]) | (c[i] & (a[i] ^ b[i]));
end
endgenerate
assign cout = c[W];
endmodule
// add_n #(.W(16)) u (.a(x), .b(y), .cin(1'b0), .s(sum), .cout(carry));assign {cout, s} = a + b + cin;: the tool uses the fast carry chain. The generate version is for learning and for custom structures.Quick quiz
1. What does $clog2(256) return?
Ceiling of log2.
2. Why parametrise modules?
One source, many configurations.
Common questions
What does $clog2(256) return?
8. Ceiling of log2.
Why parametrise modules?
Reuse with different sizes. One source, many configurations.