Verilog Gray Counter Modul – 4-Bit Gray-Code Generator
Design
Ein Gray-Code-Zähler erzeugt eine Folge, in der sich benachbarte Werte nur in genau einem Bit unterscheiden. Die Implementierung nutzt einen binären Zähler q und wandelt dessen Wert kombinatorisch in Gray-Code um: G = B ⊕ (B >> 1). Ein `ifdef zeigt zwei äquivalente Implementierungen (Schleife vs. Vektor-Operation).
module gray_ctr #(
parameter int N = 4
) (
input logic clk,
input logic rstn,
output logic [N-1:0] out
);
logic [N-1:0] q;
always_ff @(posedge clk) begin
if (!rstn) begin
q <= '0;
out <= '0;
end else begin
q <= q + 1;
`ifdef FOR_LOOP
for (int i = 0; i < N-1; i++) begin
out[i] <= q[i+1] ^ q[i];
end
out[N-1] <= q[N-1];
`else
out <= {q[N-1], q[N-1:1] ^ q[N-2:0]};
`endif
end
end
endmodule
Testbench
module tb;
parameter int N = 4;
logic clk, rstn;
logic [N-1:0] out;
gray_ctr #(.N(N)) u0 (
.clk (clk),
.rstn (rstn),
.out (out)
);
always #10 clk = ~clk;
initial begin
clk = 0;
rstn = 0;
$monitor("T=%0t rstn=%0b out=0x%0h", $time, rstn, out);
repeat (2) @(posedge clk);
rstn = 1;
repeat (20) @(posedge clk);
$finish;
end
endmodule
Simulationsergebnis
Die Ausgabe folgt der 4-Bit-Gray-Code-Sequenz: 0 → 1 → 3 → 2 → 6 → 7 → 5 → 4 → C → D → F → E → A → B → 9 → 8 → 0 …
ncsim> run T=0 rstn=0 out=0xx T=10 rstn=0 out=0x0 T=30 rstn=1 out=0x0 T=50 rstn=1 out=0x1 T=70 rstn=1 out=0x3 T=90 rstn=1 out=0x2 T=110 rstn=1 out=0x6 ... T=350 rstn=1 out=0x0 Simulation complete via $finish(1) at time 430 NS
Verilog
- Verilog meistern: Komplettes Tutorial für digitales Schaltungsdesign
- Verilog Concatenation meistern: Praktischer Leitfaden
- Verilog Assignments verstehen: Typen, Syntax und Best Practices
- Verilog Blocking vs. Non-Blocking: Wichtige Unterschiede erklärt
- Verilog Functions meistern für effizientes RTL-Design
- Verilog Tasks verstehen: Functions vs. Tasks, Syntax und Verwendung
- Verilog Clock Generator: Design & Implementierungsleitfaden
- Verilog Math Functions meistern für effizientes Hardware-Design
- Verilog $timeformat meistern: Präzision und Anzeigesteuerung
- Verilog T-Flipflop designen: RTL-Implementierung & Testbench