Level 37: Memory and Time
Task
Build an 8-bit register from D flip-flops. The register stores 8 bits of data and updates on the rising edge of clk.
Module Reg8 takes an 8-bit bus in[7:0] and a 1-bit clk, and outputs out[7:0].
Use generate-for to instantiate 8 D flip-flops. Each DFF stores one bit: q = d on the rising edge of clk.
Key insight: this is the first sequential level — the simulator processes clock ticks sequentially, and state persists between tests.
Related Materials
- DFF — D Flip-Flop
Solution
A register is an array of D flip-flops, each storing one bit. Instead of writing 8 lines manually, use generate-for.
generate-for is a robot assembler: it clones 8 DFFs spatially, placing them side by side. It is NOT a time loop: by the time the circuit runs, the "loop" has already been unrolled — 8 flip-flops physically sit on the board. The commands inside generate-for run at build time, not at run time.
- Declare the index variable:
genvar i; - Open the generate block:
generate - Loop over 8 bits:
for (i = 0; i < 8; i = i + 1) begin : dff_gen - Inside — one DFF per bit:
dff d(out[i], in[i], clk); - Close:
end endgenerate
DFF port order: (q, d, clk). Output q becomes out[i], input d is in[i], and clk is shared across all DFFs.