How to access register in FPGA Verilog?
In Verilog, “registers” are just flip-flops you create with sequential logic and then expose/read through signals or a bus. Below is a practical cheat-sheet covering declaring, writing, reading, memory-mapped access, register files/BRAM, and best practices.
1) A register = flip-flop updated on a clock
Key rules
-
Use non-blocking
<=in sequentialalways @(posedge ...)blocks. -
Reading a register is just using its signal (
q=r).
SystemVerilog tip: use
logicandalways_ff(cleaner), but plain Verilog works fine.
2) Bit fields (read/modify/write)
Often you need to set/clear bits:
Or mask writes from a bus:
3) Memory-mapped registers (MMIO) – “access from software”
Expose a few registers on a simple bus: addr, wdata, rdata, we, re.
Notes
-
This style synthesizes well and is easy to adapt to APB/AHB/AXI-Lite/Wishbone front ends.
-
For AXI-Lite, the same registers live behind the AXI handshake logic.
4) Register files (arrays) and BRAM
Small register files (e.g., 32×32, 2 read / 1 write) can be “distributed RAM” (LUTs):
Larger memories should infer block RAM (usually synchronous read):
Need ROM/init? Use
$readmemh("init.hex", mem);in aninitialblock (synth-supported on most FPGAs).
5) Accessing a register from another module
-
Right way (synthesizable): pass it through ports (like
q, or a bus). -
Wrong for synthesis: hierarchical references
top.u1.r(OK in testbenches only). -
For debug, use vendor ILAs/SignalTap or expose status via MMIO.
6) Crossing clock domains (CDC)
If software/bus clock ≠ logic clock:
-
Use sync flops for single-bit controls (two-FF synchronizer).
-
For multi-bit data, use handshake (valid/ready) or dual-clock FIFOs.
-
Don’t directly sample one clock domain in another.
7) Common pitfalls
-
Mixing blocking and non-blocking in the same always block → racey hardware.
-
Multiple always blocks driving the same reg → multiple drivers.
-
Latches inferred (missing
else/default) when you meant flops. -
Assuming BRAM is async read—on most FPGAs it’s sync.
-
Forgetting reset behavior (some FPGAs allow power-up init, but be explicit).
8) Minimal testbench “peek/poke” (simulation only)
Use this only in tb; hardware can’t do that—use MMIO if you need software access.
.jpg)
评论
发表评论