An SPI rasterizer GPU,
from FPGA to a SKY130 chip
VGA controller · framebuffer · Bresenham lines · filled rectangles · outline and filled circles — driven by an Arduino over SPI.
First on your PYNQ-Z2 with your video adapter, then the same gpu_core.v hardened with LibreLane and
wrapped in a hand-built padframe with OpenROAD, exactly like your counter8_fullchip.
Every code block below is the file in the zip, byte for byte, and every simulation picture was produced from those files.
The plan
Read this once: what you build, how the Arduino talks to the GPU, what is already verified, and where each tool runs.
What we are building
The idea
One GPU design, one RTL file set, three builds. Only the parameters of gpu_core change, so the thing you debug on the FPGA is the thing that goes into silicon.
| Build 1 · FPGA (PYNQ-Z2) | Build 2 · ASIC v1 | Build 3 · ASIC v2 (Part 7) | |
|---|---|---|---|
| Framebuffer | 320 × 240, double buffered | 40 × 30, single | 80 × 60, single |
| Pixel format | 8 bit RGB332 (256 colours) | 3 bit RGB111 (8 colours) | 8 bit RGB332 |
| Storage | Block RAM (38 × RAMB36) | 3,600 standard-cell flip-flops | 5 × OpenRAM SRAM macros |
| Screen scaling | 2 × 2 | 16 × 16 | 8 × 8 |
| Pixel clock | 25.000 MHz (MMCM) | 25.175 MHz oscillator | 25.175 MHz oscillator |
| Commands | CLEAR · LINE · RECT · CIRCLE (outline / filled) · SWAP | same | same |
| Signal pins | 4 SPI + 14 VGA + 4 LED | 11 GPIO + power-good | 16 GPIO + power-good |
| Verified here | RTL sim, Yosys xc7 estimate | RTL + gate-level sim, synthesis | RTL sim with the real OpenRAM model |
Why the ASIC framebuffer is so small
Without an SRAM macro every pixel bit is a flip-flop plus its share of a large read multiplexer. 1,200 pixels × 3 bits already costs 83 % of the 0.17 mm² of cells; all the drawing engines together are about 17 %:
The pin protocol: SPI + READY
Why SPI + one READY pin
A rasterizer GPU receives commands, not pixels. Any cheap MCU (Arduino, ESP32, Pico) should drive it with its hardware SPI, and the ASIC padframe should stay small. So the host gets three outputs and one input:
- SPI mode 0, write-only: CS, SCK, MOSI. No MISO needed.
- gpu_ready: high when the GPU accepts the next command. This is the whole flow-control scheme: wait READY → send → repeat.
- One command = one 10-byte frame while CS is low. It runs only when CS rises after exactly 80 bits. Short or long frames are ignored.
Command set
| Opcode | Name | A | B | C | D | What the GPU does | GPU busy time |
|---|---|---|---|---|---|---|---|
0x01 | CLEAR | – | – | – | – | fills the whole (back) buffer with the colour | W·H clocks · 3.07 ms FPGA, 48 µs ASIC |
0x02 | LINE | x0 | y0 | x1 | y1 | Bresenham, both end points drawn, off-screen pixels skipped | max(|dx|,|dy|) + 1 clocks |
0x03 | RECT | x | y | w | h | filled rectangle, clipped (negative x/y allowed) | visible w·h clocks |
0x04 | SWAP | – | – | – | – | FPGA: flip buffers at the next vblank · ASIC: wait for vblank | ≤ 16.7 ms |
0x05 | CIRCLE | cx | cy | r | fill | midpoint circle; D bit 0: 0 = outline, 1 = filled disc; clipped | outline ≈ 5.7·r · filled ≈ π·r² clocks |
Colours
The colour byte is always RGB332. The FPGA repeats the MSBs to drive your 4-bit-per-channel adapter; the ASIC keeps only the top bit of each channel, so the same sketch works on both:
| Name in sketch | RGB332 | bits RRRGGGBB | FPGA (RGB444 out) | ASIC v1 (RGB111 out) |
|---|---|---|---|---|
| WHITE | 0xFF | 11111111 | FFF | 111 |
| YELLOW | 0xFC | 11111100 | FF0 | 110 |
| CYAN | 0x1F | 00011111 | 0FF | 011 |
| GREEN | 0x1C | 00011100 | 0F0 | 010 |
| MAGENTA | 0xE3 | 11100011 | F0F | 101 |
| RED | 0xE0 | 11100000 | F00 | 100 |
| BLUE | 0x03 | 00000011 | 00F | 001 |
| ORANGE | 0xF0 | 11110000 | F90 | 110 |
| GREY | 0x92 | 10010010 | 99A | 111 |
| BLACK | 0x00 | 00000000 | 000 | 000 |
- SCK ≤ core clock / 8 → ≤ 3 MHz at 25 MHz (the sketch uses 2 MHz).
- Poll READY high before CS goes low; after CS goes high wait ≥ 1 µs before polling again (the GPU needs ~4 clocks to see CS).
- Coordinates use the low 12 bits as signed values: −2048 … 2047; w/h the low 12 bits unsigned; r the low 11 bits (0 … 2047). Send them as int16, big endian.
What is already verified
Everything below was run on the exact files in the zip before this page was generated. You re-run the simulation part yourself in Part 2.
| Check | Tool | Result |
|---|---|---|
| Self-checking testbench, FPGA parameters — 8 groups (incl. 15 circles) vs a golden model | Icarus Verilog 12 | PASS |
| Same testbench, ASIC v1 parameters | Icarus Verilog 12 | PASS |
| Same testbench, SRAM framebuffer with the real OpenRAM model (VLSIDA sky130_sram_macros) | Icarus | PASS |
| Full 800 × 525 VGA frame from the pins, pixel + HSYNC + VSYNC, every config | Icarus | PASS |
| Demos, every frame checked, 3 configs: pattern, starburst, circles, cube (36 frames), orbit (40 frames) | Icarus | PASS |
| Bring-up step 1 (VGA controller + adapter): real vga_test_top, 5 pictures from the VGA pins vs an independent pixel model, HSYNC width | Icarus + scripts/check_vga_test.py | 5 × 307,200 pixels match |
| Bring-up steps 2–4: real fpga_top compiled with exactly each step’s files (step 2: RECT only, step 3: + LINE, step 4: final) and its own test ROM — power-up test, new tests, regression tests, loopback through the pins; 21 frames from the VGA output | Icarus (sim/tb_selftest.v) | identical to golden-model frames |
| Refactored RTL vs the previous version: 111 cube + starburst frames from the VGA pins, 3 builds | cmp | byte-identical |
| Circle algorithm, radii 0…400: on the circle, no gaps, no overdraw, fill = outline rows | scripts/check_circle.py | ALL CHECKS PASSED |
| chip_top.v wiring: pads Hi-Z before power-good, SPI in / VGA out through pads | Icarus + pad stand-ins | PASS |
Lint of every top level with -Wall in all three builds (+ USE_POWER_PINS, as LibreLane runs it), plus vga_test_top and fpga_top with the step-2, step-3 and final core | Verilator 5.020 | 0 warnings |
| Synthesis to sky130_fd_sc_hd (tt corner) | Yosys 0.70 | 12,176 cells · 168,414 µm² · 0 latches |
| Gate-level simulation of the netlist mapped to real sky130_fd_sc_hd cells (functions read from the liberty file) vs RTL | Yosys + Icarus | identical frame — 41 commands: lines, rects, outline + filled circles; re-run after the bring-up split: same 12,176 cells, test-pattern frame identical |
| FPGA resource estimate (xc7 family) | Yosys synth_xilinx | 38 RAMB36 · ~930 LUT · 468 FF · 2 DSP48 |
| LibreLane config keys, Classic step names, PDN macro rules, Netgen recipe, KLayout DRC arguments | LibreLane 3.0.17 source | checked |
| Arduino sketch (both TARGET values) | g++ with an Arduino API stub | compiles, no warnings |
| Every pin across XDC, sketch, pin_order.cfg, chip_top.v and the floorplan; divider / DAC electrical limits | scripts/check_pins.py | ALL CONNECTIONS CONSISTENT |
Vivado, the PYNQ-Z2, LibreLane, OpenROAD, Magic and Netgen were not available in my sandbox. The configs and Tcl follow your working counter8_fullchip scripts, the LibreLane 3.0.17 source and the OpenROAD documentation. Each of those steps lists exactly what to look at.
Where each tool runs
| Task | Tool | Runs in | How you start it |
|---|---|---|---|
| RTL simulation | Icarus Verilog 13 + vvp | WSL, inside the LibreLane devshell | bash run_sims.sh |
| Waveforms | GTKWave | WSL (WSLg window) | gtkwave sim/wave.gtkw |
| FPGA build + programming | Vivado | Windows | Start menu |
| Arduino sketch | Arduino IDE 2 | Windows | Start menu |
| Macro hardening | LibreLane 3.0.17 (Yosys, OpenROAD, Magic, KLayout, Netgen) | WSL devshell | librelane config.json … |
| Chip padframe / PDN / route | OpenROAD (GUI) | WSL devshell | openroad -gui tcl/01_floorplan.tcl |
| GDS merge, extraction | Magic | WSL devshell | magic -dnull -noconsole … |
| DRC / layout viewing | KLayout | WSL devshell | klayout … |
| LVS | Netgen | WSL devshell | netgen -batch source … |
From your system report: Ubuntu 26.04 on WSL2, LibreLane v3.0.17, Yosys 0.62, Icarus 13 (devel), Verilator 5.044, KLayout 0.30.7, Magic 8.3.623, and $SKY130_PDK pointing at sky130A revision 8afc8346…. Every command on this page uses $SKY130_PDK, so nothing needs editing.
Unpack the project
Do
- Click Download the project at the top. It lands in
C:\Users\Sam\Downloads. - Open Ubuntu and paste:
mkdir -p ~/asic_projects && cd ~/asic_projects
cp /mnt/c/Users/Sam/Downloads/raster_gpu.zip .
python3 -m zipfile -e raster_gpu.zip .
cd raster_gpu && lsExpected
raster_gpu/
├── rtl/ shared GPU RTL (FPGA + ASIC)
│ ├── spi_cmd_rx.v vga_controller.v frame_buffer.v
│ └── line_renderer.v rect_filler.v circle_renderer.v gpu_core.v
├── sim/ testbenches, pad + SRAM stand-ins, GTKWave layout
├── fpga/ fpga_top.v, spi_test_host.v, selftest.mem, pynq_gpu.xdc (Part 3)
├── bringup/ the FPGA bring-up, one folder per step (Part 3)
│ ├── step1_vga/ vga_test_top.v vga_pattern.v vga_test.xdc
│ ├── step2_rect/ gpu_core.v (RECT only) selftest.mem
│ └── step3_line/ gpu_core.v (+ LINE) selftest.mem
│ (step 4 = rtl/gpu_core.v + fpga/selftest.mem, the final files)
├── arduino/gpu_demo/ gpu_demo.ino (Part 3)
├── asic/ LibreLane design dir: config.json, gpu.sdc,
│ └── src/ pin_order.cfg, src/ = rtl copy + gpu_asic.v (Part 5)
├── chip/ rtl/chip_top.v + tcl/01…06 (Part 6)
├── asic_sram/ SRAM framebuffer version (Part 7)
├── scripts/ gen_demo.py, gen_selftest.py, hex2png.py, check_pins.py,
│ check_circle.py, check_vga_test.py
└── run_sims.sh every simulation + the pin cross-check, one commandrtl/ is the master copy. asic/src/ and asic_sram/src/ hold copies because LibreLane likes all sources inside its design folder. After editing rtl/, re-copy with cp rtl/*.v asic/src/.
The RTL, one module at a time
Seven small files. The three drawing engines only walk their shape and say "plot (x, y)"; clipping, colour and addressing are written once in gpu_core. For every module: the idea, the algorithm step by step, the ports, the code, and a waveform from the real simulation.
How the RTL is organised (read this first)
One interface for every drawing engine
Every engine — line, rectangle, circle — has the same shape:
| Port | Meaning |
|---|---|
start + arguments | one-clock pulse from gpu_core; the arguments are valid in that clock and are copied inside |
busy | high from the clock after start until the last pixel; READY is low while any engine is busy |
plot, x, y | "(x, y) is a pixel of my shape" — one pixel per clock |
The engines do not know the colour, the screen size (except for skipping invisible circle spans), the memory layout or which buffer is drawn. gpu_core picks the engine that is plotting, throws away off-screen pixels, computes y · W + x once and writes the latched colour. That is why each engine is short enough to read in one go, and why adding the circle needed no change to the framebuffer path.
Coding rules used in every file
| Rule | Why |
|---|---|
One clock (25 MHz) for everything; SPI pins and rst_n are synchronized | no clock-domain crossings inside, easy timing on FPGA and ASIC |
Only control flops are reset (busy, counters, flags); datapath registers (coordinates, error terms, the command word) are loaded on start | a reset needs a gate in front of every flop; on SKY130 that is area for nothing. Before start they show x in the waveforms — harmless, because plot is 0 |
Sign extension written out: {2{a[11]}, a} | Verilator -Wall wants explicit widths, and it documents where numbers grow |
Constants sized from parameters: FB_W[ADDR_BITS-1:0] | no 32-bit integer creeping into comparisons |
| Lint-clean in all three builds (FPGA, ASIC v1, ASIC v2) | LibreLane stops on lint errors; the FPGA build hides different warnings than the ASIC |
A concatenation {…} is always unsigned in Verilog, even if every part of it comes from a signed wire. My first version of the line engine compared e2 >= {dy[13], dy}; that silently became an unsigned compare (−3 looks like 32765), the line never reached its end point and READY stayed low. The fix is to put the extended value in its own wire signed first. Lint did not warn — the self-checking testbench caught it in its first LINE.
What the cleanup bought (Yosys, SKY130 hd, ASIC v1 parameters)
| Module | Before | After | Change |
|---|---|---|---|
| spi_cmd_rx | 5,789 µm² | 5,398 µm² | −7 % (no reset on the shift register) |
| line_renderer | 8,448 µm² | 6,790 µm² | −20 % (no SETUP state, no own clipper/multiplier) |
| rect_filler | 2,355 µm² | 1,297 µm² | −45 % (walks x/y, no address arithmetic) |
| gpu_core glue | 2,246 µm² | 2,754 µm² | +23 % (now holds the shared clipper + address) |
| vga_controller | 1,346 µm² | 1,345 µm² | same |
| logic without framebuffer | 20,184 µm² | 17,584 µm² | −13 % |
| circle_renderer (new) | — | 10,762 µm² | outline + filled circles |
| frame_buffer (1,200 × 3 bit) | 141,929 µm² | 141,929 µm² | unchanged |
Same speed everywhere: every engine still writes one pixel per clock, and the line engine is one clock faster per command (no SETUP state). And the same pictures: all 111 cube and starburst frames (3 builds) captured from the VGA pins are byte-identical before and after the cleanup.
spi_cmd_rx.v — SPI receiver and CDC
Replaces
The AXI-Lite register bank of your FPGA GPU. The host now speaks SPI instead of the Zynq PS writing registers.
Key decision: SCK is not a clock
If SCK clocked the shift register, the command would live in a second clock domain and handing it to the 25 MHz logic would need a handshake or an async FIFO. Instead the GPU oversamples the three SPI wires with its own clock. Only three single-bit signals cross a clock domain, and a 2-flop synchronizer is exactly the right tool for single bits.
Step by step
- Each pin is shifted into a small register every clock:
sck_s <= {sck_s[1:0], spi_sck}. Bit [0] may go metastable and has a whole clock (40 ns) to settle before bit [1] samples it. - Only bit [1] (and bit [2] for CS and SCK) is used by logic.
sck_rise = sck_s[1] & ~sck_s[2]is one clock long for every SCK rising edge. - MOSI goes through the same two first stages, so
mosi_s[1]is exactly the bit that was on the wire when SCK rose. cs_fallclearsbit_count. Eachsck_risewith CS low shifts one bit in and counts it (the counter stops at 81, so a long frame stays invalid).cs_risewithbit_count == 80copies the shift register tocmd_wordand pulsescmd_validfor one clock. Any other count: the frame is ignored.- After reset
bit_countstarts at 81 ("not in a frame"): if the host was in the middle of a frame when the GPU was reset, the rest of that frame cannot become a command.
| Port | Dir | Width | Meaning |
|---|---|---|---|
| clk, reset | in | 1 | 25 MHz clock, synchronous reset |
| spi_cs_n / spi_sck / spi_mosi | in | 1 | raw SPI pins (asynchronous) |
| bus_idle | out | 1 | CS high for two clocks (part of READY) |
| cmd_valid | out | 1 | one-clock pulse: a complete frame arrived |
| cmd_word | out | 80 | the frame, byte 0 (opcode) in bits 79:72 |
`timescale 1ns / 1ps
// =============================================================
// spi_cmd_rx : SPI command receiver (mode 0, MSB first, write only)
//
// SCK is never used as a clock. The three SPI pins are sampled by
// the 25 MHz core clock through 2-flop synchronizers and the SCK
// edges are found inside the clk domain, so the whole GPU stays in
// ONE clock domain. Rule of thumb: f_sck <= f_clk / 8 (~3 MHz).
//
// A frame = CS falls, exactly CMD_BITS rising SCK edges, CS rises.
// Short or long frames are dropped. After reset the receiver waits
// for a CS falling edge, so half a frame can never become a command.
// =============================================================
module spi_cmd_rx #(
parameter CMD_BITS = 80
)(
input wire clk,
input wire reset,
// SPI pins (asynchronous to clk)
input wire spi_cs_n,
input wire spi_sck,
input wire spi_mosi,
output wire bus_idle, // CS has been high for 2 clocks
output reg cmd_valid, // 1-clock pulse: cmd_word is new
output reg [CMD_BITS-1:0] cmd_word
);
localparam CNT_BITS = $clog2(CMD_BITS + 2);
localparam [CNT_BITS-1:0] FULL = CMD_BITS; // a complete frame
localparam [CNT_BITS-1:0] OVER = CMD_BITS + 1; // too long / not started
// ---------------------------------------------------------
// Synchronizers. Each pin goes through a shift register:
// [0] may go metastable, [1] is the clean synchronized value,
// [2] is [1] one clock older (for edge detection).
// ---------------------------------------------------------
(* ASYNC_REG = "TRUE" *) reg [2:0] cs_s;
(* ASYNC_REG = "TRUE" *) reg [2:0] sck_s;
(* ASYNC_REG = "TRUE" *) reg [1:0] mosi_s;
always @(posedge clk) begin
if (reset) begin
cs_s <= 3'b111; // idle: CS high
sck_s <= 3'b000; // idle: SCK low (mode 0)
mosi_s <= 2'b00;
end
else begin
cs_s <= {cs_s[1:0], spi_cs_n};
sck_s <= {sck_s[1:0], spi_sck};
mosi_s <= {mosi_s[0], spi_mosi};
end
end
wire cs_low = !cs_s[1];
wire cs_fall = !cs_s[1] && cs_s[2];
wire cs_rise = cs_s[1] && !cs_s[2];
wire sck_rise = sck_s[1] && !sck_s[2];
wire mosi = mosi_s[1];
assign bus_idle = cs_s[1] && cs_s[2];
// ---------------------------------------------------------
// Frame receiver
// ---------------------------------------------------------
reg [CNT_BITS-1:0] bit_count;
reg [CMD_BITS-1:0] shift_reg;
always @(posedge clk) begin
cmd_valid <= 1'b0; // default: no pulse
if (reset)
bit_count <= OVER; // wait for a CS fall
else if (cs_fall)
bit_count <= 0; // frame starts
else if (cs_rise) begin // frame ends
if (bit_count == FULL) begin
cmd_word <= shift_reg;
cmd_valid <= 1'b1;
end
end
else if (cs_low && sck_rise) begin // one bit
shift_reg <= {shift_reg[CMD_BITS-2:0], mosi};
if (bit_count != OVER) // saturate: a long
bit_count <= bit_count + 1'b1; // frame stays invalid
end
end
endmodulesck_rise is high for exactly one clock, and bit_count counts the bit.bit_count reaches 80, CS rises, cmd_valid pulses and the line starts. READY is low during the frame and while the line draws.The edge detector needs SCK to stay at each level for at least two samples, and MOSI must still be stable two clocks after the SCK edge. With SCK ≤ clk/8 each half-period is ≥ 4 clocks. The sketch uses 2 MHz: 6.25 clocks per half-period.
vga_controller.v — VGA timing and scaling
Same idea as your FPGA version
Two counters walk the 800 × 525 VGA raster; the visible 640 × 480 part reads the framebuffer, the rest produces the sync pulses.
The pieces
- Scaling:
fb_x = h_count >> SCALE_SHIFT,fb_y = v_count >> SCALE_SHIFT. One file serves 320×240 (shift 1), 80×60 (3) and 40×30 (4). - Address
fb_y · FB_WIDTH + fb_x. FB_WIDTH is a constant, so synthesis builds shifts and adds (for 320 exactly your old(y<<8)+(y<<6)+x, for 40 it is(y<<5)+(y<<3)+x). vblank_start: a one-clock pulse when the counters enter line 480. SWAP waits for it.- No reset on the frame contents:
frame_validkeeps RGB black until the power-up clear is done.
The two-stage pipeline
| Clock | What happens | Signals |
|---|---|---|
| t | counters give the screen position → framebuffer address | h_count, v_count, fb_addr |
| t + 1 | the framebuffer returns the pixel; visible/sync are delayed by one flop to stay aligned | fb_data, visible_d, h_sync_d |
| t + 2 | everything is registered on the output pins together | pixel, hsync, vsync |
Registered outputs matter on the ASIC: the pins switch right after the clock edge with almost no logic in front, so the board sees clean edges and the pad delay is predictable.
| Port | Dir | Width | Meaning |
|---|---|---|---|
| clk, reset | in | 1 | pixel clock = system clock |
| frame_valid | in | 1 | force black until the power-up clear is done |
| fb_addr | out | ADDR_BITS | pixel index into one buffer |
| fb_data | in | PIX_BITS | pixel, one clock after fb_addr |
| vblank_start | out | 1 | pulse at line 480, column 0 |
| hsync, vsync, pixel | out | 1 / 1 / PIX_BITS | registered, 2 clocks after the counters |
`timescale 1ns / 1ps
// =============================================================
// vga_controller : 640x480 @ 60 Hz scan-out (25 MHz pixel clock)
//
// The framebuffer is smaller than the screen: every FB pixel is
// repeated (1 << SCALE_SHIFT) times in X and in Y.
// FPGA : 320 x 240, SCALE_SHIFT = 1 ( 2 x 2 screen pixels)
// SRAM : 80 x 60, SCALE_SHIFT = 3 ( 8 x 8)
// ASIC : 40 x 30, SCALE_SHIFT = 4 (16 x 16)
//
// Timing of one pixel (the FB read takes one clock):
// clock t : counters -> fb_addr
// clock t+1 : FB returns fb_data, sync/visible delayed by 1
// clock t+2 : hsync, vsync, pixel registered on the pins
// =============================================================
module vga_controller #(
parameter FB_WIDTH = 320,
parameter SCALE_SHIFT = 1,
parameter PIX_BITS = 8,
parameter ADDR_BITS = 17 // >= 11, address of one buffer
)(
input wire clk,
input wire reset,
input wire frame_valid, // black until the FB is cleared
output wire [ADDR_BITS-1:0] fb_addr, // pixel index into the FB
input wire [PIX_BITS-1:0] fb_data, // arrives one clock later
output wire vblank_start, // 1-clock pulse, first blank line
output reg hsync, // active low
output reg vsync, // active low
output reg [PIX_BITS-1:0] pixel
);
// 640x480 @ 60 Hz (VESA): visible, front porch, sync, back porch
localparam H_VIS = 640, H_FP = 16, H_SYNC = 96, H_BP = 48;
localparam V_VIS = 480, V_FP = 10, V_SYNC = 2, V_BP = 33;
localparam H_TOTAL = H_VIS + H_FP + H_SYNC + H_BP; // 800
localparam V_TOTAL = V_VIS + V_FP + V_SYNC + V_BP; // 525
reg [9:0] h_count; // 0 .. 799
reg [9:0] v_count; // 0 .. 524
wire visible = (h_count < H_VIS) && (v_count < V_VIS);
wire h_sync = (h_count >= H_VIS + H_FP) && (h_count < H_VIS + H_FP + H_SYNC);
wire v_sync = (v_count >= V_VIS + V_FP) && (v_count < V_VIS + V_FP + V_SYNC);
assign vblank_start = (h_count == 0) && (v_count == V_VIS);
// framebuffer coordinate = screen coordinate / scale
wire [ADDR_BITS-1:0] fb_x = {{(ADDR_BITS-10){1'b0}}, h_count >> SCALE_SHIFT};
wire [ADDR_BITS-1:0] fb_y = {{(ADDR_BITS-10){1'b0}}, v_count >> SCALE_SHIFT};
// y * FB_WIDTH is a constant multiply: synthesis builds it from
// shifts and adds (320: (y<<8)+(y<<6), 40: (y<<5)+(y<<3)).
localparam [ADDR_BITS-1:0] STRIDE = FB_WIDTH[ADDR_BITS-1:0];
assign fb_addr = visible ? fb_y * STRIDE + fb_x : {ADDR_BITS{1'b0}};
reg visible_d, h_sync_d, v_sync_d; // delayed by the FB read latency
always @(posedge clk) begin
if (reset) begin
h_count <= 0;
v_count <= 0;
visible_d <= 1'b0;
h_sync_d <= 1'b0;
v_sync_d <= 1'b0;
hsync <= 1'b1;
vsync <= 1'b1;
pixel <= 0;
end
else begin
// counters: h wraps every 800 clocks, v every 525 lines
if (h_count == H_TOTAL - 1) begin
h_count <= 0;
v_count <= (v_count == V_TOTAL - 1) ? 10'd0 : v_count + 1'b1;
end
else
h_count <= h_count + 1'b1;
// stage 1: wait for the FB data
visible_d <= visible && frame_valid;
h_sync_d <= h_sync;
v_sync_d <= v_sync;
// stage 2: registered outputs, sync pulses are negative
hsync <= !h_sync_d;
vsync <= !v_sync_d;
pixel <= visible_d ? fb_data : {PIX_BITS{1'b0}};
end
end
endmoduleframe_buffer.v — one write port, one read port
Your two-port framebuffer on one clock: the pixel writer uses the write port, the VGA controller the read port, so drawing never has to wait for the display.
- No
initialblock. Silicon powers up with random contents;gpu_coreclears the memory after every reset instead. - Exact depth (
DEPTH= W · H · buffers) instead of a power of two. On the FPGA it is BRAM either way; on the ASIC 2,048 words instead of 1,200 would cost 2,544 extra flip-flops. - Registered read: data appears one clock after the address — the latency the VGA pipeline is built around, and what BRAM and the SRAM macros give anyway.
`timescale 1ns / 1ps
// =============================================================
// Frame buffer : 1 write port (draw engines) + 1 read port (VGA)
//
// FPGA : DEPTH = 2 * 320 * 240 (double buffered), PIX_BITS = 8
// -> Vivado infers block RAM
// ASIC : DEPTH = 40 * 30 (single buffer), PIX_BITS = 3
// -> Yosys builds it out of flip-flops + a read mux
//
// Read data is registered: it appears 1 clock after addr_read.
// No "initial" block on purpose: an ASIC has no power-on contents,
// gpu_core clears the memory after reset instead.
// =============================================================
module frame_buffer #(
parameter PIX_BITS = 8,
parameter DEPTH = 153600,
parameter ADDR_BITS = 18
)(
input wire clk,
// Write port
input wire write_en,
input wire [ADDR_BITS-1:0] addr_write,
input wire [PIX_BITS-1:0] write_data,
// Read port
input wire [ADDR_BITS-1:0] addr_read,
output reg [PIX_BITS-1:0] read_data
);
(* ram_style = "block" *)
reg [PIX_BITS-1:0] mem [0 : DEPTH-1];
// Write port
always @(posedge clk) begin
if (write_en)
mem[addr_write] <= write_data;
end
// Read port
always @(posedge clk) begin
read_data <= mem[addr_read];
end
endmoduleIf the VGA reads the address being written in the same clock it gets the old pixel. On screen that is invisible — the next frame shows the new pixel.
The SRAM version keeps the module name, ports and one-clock read latency, so nothing else changes.
line_renderer.v — Bresenham lines, explained
The problem
A line from (x0, y0) to (x1, y1) has to become a chain of pixels: one pixel per step, no gaps, as close to the true line as possible. The obvious way — y = y0 + (x − x0) · slope — needs a division and rounding per pixel. Bresenham's algorithm needs only additions and comparisons, so the hardware is a few adders and the engine can produce one pixel per clock.
The idea: keep score of the error
Walk from the start point towards the end point. At each pixel there are three ways forward: step in x only, in y only, or diagonally (both). Bresenham keeps one integer, err, that says how far the diagonal neighbour is from the true line, and decides from it which way is best:
| Quantity | Value | Meaning |
|---|---|---|
dx | |x1 − x0| | how far to go in x (≥ 0) |
dy | −|y1 − y0| | how far to go in y, stored negative (≤ 0) — this makes all 8 octants one formula |
sx, sy | +1 or −1 | direction of travel in x and y |
e(u, v) | v · dx + u · dy | line equation: 0 exactly on the line (u, v = steps taken in x, y) |
err | e of the diagonal neighbour | starts as e(1, 1) = dx + dy |
Moving in x adds dy to e, moving in y adds dx. Now compare the three candidates. The error of the diagonal is err; of "y only" it is err − dy; of "x only" it is err − dx:
- Step x (diagonal or x-only) when the diagonal is at least as close as y-only: |err| ≤ |err − dy|. With dy ≤ 0 this works out to err ≥ dy / 2, i.e.
2·err ≥ dy. - Step y (diagonal or y-only) when the diagonal is at least as close as x-only: |err| ≤ |err − dx|, i.e.
2·err ≤ dx. - Both true → diagonal step. Multiplying by 2 removes the ½, so everything stays integer.
- After the step, add
dyto err for an x-step anddxfor a y-step: err is again the error of the new diagonal neighbour.
dx = |x1 - x0| sx = (x0 < x1) ? +1 : -1
dy = -|y1 - y0| sy = (y0 < y1) ? +1 : -1
err = dx + dy
loop:
plot(x, y)
if (x == x1 and y == y1): stop # end point is drawn too
e2 = 2 * err
if (e2 >= dy): err += dy; x += sx # step in x
if (e2 <= dx): err += dx; y += sy # step in yWorked example: LINE (2,1) → (9,4)
dx = 7, dy = −3, sx = sy = +1, err₀ = 4. One row per clock — exactly what the waveform below shows:
| Clock | plot (x, y) | err | e2 = 2·err | e2 ≥ dy → x | e2 ≤ dx → y | next err |
|---|---|---|---|---|---|---|
| 1 | (2,1) | 4 | 8 | yes | no | 4 -3 = 1 |
| 2 | (3,1) | 1 | 2 | yes | yes | 1 +4 = 5 |
| 3 | (4,2) | 5 | 10 | yes | no | 5 -3 = 2 |
| 4 | (5,2) | 2 | 4 | yes | yes | 2 +4 = 6 |
| 5 | (6,3) | 6 | 12 | yes | no | 6 -3 = 3 |
| 6 | (7,3) | 3 | 6 | yes | yes | 3 +4 = 7 |
| 7 | (8,4) | 7 | 14 | yes | no | 7 -3 = 4 |
| 8 | (9,4) | 4 | — | — | — | end point → busy = 0 |
From algorithm to hardware
| Algorithm | RTL | Hardware |
|---|---|---|
| dx, dy, err, sx, sy at the start | adx_in, ady_in computed straight from the inputs; loaded on start | 2 subtractors + 2 negators, no extra clock |
| plot(x, y) | plot = busy; x, y are registers | every busy clock is a pixel |
| the end test | at_end = (x == x_end) && (y == y_end) | 2 comparators; true while the last pixel is plotted |
| e2 = 2·err | {err, 1'b0} | just wiring |
| the two decisions | step_x = (e2 >= dy_w), step_y = (e2 <= dx_w) | 2 comparators |
| err update | err + add_x + add_y | one 3-input adder |
Widths and clipping
- Coordinates are signed 12-bit (−2048 … 2047): a 3D projection often puts an end point off screen. The engine walks the whole line;
gpu_coredrops the off-screen pixels. - dx can be 2047 − (−2048) = 4095 → 13 bits, so the error term uses 14 bits (
EW = CW + 2) and e2 one more. Inputs are sign-extended before subtracting so nothing can wrap. - Time: max(|dx|, |dy|) + 1 clocks — one per pixel. A full-screen diagonal on the FPGA is 320 clocks = 12.8 µs.
| Port | Dir | Width | Meaning |
|---|---|---|---|
| start | in | 1 | one-clock pulse, x0…y1 valid |
| x0, y0, x1, y1 | in | CW signed | end points |
| busy | out | 1 | walking the line |
| plot, x, y | out | 1, CW signed | pixel (x, y) this clock |
`timescale 1ns / 1ps
// =============================================================
// line_renderer : Bresenham line, all 8 octants, integer only
//
// dx = |x1 - x0| sx = +1 if x0 < x1 else -1
// dy = -|y1 - y0| sy = +1 if y0 < y1 else -1
// err = dx + dy
// loop: plot(x, y)
// if (x, y) == (x1, y1): done
// e2 = 2 * err
// if e2 >= dy: err += dy, x += sx (step in x)
// if e2 <= dx: err += dx, y += sy (step in y)
//
// One pixel per clock, both end points included. Coordinates are
// signed, so a line may start or end off screen: gpu_core clips
// every pixel, this module only walks the line.
// =============================================================
module line_renderer #(
parameter CW = 12 // signed coordinate width
)(
input wire clk,
input wire reset,
input wire start, // 1-clock pulse, args valid
input wire signed [CW-1:0] x0,
input wire signed [CW-1:0] y0,
input wire signed [CW-1:0] x1,
input wire signed [CW-1:0] y1,
output reg busy,
output wire plot, // (x, y) is a pixel of the line
output reg signed [CW-1:0] x,
output reg signed [CW-1:0] y
);
// |dx|, |dy| need CW+1 bits, their sum one more, plus sign
localparam EW = CW + 2;
// ---- set-up values, computed straight from the inputs ----
// sign-extend first, so x1 - x0 can never overflow
wire signed [EW-1:0] x0_e = {{2{x0[CW-1]}}, x0};
wire signed [EW-1:0] x1_e = {{2{x1[CW-1]}}, x1};
wire signed [EW-1:0] y0_e = {{2{y0[CW-1]}}, y0};
wire signed [EW-1:0] y1_e = {{2{y1[CW-1]}}, y1};
wire signed [EW-1:0] dx_in = x1_e - x0_e;
wire signed [EW-1:0] dy_in = y1_e - y0_e;
wire signed [EW-1:0] adx_in = dx_in[EW-1] ? -dx_in : dx_in;
wire signed [EW-1:0] ady_in = dy_in[EW-1] ? -dy_in : dy_in;
// ---- line state ----
reg signed [EW-1:0] dx; // +|x1 - x0|
reg signed [EW-1:0] dy; // -|y1 - y0|
reg signed [EW-1:0] err;
reg sx, sy; // 1 = step +1, 0 = step -1
reg signed [CW-1:0] x_end, y_end;
// ---- one Bresenham step ----
// compare at EW+1 bits. Note: {..} is always UNSIGNED in Verilog,
// so the extended copies get their own signed wires.
wire signed [EW:0] e2 = {err, 1'b0}; // 2 * err
wire signed [EW:0] dx_w = {dx[EW-1], dx};
wire signed [EW:0] dy_w = {dy[EW-1], dy};
wire step_x = (e2 >= dy_w);
wire step_y = (e2 <= dx_w);
wire signed [EW-1:0] add_x = step_x ? dy : {EW{1'b0}};
wire signed [EW-1:0] add_y = step_y ? dx : {EW{1'b0}};
wire at_end = (x == x_end) && (y == y_end);
assign plot = busy; // every busy clock is one pixel
always @(posedge clk) begin
if (reset)
busy <= 1'b0;
else if (!busy) begin
if (start) begin
busy <= 1'b1;
x <= x0;
y <= y0;
x_end <= x1;
y_end <= y1;
dx <= adx_in;
dy <= -ady_in;
err <= adx_in - ady_in;
sx <= (x0 < x1);
sy <= (y0 < y1);
end
end
else if (at_end)
busy <= 1'b0; // last pixel was plotted this clock
else begin
if (step_x) x <= sx ? x + 1'b1 : x - 1'b1;
if (step_y) y <= sy ? y + 1'b1 : y - 1'b1;
err <= err + add_x + add_y;
end
end
endmodulestart, then 8 pixels in 8 clocks. err follows the table above; step_y fires every other pixel (slope 3/7). Before start the datapath registers show x (never reset) — harmless, plot is 0.rect_filler.v — rectangles and CLEAR
The simplest engine: two nested counters. gpu_core has already clipped the rectangle to the screen and turned it into inclusive corners (x0, y0) – (x1, y1), so every clock is a visible pixel and there is no bounds check inside. CLEAR is the full-screen rectangle (0, 0) – (W−1, H−1).
Step by step
- On
start: x ← x0, y ← y0, remember x0 (start of every row), x1 and y1. - Every busy clock plots (x, y). If x ≠ x1: x ← x + 1.
- Else, if y ≠ y1: next row — x ← x0, y ← y + 1.
- Else (x1, y1) was the last pixel: busy ← 0.
| Clock | x | y | address y·40 + x | next |
|---|---|---|---|---|
| 1 | 3 | 6 | 243 | x+1 |
| 2 | 4 | 6 | 244 | x+1 |
| 3 | 5 | 6 | 245 | x+1 |
| 4 | 6 | 6 | 246 | row end → x = 3, y = 7 |
| 5 | 3 | 7 | 283 | x+1 |
| … | … | |||
| 8 | 6 | 7 | 286 | done |
Your FPGA rect.v avoided the multiply by stepping the address (+1 per pixel, +stride per row). Now the address y · W + x is computed once in gpu_core for all engines; W is a constant, so it is two adders (320 = 256 + 64), not a multiplier. The rectangle engine shrank from 2,355 to 1,297 µm².
`timescale 1ns / 1ps
// =============================================================
// rect_filler : filled rectangle, one pixel per clock
//
// Walks x from x0 to x1, then the next row, until (x1, y1).
// The corners are inclusive and already clipped to the screen by
// gpu_core (0 <= x0 <= x1 < W, 0 <= y0 <= y1 < H), so every clock
// is a visible pixel. CLEAR is a full-screen rectangle.
// =============================================================
module rect_filler #(
parameter XW = 9, // x bits (320 -> 9)
parameter YW = 8 // y bits (240 -> 8)
)(
input wire clk,
input wire reset,
input wire start, // 1-clock pulse, args valid
input wire [XW-1:0] x0,
input wire [YW-1:0] y0,
input wire [XW-1:0] x1,
input wire [YW-1:0] y1,
output reg busy,
output wire plot,
output reg [XW-1:0] x,
output reg [YW-1:0] y
);
reg [XW-1:0] x_first, x_last;
reg [YW-1:0] y_last;
assign plot = busy;
always @(posedge clk) begin
if (reset)
busy <= 1'b0;
else if (!busy) begin
if (start) begin
busy <= 1'b1;
x <= x0;
y <= y0;
x_first <= x0;
x_last <= x1;
y_last <= y1;
end
end
else if (x != x_last)
x <= x + 1'b1; // next pixel in the row
else if (y != y_last) begin
x <= x_first; // next row
y <= y + 1'b1;
end
else
busy <= 1'b0; // (x1, y1) was the last pixel
end
endmodulecircle_renderer.v — midpoint circles, outline and filled
What it draws
New command 0x05 CIRCLE: A = cx, B = cy, C = r (0 … 2047), D bit 0 = fill (0 = outline, 1 = filled disc). Like the line, the centre may be anywhere — even off screen — and everything is clipped. The algorithm is the midpoint circle algorithm (Bresenham's circle): again only additions, subtractions and comparisons — no multiplier, no square root, no sine table.
Idea 1: compute one eighth, mirror the rest
A circle is symmetric about the x axis, the y axis and both diagonals. If (x, y) is on a circle around the origin, so are (±x, ±y) and (±y, ±x) — eight points. So the engine only walks octant 0: from (r, 0) at 3 o'clock down to the 45° diagonal where x = y. Every point it finds there gives eight pixels.
Idea 2: walk the octant with a midpoint test
In octant 0 the circle is steep: every step goes one row further (y + 1), and x either stays or moves one column inwards (x − 1). To choose, look at the point exactly halfway between the two candidates and ask whether it is inside or outside the circle. With f(x, y) = x² + y² − r² (negative inside, positive outside):
Why there are no squares in the hardware
d is never computed from scratch. When y grows by one and x maybe shrinks by one, the change of d is simple (y′, x′ are the new values):
| Choice | New midpoint | d′ − d | Update in the RTL |
|---|---|---|---|
| A: x stays (d < 0) | (x − ½, y′ + 1) | (y′+1)² − y′² = 2·y′ + 1 | d + 2·y_n + 1 |
| B: x − 1 (d ≥ 0) | (x′ − ½, y′ + 1) | 2·y′ + 1 − 2·x′ | d + 2·(y_n − x_n) + 1 |
The RTL writes both as d + (inc <<< 1) + 1 with inc = d_neg ? y_n : y_n − x_n: one subtractor, one multiplexer, a shift (wiring) and one adder.
Start value. The first midpoint is (r − ½, 1): f = (r − ½)² + 1 − r² = 5/4 − r. Every update adds an integer, so the true d is always "integer + ¼". For the sign test the ¼ never matters (an integer n satisfies n + ¼ < 0 exactly when n < 0), so the hardware starts at d = 1 − r and stays integer. Stop: when the next point would have x < y, the octant is finished (signal last).
x = r, y = 0, d = 1 - r
loop:
draw step (x, y) # 8 points, or up to 4 spans
y' = y + 1
if d < 0: x' = x, d' = d + 2*y' + 1
else: x' = x - 1, d' = d + 2*(y' - x') + 1
if x' < y': stop # "last"
x, y, d = x', y', d'Worked example: r = 7
| Step | (x, y) | d | d < 0 ? | next (x′, y′) | d′ | last? |
|---|---|---|---|---|---|---|
| 1 | (7,0) | -6 | yes | (7,1) | -6 + 2·1 + 1 = -3 | no |
| 2 | (7,1) | -3 | yes | (7,2) | -3 + 2·2 + 1 = 2 | no |
| 3 | (7,2) | 2 | no | (6,3) | 2 + 2·(3−6) + 1 = -3 | no |
| 4 | (6,3) | -3 | yes | (6,4) | -3 + 2·4 + 1 = 6 | no |
| 5 | (6,4) | 6 | no | (5,5) | 6 + 2·(5−5) + 1 = 7 | no |
| 6 | (5,5) | 7 | no | (4,6) | — | yes → done |
Outline: 8 pixels per step
A 3-bit counter k runs 0…7; a case statement turns it into the offset (ox, oy) — the table in the symmetry picture. px = cx + ox, py = cy + oy. After k = 7 the engine takes the next step. On the first step (y = 0) and on the diagonal (x = y) some of the eight points coincide; they are simply written twice — skipping them would need more logic than it saves (at most 8 extra clocks per circle).
Filled: spans, each row exactly once
The same walk gives the horizontal extent of the disc: row cy ± y goes from cx − x to cx + x, and row cy ± x from cx − y to cx + y. Drawing all four spans at every step would draw many rows again and again, because x often stays the same for several steps. The rules that make every row appear exactly once:
| Span s | Row | From … to | Drawn when |
|---|---|---|---|
| 0 | cy + y | cx − x … cx + x | every step |
| 1 | cy − y | cx − x … cx + x | every step except y = 0 (that row is span 0) |
| 2 | cy + x | cx − y … cx + y | only on the last step before x changes (d ≥ 0) or the very last step — that is the widest span this row gets — and not when x = y (same row as span 0) |
| 3 | cy − x | cx − y … cx + y | same as span 2 |
scripts/check_circle.py (in the zip, independent of the RTL) checks that every outline pixel lies within half a pixel of the true circle, the outline has no gaps, the filled disc writes no pixel twice, and the filled disc is exactly every row filled between the leftmost and rightmost outline pixel — so a filled circle and its outline always match. Result: ALL CHECKS PASSED. The testbench then checks the RTL against the same rules pixel by pixel.
Clipping without wasting clocks
Each span is clipped to the screen before it is walked (left_c, rght_c, row inside 0…H−1). A span that is completely off screen costs one clock (S_SPAN_SET) instead of hundreds. gpu_core still checks every pixel, so even a wrong clip here could never write outside the framebuffer.
Widths
- r is 11 bits (0…2047). cx ± r can reach ±4095, so positions use PW = 15 bits signed (COORD_BITS + 3), comfortably holding d too (|d| ≤ about 3·r).
- The extreme case CIRCLE (2047, −2048, r = 2047) is in the testbench: it must write nothing (all off screen) and must finish.
Using it from the Arduino
gpuCircle(160, 120, 50, WHITE); // outline, centre (160,120), r = 50
gpuFillCircle(80, 120, 30, RED); // filled disc
gpuFillCircle(-10, 230, 40, BLUE); // centre off screen: only the visible part is drawn
// the same FillCircle as raw bytes on the SPI bus:
// 05 0050 0078 001E 0001 E0 op, cx=80, cy=120, r=30, fill=1, colour RGB332How long it takes
radii 0..400: ALL CHECKS PASSED
r steps outline clocks filled pixels (pi r^2) filled clocks @25 MHz
3 3 24 37 28 49 0.00 ms
10 8 64 349 314 381 0.02 ms
50 36 288 8005 7854 8149 0.33 ms
100 71 568 31689 31416 31973 1.28 ms
200 142 1136 126253 125664 126821 5.07 msSteps ≈ r / √2 + 1. Outline: 8 clocks per step (r = 100 → 568 clocks = 23 µs). Filled: one clock per pixel plus 4 per step (r = 100 → 31,973 clocks = 1.3 ms, only 1.8 % more than the πr² pixels). Area on SKY130: 10,762 µm².
| Port | Dir | Width | Meaning |
|---|---|---|---|
| start, fill | in | 1 | one-clock pulse; fill = D bit 0 |
| cx_in, cy_in | in | CW signed | centre (sign-extended by gpu_core) |
| r_in | in | RW | radius, unsigned |
| busy | out | 1 | drawing |
| plot, px, py | out | 1, CW signed | pixel this clock |
`timescale 1ns / 1ps
// =============================================================
// circle_renderer : midpoint (Bresenham) circle, outline or filled
//
// Walks one octant (from (r, 0) up to the 45 degree diagonal) and
// uses the 8-way symmetry of the circle for the rest:
//
// x = r, y = 0, d = 1 - r
// while x >= y:
// draw step (x, y) <- 8 points or 4 spans
// y = y + 1
// if d < 0: d = d + 2*y + 1 (stay on this column)
// else: x = x - 1
// d = d + 2*(y - x) + 1 (step inwards)
//
// OUTLINE : 8 pixels per step, one per clock
// (cx+-x, cy+-y) and (cx+-y, cy+-x)
// FILLED : up to 4 horizontal spans per step
// rows cy+-y from cx-x to cx+x (every step)
// rows cy+-x from cx-y to cx+y (only on the last step
// before x changes, so
// each row is drawn once)
// Spans are clipped to the screen before they are walked,
// so off-screen parts cost no clocks.
//
// Only adds, subtracts and compares: no multiplier, no square root.
// gpu_core clips every pixel again, so nothing can be written
// outside the framebuffer whatever cx, cy and r are.
// =============================================================
module circle_renderer #(
parameter CW = 15, // signed width of cx, cy, x, y, d
parameter RW = 11, // radius bits (0 .. 2047)
parameter SCREEN_W = 320,
parameter SCREEN_H = 240
)(
input wire clk,
input wire reset,
input wire start, // 1-clock pulse, args valid
input wire fill, // 0 = outline, 1 = filled disc
input wire signed [CW-1:0] cx_in,
input wire signed [CW-1:0] cy_in,
input wire [RW-1:0] r_in,
output reg busy,
output wire plot,
output wire signed [CW-1:0] px,
output wire signed [CW-1:0] py
);
localparam signed [CW-1:0] ONE = 1;
localparam signed [CW-1:0] ZERO = 0;
localparam X_LAST = SCREEN_W - 1;
localparam Y_LAST = SCREEN_H - 1;
localparam signed [CW-1:0] XMAX = X_LAST[CW-1:0];
localparam signed [CW-1:0] YMAX = Y_LAST[CW-1:0];
localparam [1:0] S_POINTS = 2'd0; // outline: 8 points per step
localparam [1:0] S_SPAN_SET = 2'd1; // filled: choose + clip a span
localparam [1:0] S_SPAN_RUN = 2'd2; // filled: walk the span
reg [1:0] state;
reg signed [CW-1:0] cx, cy; // centre
reg signed [CW-1:0] x, y, d; // octant position + decision
reg [2:0] k; // outline: which of the 8 points
reg [1:0] s; // filled: which of the 4 spans
reg signed [CW-1:0] run_x, run_end, run_row; // span being walked
// ---------------------------------------------------------
// Next midpoint step (used by both modes)
// ---------------------------------------------------------
wire d_neg = d[CW-1]; // d < 0
wire signed [CW-1:0] y_n = y + ONE;
wire signed [CW-1:0] x_n = d_neg ? x : x - ONE;
wire signed [CW-1:0] inc = d_neg ? y_n : y_n - x_n;
wire signed [CW-1:0] d_n = d + (inc <<< 1) + ONE;
wire last = (x_n < y_n); // octant finished
// ---------------------------------------------------------
// OUTLINE: point k of the 8 symmetric points
// ---------------------------------------------------------
reg signed [CW-1:0] ox, oy; // offset from the centre
always @(*) begin
case (k)
3'd0: begin ox = x; oy = y; end
3'd1: begin ox = y; oy = x; end
3'd2: begin ox = -y; oy = x; end
3'd3: begin ox = -x; oy = y; end
3'd4: begin ox = -x; oy = -y; end
3'd5: begin ox = -y; oy = -x; end
3'd6: begin ox = y; oy = -x; end
default: begin ox = x; oy = -y; end
endcase
end
// ---------------------------------------------------------
// FILLED: span s of the current step
// s = 0 : row cy + y, half width x s = 2 : row cy + x, half width y
// s = 1 : row cy - y, half width x s = 3 : row cy - x, half width y
// ---------------------------------------------------------
wire signed [CW-1:0] row_off = s[1] ? x : y;
wire signed [CW-1:0] half = s[1] ? y : x;
wire signed [CW-1:0] row = s[0] ? cy - row_off : cy + row_off;
// which spans are needed in this step (each row exactly once)
wire span_on = s[1] ? ((!d_neg || last) && (x != y)) // x rows: widest span only
: (!s[0] || (y != ZERO)); // y rows: row cy-0 = cy+0
// clip the span to the screen
wire signed [CW-1:0] left = cx - half;
wire signed [CW-1:0] right = cx + half;
wire signed [CW-1:0] left_c = (left < ZERO) ? ZERO : left;
wire signed [CW-1:0] rght_c = (right > XMAX) ? XMAX : right;
wire span_visible = span_on && (row >= ZERO) && (row <= YMAX) && (left_c <= rght_c);
// ---------------------------------------------------------
// Control
// ---------------------------------------------------------
wire span_done = (state == S_SPAN_SET && !span_visible) ||
(state == S_SPAN_RUN && run_x == run_end);
// advance (x, y, d) after the 8th point or after the 4th span
wire step = (state == S_POINTS) ? (k == 3'd7) : (span_done && s == 2'd3);
assign plot = busy && (state == S_POINTS || state == S_SPAN_RUN);
assign px = (state == S_POINTS) ? cx + ox : run_x;
assign py = (state == S_POINTS) ? cy + oy : run_row;
always @(posedge clk) begin
if (reset)
busy <= 1'b0;
else if (!busy) begin
if (start) begin
busy <= 1'b1;
state <= fill ? S_SPAN_SET : S_POINTS;
cx <= cx_in;
cy <= cy_in;
x <= $signed({{(CW-RW){1'b0}}, r_in});
y <= ZERO;
d <= ONE - $signed({{(CW-RW){1'b0}}, r_in});
k <= 3'd0;
s <= 2'd0;
end
end
else begin
case (state)
S_POINTS:
k <= k + 1'b1; // wraps 7 -> 0
S_SPAN_SET:
if (span_visible) begin
run_x <= left_c;
run_end <= rght_c;
run_row <= row;
state <= S_SPAN_RUN;
end
default: // S_SPAN_RUN
if (run_x != run_end)
run_x <= run_x + ONE;
else
state <= S_SPAN_SET;
endcase
if (span_done)
s <= s + 1'b1; // wraps 3 -> 0
if (step) begin
x <= x_n;
y <= y_n;
d <= d_n;
if (last)
busy <= 1'b0;
end
end
end
endmoduleplot is high all 24 clocks.gpu_core.v — decode, pixel writer, reset, double buffering
gpu_core takes the role of your vga_top.v without the Zynq PS, AXI, 3D pipeline, textures and depth buffer. Read it top to bottom; each block is one idea:
- Reset synchronizer — a 2-bit shift register:
rst_nlow sets it at once (asynchronously), release happens on a clock edge two clocks later. Everything else uses the clean synchronousreset. - Power-up clear —
init_addrwalks the whole memory writing 0, one word per clock. RGB is forced black and READY is low untilinit_done. - Command fields — the 80-bit word is cut into op, A, B, C, D and the colour; only the low 12 bits of each argument are used.
- Accept — a command is accepted only when nothing is busy (
idle); a command sent while busy is dropped.gpu_ready = idle & !cmd_valid & bus_idle. The colour is latched once per command intodraw_color. - RECT clipping — inclusive corners x0 = x, x1 = x + w − 1 in 14-bit signed, clamped to 0 … W−1 (same for y). If x0 > x1 or y0 > y1 the rectangle is invisible (this also covers w = 0 and h = 0) and the engine is never started. CLEAR feeds the full-screen corners.
- Engines — one start pulse each; the circle gets its centre sign-extended to 15 bits and
fill = D[0]. - Pixel writer — choose the plotting engine, widen to 15-bit signed, keep only 0 ≤ x < W and 0 ≤ y < H, address = back buffer + y · W + x.
- SWAP / double buffering — drawing always targets the back buffer. SWAP sets
swap_pending; atvblank_startthe buffers flip. WithDOUBLE_BUF = 0SWAP only waits for vblank (used by the ASIC sketch to start drawing during blanking). - Framebuffer + VGA — the init sweep owns the write port until done; the VGA reads the front buffer.
How one command travels through the core
| Clock | What happens | Signal to watch |
|---|---|---|
| host | CS rises after 80 SCK edges | spi_cs_n |
| +2 | CS has passed the synchronizer | u_spi.cs_s[1] |
| +3 | rising edge seen, 80 bits → cmd_valid = 1 for one clock; READY drops | cmd_valid, gpu_ready |
| +3 | accept = cmd_valid & idle → one engine gets start; the colour is latched | accept, u_*.start |
| +4 … | engine busy, one pixel per clock: plot → clip → address → write | plot, fb_we, fb_waddr |
| end | busy = 0 → READY = 1 → the host may send the next command | gpu_ready |
| Parameter | FPGA | ASIC v1 | ASIC v2 | Effect |
|---|---|---|---|---|
| FB_W × FB_H | 320 × 240 | 40 × 30 | 80 × 60 | framebuffer size |
| SCALE_SHIFT | 1 | 4 | 3 | screen px per FB px = 2^shift |
| PIX_BITS | 8 | 3 | 8 | RGB332 or RGB111 |
| DOUBLE_BUF | 1 | 0 | 0 | second buffer + flip at vblank |
| COORD_BITS | 12 | 12 | 12 | signed coordinate range ±2047 |
Part 3 does not start with this file. It brings the GPU up the way you would write it: bringup/step2_rect/gpu_core.v (RECT only, no clipping in the writer), then bringup/step3_line/gpu_core.v (+ LINE and the clipping writer), then this file (+ CIRCLE, 15-bit writer). Each step shows the exact diff and has its own tests on the monitor.
`timescale 1ns / 1ps
// =============================================================
// gpu_core : SPI rasterizer GPU
// VGA scan-out + framebuffer + line + rectangle + circle
//
// The SAME file is used on the PYNQ-Z2 and in the SKY130 ASIC,
// only the parameters change:
//
// parameter FPGA (PYNQ-Z2) ASIC v1 (SKY130) ASIC v2 (SRAM)
// FB_W x FB_H 320 x 240 40 x 30 80 x 60
// SCALE_SHIFT 1 (2 x 2) 4 (16 x 16) 3 (8 x 8)
// PIX_BITS 8 (RGB332) 3 (RGB111) 8
// DOUBLE_BUF 1 0 0
//
// This is the complete core (bring-up step 4). The FPGA bring-up builds
// it up in steps: bringup/step2_rect/gpu_core.v (RECT only), then
// bringup/step3_line/gpu_core.v (+ LINE), then this file (+ CIRCLE).
//
// Host protocol: one 10-byte SPI frame per command (mode 0, MSB
// first, CS low for the whole frame). Wait for gpu_ready = 1
// before every frame.
//
// byte 0 opcode
// byte 1..2 A (int16, big endian)
// byte 3..4 B
// byte 5..6 C
// byte 7..8 D
// byte 9 colour, RGB332 (RRRGGGBB)
//
// 0x01 CLEAR - fill the whole back buffer
// 0x02 LINE A=x0 B=y0 C=x1 D=y1 Bresenham, both ends drawn
// 0x03 RECT A=x B=y C=w D=h filled
// 0x04 SWAP - show the back buffer at the
// next vblank (single buffer:
// just wait for vblank)
// 0x05 CIRCLE A=cx B=cy C=r D=fill midpoint circle, D bit 0:
// 0 = outline, 1 = filled
//
// Coordinates use the low COORD_BITS bits as a signed number
// (-2048 .. 2047), w/h the low COORD_BITS bits unsigned, r the low
// COORD_BITS-1 bits (0 .. 2047). Anything off screen is clipped.
// =============================================================
module gpu_core #(
parameter FB_W = 320,
parameter FB_H = 240,
parameter SCALE_SHIFT = 1,
parameter PIX_BITS = 8,
parameter DOUBLE_BUF = 1,
parameter COORD_BITS = 12
)(
input wire clk, // 25 MHz pixel + system clock
input wire rst_n, // asynchronous, active low
input wire spi_cs_n, // SPI from the host MCU
input wire spi_sck,
input wire spi_mosi,
output wire gpu_ready,
output wire vga_hs,
output wire vga_vs,
output wire [PIX_BITS-1:0] vga_pix,
output reg dbg_cmd_toggle // LED on the FPGA, unused on the ASIC
);
// ---------------------------------------------------------
// Sizes
// ---------------------------------------------------------
localparam FB_PIXELS = FB_W * FB_H;
localparam DEPTH = DOUBLE_BUF ? 2 * FB_PIXELS : FB_PIXELS;
localparam ADDR_BITS = $clog2(DEPTH);
localparam XW = $clog2(FB_W); // bits of an on-screen x
localparam YW = $clog2(FB_H);
localparam CB = COORD_BITS;
localparam PW = COORD_BITS + 3; // pixel coordinate width
// (circle: cx +- r)
localparam [7:0] OP_CLEAR = 8'h01;
localparam [7:0] OP_LINE = 8'h02;
localparam [7:0] OP_RECT = 8'h03;
localparam [7:0] OP_SWAP = 8'h04;
localparam [7:0] OP_CIRCLE = 8'h05;
// ---------------------------------------------------------
// Reset synchronizer: assert at once, release on a clock edge
// ---------------------------------------------------------
(* ASYNC_REG = "TRUE" *) reg [1:0] reset_s;
always @(posedge clk or negedge rst_n) begin
if (!rst_n)
reset_s <= 2'b11;
else
reset_s <= {reset_s[0], 1'b0};
end
wire reset = reset_s[1];
// ---------------------------------------------------------
// Power-up clear: write 0 to every word once after reset
// (silicon has no initial values)
// ---------------------------------------------------------
localparam LAST_I = DEPTH - 1;
localparam [ADDR_BITS-1:0] LAST_ADDR = LAST_I[ADDR_BITS-1:0];
reg init_done;
reg [ADDR_BITS-1:0] init_addr;
always @(posedge clk) begin
if (reset) begin
init_done <= 1'b0;
init_addr <= 0;
end
else if (!init_done) begin
if (init_addr == LAST_ADDR)
init_done <= 1'b1;
else
init_addr <= init_addr + 1'b1;
end
end
// ---------------------------------------------------------
// SPI receiver
// ---------------------------------------------------------
wire bus_idle;
wire cmd_valid;
wire [79:0] cmd_word;
spi_cmd_rx #(.CMD_BITS(80)) u_spi (
.clk(clk), .reset(reset),
.spi_cs_n(spi_cs_n), .spi_sck(spi_sck), .spi_mosi(spi_mosi),
.bus_idle(bus_idle), .cmd_valid(cmd_valid), .cmd_word(cmd_word)
);
// ---------------------------------------------------------
// Command fields
// ---------------------------------------------------------
// The protocol carries int16 values; only the low bits are used.
/* verilator lint_off UNUSEDSIGNAL */
wire [7:0] op = cmd_word[79:72];
wire [15:0] arg_a = cmd_word[71:56];
wire [15:0] arg_b = cmd_word[55:40];
wire [15:0] arg_c = cmd_word[39:24];
wire [15:0] arg_d = cmd_word[23:8];
wire [7:0] rgb332 = cmd_word[7:0];
/* verilator lint_on UNUSEDSIGNAL */
wire signed [CB-1:0] a = arg_a[CB-1:0];
wire signed [CB-1:0] b = arg_b[CB-1:0];
wire signed [CB-1:0] c = arg_c[CB-1:0];
wire signed [CB-1:0] d = arg_d[CB-1:0];
// RGB332 -> framebuffer pixel (ASIC: keep the MSB of R, G and B)
wire [PIX_BITS-1:0] cmd_color;
generate
if (PIX_BITS == 3) begin : g_rgb111
assign cmd_color = {rgb332[7], rgb332[4], rgb332[1]};
end
else begin : g_rgb332
assign cmd_color = rgb332[PIX_BITS-1:0];
end
endgenerate
// ---------------------------------------------------------
// Accepting a command
// ---------------------------------------------------------
wire line_busy, rect_busy, circ_busy;
reg swap_pending;
wire idle = init_done && !line_busy && !rect_busy && !circ_busy && !swap_pending;
wire accept = cmd_valid && idle; // a command sent while busy is dropped
assign gpu_ready = idle && !cmd_valid && bus_idle;
wire is_clear = (op == OP_CLEAR);
wire is_line = (op == OP_LINE);
wire is_rect = (op == OP_RECT);
wire is_swap = (op == OP_SWAP);
wire is_circle = (op == OP_CIRCLE);
// colour for the whole command, latched once
reg [PIX_BITS-1:0] draw_color;
always @(posedge clk) begin
if (reset)
dbg_cmd_toggle <= 1'b0;
else if (accept) begin
dbg_cmd_toggle <= !dbg_cmd_toggle;
draw_color <= cmd_color;
end
end
// ---------------------------------------------------------
// RECT / CLEAR: clip [x, x+w) x [y, y+h) to the screen.
// The filler then only walks visible pixels.
// ---------------------------------------------------------
localparam BW = CB + 2; // holds x + w
localparam X_LAST = FB_W - 1;
localparam Y_LAST = FB_H - 1;
localparam signed [BW-1:0] B_ONE = 1;
localparam signed [BW-1:0] B_ZERO = 0;
localparam signed [BW-1:0] B_XMAX = X_LAST[BW-1:0];
localparam signed [BW-1:0] B_YMAX = Y_LAST[BW-1:0];
wire signed [BW-1:0] rx0 = {{2{a[CB-1]}}, a}; // sign-extended
wire signed [BW-1:0] ry0 = {{2{b[CB-1]}}, b};
wire signed [BW-1:0] rx1 = rx0 + $signed({2'b00, arg_c[CB-1:0]}) - B_ONE; // inclusive
wire signed [BW-1:0] ry1 = ry0 + $signed({2'b00, arg_d[CB-1:0]}) - B_ONE;
wire signed [BW-1:0] kx0 = (rx0 < B_ZERO) ? B_ZERO : rx0;
wire signed [BW-1:0] ky0 = (ry0 < B_ZERO) ? B_ZERO : ry0;
wire signed [BW-1:0] kx1 = (rx1 > B_XMAX) ? B_XMAX : rx1;
wire signed [BW-1:0] ky1 = (ry1 > B_YMAX) ? B_YMAX : ry1;
// w = 0 or h = 0 or completely off screen -> nothing to draw
wire rect_visible = (kx0 <= kx1) && (ky0 <= ky1);
/* verilator lint_off UNUSEDSIGNAL */
wire [XW-1:0] fill_x0 = is_clear ? {XW{1'b0}} : kx0[XW-1:0];
wire [YW-1:0] fill_y0 = is_clear ? {YW{1'b0}} : ky0[YW-1:0];
wire [XW-1:0] fill_x1 = is_clear ? B_XMAX[XW-1:0] : kx1[XW-1:0];
wire [YW-1:0] fill_y1 = is_clear ? B_YMAX[YW-1:0] : ky1[YW-1:0];
/* verilator lint_on UNUSEDSIGNAL */
// ---------------------------------------------------------
// Draw engines. Each one only says "plot (x, y)", one pixel
// per clock. Exactly one engine is busy at a time.
// ---------------------------------------------------------
wire line_plot, rect_plot, circ_plot;
wire signed [CB-1:0] line_x, line_y;
wire [XW-1:0] rect_x;
wire [YW-1:0] rect_y;
wire signed [PW-1:0] circ_x, circ_y;
line_renderer #(.CW(CB)) u_line (
.clk(clk), .reset(reset),
.start(accept && is_line),
.x0(a), .y0(b), .x1(c), .y1(d),
.busy(line_busy), .plot(line_plot), .x(line_x), .y(line_y)
);
rect_filler #(.XW(XW), .YW(YW)) u_rect (
.clk(clk), .reset(reset),
.start(accept && (is_clear || (is_rect && rect_visible))),
.x0(fill_x0), .y0(fill_y0), .x1(fill_x1), .y1(fill_y1),
.busy(rect_busy), .plot(rect_plot), .x(rect_x), .y(rect_y)
);
wire signed [PW-1:0] cx_p = {{3{a[CB-1]}}, a}; // sign-extend to PW
wire signed [PW-1:0] cy_p = {{3{b[CB-1]}}, b};
circle_renderer #(.CW(PW), .RW(CB - 1), .SCREEN_W(FB_W), .SCREEN_H(FB_H)) u_circ (
.clk(clk), .reset(reset),
.start(accept && is_circle),
.fill(arg_d[0]),
.cx_in(cx_p), .cy_in(cy_p),
.r_in(arg_c[CB-2:0]),
.busy(circ_busy), .plot(circ_plot), .px(circ_x), .py(circ_y)
);
// ---------------------------------------------------------
// Pixel writer, shared by all engines:
// pick the active engine -> clip -> address = y * FB_W + x
// ---------------------------------------------------------
localparam signed [PW-1:0] P_ZERO = 0;
localparam signed [PW-1:0] P_W = FB_W[PW-1:0];
localparam signed [PW-1:0] P_H = FB_H[PW-1:0];
wire signed [PW-1:0] rect_xs = $signed({{(PW-XW){1'b0}}, rect_x});
wire signed [PW-1:0] rect_ys = $signed({{(PW-YW){1'b0}}, rect_y});
wire signed [PW-1:0] line_xs = {{3{line_x[CB-1]}}, line_x};
wire signed [PW-1:0] line_ys = {{3{line_y[CB-1]}}, line_y};
wire plot = line_plot || rect_plot || circ_plot;
wire signed [PW-1:0] plot_x = line_plot ? line_xs : circ_plot ? circ_x : rect_xs;
wire signed [PW-1:0] plot_y = line_plot ? line_ys : circ_plot ? circ_y : rect_ys;
wire on_screen = (plot_x >= P_ZERO) && (plot_x < P_W) &&
(plot_y >= P_ZERO) && (plot_y < P_H);
wire draw_we = plot && on_screen;
// only used when on_screen, so the low XW / YW bits are the whole value
localparam [ADDR_BITS-1:0] STRIDE = FB_W[ADDR_BITS-1:0];
wire [ADDR_BITS-1:0] draw_x = {{(ADDR_BITS-XW){1'b0}}, plot_x[XW-1:0]};
wire [ADDR_BITS-1:0] draw_y = {{(ADDR_BITS-YW){1'b0}}, plot_y[YW-1:0]};
// ---------------------------------------------------------
// SWAP and double buffering
// front_buf = the buffer on screen; we always draw the other one
// ---------------------------------------------------------
reg front_buf;
wire vblank_start;
always @(posedge clk) begin
if (reset) begin
front_buf <= 1'b0;
swap_pending <= 1'b0;
end
else if (accept && is_swap)
swap_pending <= 1'b1;
else if (swap_pending && vblank_start) begin
swap_pending <= 1'b0;
if (DOUBLE_BUF)
front_buf <= !front_buf;
end
end
localparam BUF1_I = DOUBLE_BUF ? FB_PIXELS : 0;
localparam [ADDR_BITS-1:0] BUF1 = BUF1_I[ADDR_BITS-1:0];
wire [ADDR_BITS-1:0] front_base = front_buf ? BUF1 : {ADDR_BITS{1'b0}};
wire [ADDR_BITS-1:0] back_base = front_buf ? {ADDR_BITS{1'b0}} : BUF1;
// ---------------------------------------------------------
// Framebuffer: the init sweep has the write port until done
// ---------------------------------------------------------
wire fb_we = (!init_done && !reset) || draw_we;
wire [ADDR_BITS-1:0] fb_waddr = init_done ? back_base + draw_y * STRIDE + draw_x : init_addr;
wire [PIX_BITS-1:0] fb_wdata = init_done ? draw_color : {PIX_BITS{1'b0}};
wire [ADDR_BITS-1:0] scan_addr;
wire [PIX_BITS-1:0] scan_data;
frame_buffer #(.PIX_BITS(PIX_BITS), .DEPTH(DEPTH), .ADDR_BITS(ADDR_BITS)) u_fb (
.clk(clk),
.write_en(fb_we), .addr_write(fb_waddr), .write_data(fb_wdata),
.addr_read(front_base + scan_addr), .read_data(scan_data)
);
// ---------------------------------------------------------
// VGA scan-out
// ---------------------------------------------------------
vga_controller #(
.FB_WIDTH(FB_W), .SCALE_SHIFT(SCALE_SHIFT),
.PIX_BITS(PIX_BITS), .ADDR_BITS(ADDR_BITS)
) u_vga (
.clk(clk), .reset(reset), .frame_valid(init_done),
.fb_addr(scan_addr), .fb_data(scan_data),
.vblank_start(vblank_start),
.hsync(vga_hs), .vsync(vga_vs), .pixel(vga_pix)
);
endmoduleinit_done → READY. The FPGA needs 153,600 clocks (6.1 ms).Simulate before you touch hardware
Run everything in the LibreLane devshell (it ships Icarus Verilog 13). One script runs all of it in about a minute.
The self-checking testbench
How it checks
sim/tb_gpu.v keeps a software model of the framebuffer. After every command it checks the number of pixels written and compares every pixel of the back buffer; then it captures a whole VGA frame from the output pins and checks all 800 × 525 samples including HSYNC and VSYNC.
| Group | What is tested |
|---|---|
| [1] | READY and RGB low during reset; exact count of power-up clear writes |
| [2] | lines: 8 octants, horizontal, vertical, single point, clipped at both ends, fully off screen |
| [3] | rectangles: normal, clipped top-left (negative x/y), clipped bottom-right, zero width, off screen |
| [4] | circles: outline + filled, r = 0 and 1, clipped on every side, off screen, r bigger than the screen, the extreme (2047, −2048, 2047) |
| [5] | 79-bit frame, 81-bit frame, unknown opcode → nothing written |
| [6] | a second command sent while CLEAR is busy → dropped |
| [7] | scene with lines, rectangles and circles + SWAP; the swap must land exactly on vblank; full frame from the pins |
| [8] | reset in the middle of a command → clean restart |
The model is written the simple way (loops over integers, no widths, no FSMs), so a mistake in the RTL's bit widths or state machine shows up as a mismatch. For the circle it uses the same span rules as the RTL — and scripts/check_circle.py separately proves those rules give the right disc.
▸ Show sim/tb_gpu.v · 488 lines
`timescale 1ns / 1ps
// =============================================================
// Self-checking testbench for gpu_core
// [1] reset + power-up clear [5] malformed SPI frames
// [2] lines [6] command while busy
// [3] rectangles [7] SWAP + full frame from the pins
// [4] circles [8] reset in the middle of a command
//
// default : FPGA parameters (320x240, RGB332, double buffer)
// -DASIC_CFG : ASIC parameters (40x30, RGB111, single buffer)
//
// +vcd dump waveforms to build/gpu.vcd
// +demo=<file.hex> run a command stream from gen_demo.py
// +frames=<prefix> where captured VGA frames are written
//
// A software model of the framebuffer is kept next to the DUT.
// After every command the DUT memory is compared with the model,
// and captured VGA frames are compared pixel-by-pixel too.
// =============================================================
module tb_gpu;
`ifdef ASIC_CFG
localparam FB_W = 40, FB_H = 30, SHIFT = 4, PIX_BITS = 3, DOUBLE_BUF = 0;
`elsif SRAM_CFG
localparam FB_W = 80, FB_H = 60, SHIFT = 3, PIX_BITS = 8, DOUBLE_BUF = 0;
`else
localparam FB_W = 320, FB_H = 240, SHIFT = 1, PIX_BITS = 8, DOUBLE_BUF = 1;
`endif
localparam FB_PIXELS = FB_W * FB_H;
localparam DEPTH = FB_PIXELS * (DOUBLE_BUF ? 2 : 1);
localparam SPI_HALF = 250; // 2 MHz SCK
// ---------------- clock / DUT ----------------
reg clk = 1'b0;
always #20 clk = ~clk; // 25 MHz
reg rst_n = 1'b0;
reg cs_n = 1'b1, sck = 1'b0, mosi = 1'b0;
wire ready, hs, vs, dbg;
wire [PIX_BITS-1:0] pix;
gpu_core #(
.FB_W(FB_W), .FB_H(FB_H), .SCALE_SHIFT(SHIFT),
.PIX_BITS(PIX_BITS), .DOUBLE_BUF(DOUBLE_BUF)
) dut (
.clk(clk), .rst_n(rst_n),
.spi_cs_n(cs_n), .spi_sck(sck), .spi_mosi(mosi),
.gpu_ready(ready),
.vga_hs(hs), .vga_vs(vs), .vga_pix(pix),
.dbg_cmd_toggle(dbg)
);
// ---------------- write monitor ----------------
integer writes = 0;
always @(posedge clk) begin
if (dut.fb_we === 1'b1) begin
if (dut.fb_waddr >= DEPTH)
$fatal(1, "FB write out of range: %0d", dut.fb_waddr);
if (dut.line_plot + dut.rect_plot + dut.circ_plot > 1)
$fatal(1, "two engines plotting at once");
writes = writes + 1;
end
end
// READY watchdog
integer stall = 0;
always @(posedge clk) begin
if (ready === 1'b1) stall = 0;
else begin
stall = stall + 1;
if (stall > 3000000) $fatal(1, "READY stuck low (line %b rect %b circle %b swap %b)", dut.line_busy, dut.rect_busy, dut.circ_busy, dut.swap_pending);
end
end
// swaps must happen exactly at the start of vertical blanking
reg prev_front = 1'b0;
integer swaps_seen = 0;
always @(negedge clk) begin
if (dut.front_buf !== prev_front && dut.reset !== 1'b1) begin
if (dut.u_vga.v_count != 480 || dut.u_vga.h_count != 1)
$fatal(1, "buffer swap outside vblank (v=%0d h=%0d)",
dut.u_vga.v_count, dut.u_vga.h_count);
swaps_seen = swaps_seen + 1;
end
prev_front = dut.front_buf;
end
// ---------------- software model ----------------
reg [PIX_BITS-1:0] model [0 : 2*FB_PIXELS-1];
integer front = 0; // which model buffer is on screen
integer model_count; // pixels the last command should write
function [PIX_BITS-1:0] conv(input [7:0] c);
conv = (PIX_BITS == 3) ? {c[7], c[4], c[1]} : c[PIX_BITS-1:0];
endfunction
function integer back;
input dummy;
back = DOUBLE_BUF ? 1 - front : 0;
endfunction
function integer sx12(input [15:0] v); // 12-bit signed, like the RTL
sx12 = v[11] ? ($signed({1'b0, v[11:0]}) - 4096) : v[11:0];
endfunction
task model_plot(input integer x, input integer y, input [PIX_BITS-1:0] c);
begin
if (x >= 0 && x < FB_W && y >= 0 && y < FB_H) begin
model[back(0) * FB_PIXELS + y * FB_W + x] = c;
model_count = model_count + 1;
end
end
endtask
task model_line(input integer x0, y0, x1, y1, input [PIX_BITS-1:0] c);
integer x, y, dx, dy, sx, sy, err, e2, done;
begin
dx = (x1 > x0) ? x1 - x0 : x0 - x1;
dy = (y1 > y0) ? y0 - y1 : y1 - y0;
sx = (x0 < x1) ? 1 : -1;
sy = (y0 < y1) ? 1 : -1;
err = dx + dy; x = x0; y = y0; done = 0;
while (!done) begin
model_plot(x, y, c);
if (x == x1 && y == y1) done = 1;
else begin
e2 = 2 * err;
if (e2 >= dy) begin err = err + dy; x = x + sx; end
if (e2 <= dx) begin err = err + dx; y = y + sy; end
end
end
end
endtask
task model_rect(input integer x, y, w, h, input [PIX_BITS-1:0] c);
integer i, j, x0, y0, x1, y1;
begin
x0 = (x < 0) ? 0 : x; y0 = (y < 0) ? 0 : y;
x1 = (x + w > FB_W) ? FB_W : x + w;
y1 = (y + h > FB_H) ? FB_H : y + h;
for (j = y0; j < y1; j = j + 1)
for (i = x0; i < x1; i = i + 1)
model_plot(i, j, c);
end
endtask
// midpoint circle, same step order and span rules as circle_renderer.v
task model_span(input integer row, xa, xb, input [PIX_BITS-1:0] c);
integer i;
begin
if (xa < 0) xa = 0;
if (xb > FB_W - 1) xb = FB_W - 1;
if (row >= 0 && row < FB_H)
for (i = xa; i <= xb; i = i + 1)
model_plot(i, row, c);
end
endtask
task model_circle(input integer cx, cy, r, fill, input [PIX_BITS-1:0] c);
integer x, y, dd, xn, yn, dn, last;
begin
x = r; y = 0; dd = 1 - r; last = 0;
while (!last) begin
yn = y + 1;
xn = (dd < 0) ? x : x - 1;
dn = (dd < 0) ? dd + 2 * yn + 1 : dd + 2 * (yn - xn) + 1;
last = (xn < yn);
if (!fill) begin
model_plot(cx + x, cy + y, c); model_plot(cx + y, cy + x, c);
model_plot(cx - y, cy + x, c); model_plot(cx - x, cy + y, c);
model_plot(cx - x, cy - y, c); model_plot(cx - y, cy - x, c);
model_plot(cx + y, cy - x, c); model_plot(cx + x, cy - y, c);
end
else begin
model_span(cy + y, cx - x, cx + x, c);
if (y != 0)
model_span(cy - y, cx - x, cx + x, c);
if ((dd >= 0 || last) && x != y) begin
model_span(cy + x, cx - y, cx + y, c);
model_span(cy - x, cx - y, cx + y, c);
end
end
x = xn; y = yn; dd = dn;
end
end
endtask
task model_apply(input [79:0] w);
reg [7:0] op;
integer a, b, c, d;
begin
op = w[79:72];
a = sx12(w[71:56]); b = sx12(w[55:40]);
c = sx12(w[39:24]); d = sx12(w[23:8]);
model_count = 0;
case (op)
8'h01: model_rect(0, 0, FB_W, FB_H, conv(w[7:0]));
8'h02: model_line(a, b, c, d, conv(w[7:0]));
8'h03: model_rect(a, b, w[39:24] & 12'hFFF, w[23:8] & 12'hFFF, conv(w[7:0]));
8'h04: if (DOUBLE_BUF) front = 1 - front;
8'h05: model_circle(a, b, w[34:24], w[8], conv(w[7:0]));
default: ;
endcase
end
endtask
// read one pixel out of the DUT memory (flip-flop array or SRAM macros)
function [PIX_BITS-1:0] peek(input integer a);
`ifdef SRAM_CFG
reg [31:0] wd;
begin
case (a / 1024)
0: wd = dut.u_fb.g_bank[0].u_sram.mem[(a % 1024) / 4];
1: wd = dut.u_fb.g_bank[1].u_sram.mem[(a % 1024) / 4];
2: wd = dut.u_fb.g_bank[2].u_sram.mem[(a % 1024) / 4];
3: wd = dut.u_fb.g_bank[3].u_sram.mem[(a % 1024) / 4];
default: wd = dut.u_fb.g_bank[4].u_sram.mem[(a % 1024) / 4];
endcase
peek = wd >> (8 * (a % 4));
end
`else
peek = dut.u_fb.mem[a];
`endif
endfunction
task compare_back;
integer i, base;
begin
base = DOUBLE_BUF ? (dut.front_buf ? 0 : FB_PIXELS) : 0;
if (DOUBLE_BUF && dut.front_buf !== front[0])
$fatal(1, "front buffer mismatch");
for (i = 0; i < FB_PIXELS; i = i + 1)
if (peek(base + i) !== model[back(0) * FB_PIXELS + i])
$fatal(1, "FB mismatch at pixel %0d (x=%0d y=%0d): dut=%h model=%h",
i, i % FB_W, i / FB_W, peek(base + i),
model[back(0) * FB_PIXELS + i]);
end
endtask
// ---------------- SPI host ----------------
task wait_ready;
begin
wait (ready === 1'b1);
@(negedge clk);
@(negedge clk); // SRAM macros commit writes half a clock later
end
endtask
task spi_frame(input [79:0] w, input integer nbits);
integer i;
begin
cs_n = 1'b0;
#(SPI_HALF);
for (i = 0; i < nbits; i = i + 1) begin
mosi = (i < 80) ? w[79 - i] : 1'b0;
#(SPI_HALF) sck = 1'b1;
#(SPI_HALF) sck = 1'b0;
end
#(SPI_HALF) cs_n = 1'b1;
#(SPI_HALF);
end
endtask
integer n_cmds = 0;
// send one command, then check write count + whole back buffer
task exec(input [79:0] w);
integer wr0;
begin
wait_ready;
model_apply(w);
wr0 = writes;
spi_frame(w, 80);
repeat (8) @(negedge clk);
wait_ready;
if (writes - wr0 != model_count)
$fatal(1, "cmd %h wrote %0d pixels, model says %0d", w, writes - wr0, model_count);
if (w[79:72] != 8'h04)
compare_back;
n_cmds = n_cmds + 1;
end
endtask
function [79:0] mk(input [7:0] op, input integer a, b, c, d, input [7:0] col);
mk = {op, a[15:0], b[15:0], c[15:0], d[15:0], col};
endfunction
// ---------------- VGA frame capture from the pins ----------------
integer hd1 = 0, vd1 = 0, hd2 = 0, vd2 = 0;
integer cap_state = 0, cap_fd = 0, cap_errors = 0;
reg [PIX_BITS-1:0] expect_pix;
reg expect_hs, expect_vs;
always @(negedge clk) begin
// pins at this negedge belong to the counter value seen 2 negedges ago
if (cap_state == 1 && hd2 == 0 && vd2 == 0)
cap_state = 2;
if (cap_state == 2) begin
expect_hs = !(hd2 >= 656 && hd2 < 752);
expect_vs = !(vd2 >= 490 && vd2 < 492);
if (hd2 < 640 && vd2 < 480)
expect_pix = model[front * FB_PIXELS + (vd2 >> SHIFT) * FB_W + (hd2 >> SHIFT)];
else
expect_pix = 0;
if (pix !== expect_pix || hs !== expect_hs || vs !== expect_vs) begin
cap_errors = cap_errors + 1;
if (cap_errors < 5)
$display("VGA mismatch at (%0d,%0d): pix=%h exp=%h hs=%b vs=%b",
hd2, vd2, pix, expect_pix, hs, vs);
end
if (hd2 < 640 && vd2 < 480)
$fwrite(cap_fd, "%h\n", pix);
if (hd2 == 799 && vd2 == 524)
cap_state = 3;
end
hd2 = hd1; vd2 = vd1;
hd1 = dut.u_vga.h_count; vd1 = dut.u_vga.v_count;
end
task capture_frame(input [8*128-1:0] fname);
begin
cap_fd = $fopen(fname, "w");
cap_errors = 0;
cap_state = 1;
wait (cap_state == 3);
cap_state = 0;
$fclose(cap_fd);
if (cap_errors != 0)
$fatal(1, "captured frame %0s has %0d mismatches", fname, cap_errors);
$display(" captured + verified frame -> %0s", fname);
end
endtask
// ---------------- test sequence ----------------
reg [8*128-1:0] demo_file, frame_prefix, fname;
reg [79:0] w;
integer fd, i, r, wr0, frame_no, swaps_in_stream;
initial begin
if ($test$plusargs("vcd")) begin
$dumpfile("build/gpu.vcd");
$dumpvars(0, tb_gpu);
end
if (!$value$plusargs("frames=%s", frame_prefix))
frame_prefix = "build/frame";
for (i = 0; i < 2 * FB_PIXELS; i = i + 1) model[i] = 0;
// ---- 1. reset + power-up clear ----
#1000;
if (ready !== 1'b0 || pix !== 0) $fatal(1, "reset: READY/RGB not low");
rst_n = 1'b1;
wait_ready;
if (writes != DEPTH) $fatal(1, "power-up clear wrote %0d, expected %0d", writes, DEPTH);
compare_back;
$display("[1] reset + power-up clear of %0d words OK", DEPTH);
if ($value$plusargs("demo=%s", demo_file)) begin
// ---------------- demo mode ----------------
fd = $fopen(demo_file, "r");
if (fd == 0) $fatal(1, "cannot open %0s", demo_file);
frame_no = 0; swaps_in_stream = 0;
while (!$feof(fd)) begin
r = $fscanf(fd, "%h\n", w);
if (r == 1) begin
exec(w);
if (w[79:72] == 8'h04) begin
swaps_in_stream = swaps_in_stream + 1;
if (DOUBLE_BUF || swaps_in_stream > 1) begin
$sformat(fname, "%0s_%03d.hex", frame_prefix, frame_no);
capture_frame(fname);
frame_no = frame_no + 1;
end
end
end
end
$fclose(fd);
$display("PASS: demo %0s, %0d commands, %0d frames", demo_file, n_cmds, frame_no);
$finish;
end
// ---- 2. lines: all 8 octants, axis, point, clipped ----
exec(mk(8'h01, 0, 0, 0, 0, 8'h00));
exec(mk(8'h02, FB_W/2, FB_H/2, FB_W-3, FB_H/2+3, 8'hE0));
exec(mk(8'h02, FB_W/2, FB_H/2, FB_W/2+4, FB_H-2, 8'h1C));
exec(mk(8'h02, FB_W/2, FB_H/2, FB_W/2-4, FB_H-2, 8'h03));
exec(mk(8'h02, FB_W/2, FB_H/2, 2, FB_H/2+3, 8'hFC));
exec(mk(8'h02, FB_W/2, FB_H/2, 2, FB_H/2-3, 8'h1F));
exec(mk(8'h02, FB_W/2, FB_H/2, FB_W/2-4, 1, 8'hE3));
exec(mk(8'h02, FB_W/2, FB_H/2, FB_W/2+4, 1, 8'hFF));
exec(mk(8'h02, FB_W/2, FB_H/2, FB_W-3, FB_H/2-3, 8'hF0));
exec(mk(8'h02, 0, 0, FB_W-1, 0, 8'hFF)); // horizontal
exec(mk(8'h02, FB_W-1, FB_H-1, FB_W-1, 0, 8'hE0)); // vertical
exec(mk(8'h02, 5, 5, 5, 5, 8'h1C)); // single point
exec(mk(8'h02, -20, -10, FB_W+15, FB_H+7, 8'h03)); // clipped both ends
exec(mk(8'h02, -100, 3, -5, 9, 8'hFF)); // fully off screen
$display("[2] line renderer: octants, axis, point, clipping OK");
// ---- 3. rectangles + clipping ----
exec(mk(8'h03, 3, 2, 7, 5, 8'hE0));
exec(mk(8'h03, -4, -3, 9, 8, 8'h1C)); // clipped top/left
exec(mk(8'h03, FB_W-4, FB_H-3, 50, 50, 8'h03)); // clipped bottom/right
exec(mk(8'h03, 10, 10, 0, 5, 8'hFF)); // zero width -> nothing
exec(mk(8'h03, FB_W+5, 2, 4, 4, 8'hFF)); // off screen -> nothing
$display("[3] rectangle filler + clipping OK");
// ---- 4. circles: outline + filled, tiny, clipped, huge, off screen ----
exec(mk(8'h01, 0, 0, 0, 0, 8'h00));
exec(mk(8'h05, FB_W/2, FB_H/2, FB_H/3, 0, 8'hFF)); // outline
exec(mk(8'h05, FB_W/2, FB_H/2, FB_H/5, 1, 8'hE0)); // filled
exec(mk(8'h05, 4, 4, 0, 0, 8'h1C)); // r = 0
exec(mk(8'h05, 8, 4, 0, 1, 8'h1C));
exec(mk(8'h05, 4, 9, 1, 0, 8'h03)); // r = 1
exec(mk(8'h05, 9, 9, 1, 1, 8'h03));
exec(mk(8'h05, -3, 2, 8, 0, 8'hFC)); // clipped left/top
exec(mk(8'h05, -3, FB_H/2, 8, 1, 8'hFC));
exec(mk(8'h05, FB_W-2, FB_H-1, 10, 1, 8'h1F)); // clipped right/bottom
exec(mk(8'h05, FB_W-2, 1, 9, 0, 8'hE3));
exec(mk(8'h05, -100, -100, 5, 1, 8'hFF)); // off screen
exec(mk(8'h05, 2047, -2048, 2047, 0, 8'hFF)); // extreme values
exec(mk(8'h05, 2047, -2048, 2047, 1, 8'hFF));
exec(mk(8'h05, FB_W/2, FB_H/2, FB_W, 1, 8'h92)); // covers the screen
exec(mk(8'h05, FB_W/2, FB_H/2, FB_W, 0, 8'hF0)); // all off screen
$display("[4] circle renderer: outline, filled, r=0/1, clipping, extremes OK");
// ---- 5. malformed frames must not write anything ----
wr0 = writes;
wait_ready; spi_frame(mk(8'h03, 0, 0, 5, 5, 8'hFF), 79);
wait_ready; spi_frame(mk(8'h03, 0, 0, 5, 5, 8'hFF), 81);
wait_ready; spi_frame(mk(8'h7F, 0, 0, 5, 5, 8'hFF), 80);
repeat (50) @(negedge clk);
wait_ready;
if (writes != wr0) $fatal(1, "malformed frame wrote pixels");
compare_back;
$display("[5] short / long / unknown frames ignored OK");
// ---- 6. a frame sent while busy is dropped ----
model_apply(mk(8'h01, 0, 0, 0, 0, 8'h92));
wr0 = writes;
wait_ready;
spi_frame(mk(8'h01, 0, 0, 0, 0, 8'h92), 80); // CLEAR (busy for FB_PIXELS clocks)
spi_frame(mk(8'h03, 0, 0, 4, 4, 8'hE0), 80); // immediately, no READY check
repeat (8) @(negedge clk);
wait_ready;
if (writes - wr0 != FB_PIXELS) $fatal(1, "busy-drop test wrote %0d", writes - wr0);
compare_back;
$display("[6] command during busy dropped OK");
// ---- 7. build a scene, SWAP, capture a full frame from the pins ----
exec(mk(8'h01, 0, 0, 0, 0, 8'h00));
exec(mk(8'h03, 2, 2, FB_W/3, FB_H/3, 8'hE0));
exec(mk(8'h03, FB_W/2, FB_H/2, FB_W/3, FB_H/3, 8'h1C));
exec(mk(8'h02, 0, FB_H-1, FB_W-1, 0, 8'hFF));
exec(mk(8'h02, 0, 0, FB_W-1, FB_H-1, 8'h03));
exec(mk(8'h05, FB_W*3/4, FB_H/4, FB_H/6, 1, 8'hFC));
exec(mk(8'h05, FB_W/4, FB_H*3/4, FB_H/6, 0, 8'h1F));
exec(mk(8'h04, 0, 0, 0, 0, 8'h00)); // SWAP
if (DOUBLE_BUF && swaps_seen != 1) $fatal(1, "swap did not happen");
$sformat(fname, "%0s_test.hex", frame_prefix);
capture_frame(fname);
$display("[7] SWAP at vblank + full 800x525 frame (pixels, HSYNC, VSYNC) OK");
// ---- 8. reset again in the middle of things ----
wait_ready;
spi_frame(mk(8'h01, 0, 0, 0, 0, 8'hFF), 80);
#2000;
rst_n = 1'b0; #500;
if (ready !== 1'b0) $fatal(1, "READY high in reset");
wr0 = writes;
rst_n = 1'b1;
for (i = 0; i < 2 * FB_PIXELS; i = i + 1) model[i] = 0;
front = 0;
wait_ready;
if (writes - wr0 != DEPTH) $fatal(1, "second power-up clear wrote %0d", writes - wr0);
compare_back;
$display("[8] reset during a command + second clear OK");
$display("PASS: all gpu_core tests (%0dx%0d, %0d-bit, %s buffer), %0d commands",
FB_W, FB_H, PIX_BITS, DOUBLE_BUF ? "double" : "single", n_cmds);
$finish;
end
endmoduleDo
- Start the LibreLane devshell the same way you did for counter8.
- Run:
cd ~/asic_projects/raster_gpu
bash run_sims.sh▸ Show run_sims.sh · 80 lines
#!/usr/bin/env bash
# =============================================================
# run_sims.sh : every simulation + the pin cross-check, one command
# cd ~/asic_projects/raster_gpu && bash run_sims.sh
# Stops at the first failure (set -e + $fatal in the testbenches).
# =============================================================
set -e
mkdir -p build/demo
RTL="rtl/spi_cmd_rx.v rtl/vga_controller.v rtl/frame_buffer.v
rtl/line_renderer.v rtl/rect_filler.v rtl/circle_renderer.v rtl/gpu_core.v"
# SRAM build: same RTL, but the SRAM frame_buffer + a stand-in macro model
SRAM_RTL="rtl/spi_cmd_rx.v rtl/vga_controller.v rtl/line_renderer.v rtl/rect_filler.v
rtl/circle_renderer.v rtl/gpu_core.v asic_sram/src/frame_buffer.v sim/sram_model_sim.v"
show() { grep -E "^\[|PASS|FATAL|mismatch" || true; }
echo "=== 1/8 FPGA config (320x240, RGB332, double buffer)"
iverilog -g2012 -s tb_gpu -o build/tb_fpga $RTL sim/tb_gpu.v
vvp -n build/tb_fpga +frames=build/fpga | show
echo "=== 2/8 ASIC v1 config (40x30, RGB111, single buffer)"
iverilog -g2012 -DASIC_CFG -s tb_gpu -o build/tb_asic $RTL sim/tb_gpu.v
vvp -n build/tb_asic +frames=build/asic | show
echo "=== 3/8 ASIC v2 config (80x60, RGB332, 5 SRAM macros)"
iverilog -g2012 -DSRAM_CFG -s tb_gpu -o build/tb_sram $SRAM_RTL sim/tb_gpu.v
vvp -n build/tb_sram +frames=build/sram | show
echo "=== 4/8 short waveform run -> build/wave.vcd"
iverilog -g2012 -s tb_wave -o build/tb_wave $RTL asic/src/gpu_asic.v sim/tb_wave.v
vvp -n build/tb_wave > /dev/null && echo "wave.vcd written (open with: gtkwave sim/wave.gtkw)"
echo "=== 5/8 chip_top wiring with pad stand-ins"
iverilog -g2012 -DUSE_POWER_PINS -s tb_chip -o build/tb_chip $RTL asic/src/gpu_asic.v \
chip/rtl/chip_top.v sim/pad_models_sim.v sim/tb_chip.v
vvp -n build/tb_chip | show
echo "=== 6/8 demos on the FPGA config: circles + cube (6 frames)"
python3 scripts/gen_demo.py fpga circles build/demo/fpga_circles.cmd
vvp -n build/tb_fpga +demo=build/demo/fpga_circles.cmd +frames=build/demo/fpga_circles | grep -E "PASS|FATAL"
python3 scripts/gen_demo.py fpga cube build/demo/fpga_cube.cmd 6
vvp -n build/tb_fpga +demo=build/demo/fpga_cube.cmd +frames=build/demo/fpga_cube | grep -E "PASS|FATAL"
echo "=== 7/8 FPGA bring-up: step 1 VGA test, then fpga_top at steps 2, 3, 4 with its test host"
mkdir -p build/vga_test build/selftest
iverilog -g2012 -s tb_vga_test -o build/tb_vga_test rtl/vga_controller.v bringup/step1_vga/vga_pattern.v \
bringup/step1_vga/vga_test_top.v sim/clk_wiz_sim.v sim/tb_vga_test.v
vvp -n build/tb_vga_test | grep -E "PASS|FATAL"
python3 scripts/check_vga_test.py | tail -n 1
python3 scripts/gen_selftest.py > build/selftest/gen.log
BASE="rtl/spi_cmd_rx.v rtl/vga_controller.v rtl/frame_buffer.v rtl/rect_filler.v"
for S in 2 3 4; do
# each step is compiled with exactly the files it has at that point
case $S in
2) FILES="$BASE bringup/step2_rect/gpu_core.v"; ROM=bringup/step2_rect/selftest.mem ;;
3) FILES="$BASE rtl/line_renderer.v bringup/step3_line/gpu_core.v"; ROM=bringup/step3_line/selftest.mem ;;
4) FILES="$BASE rtl/line_renderer.v rtl/circle_renderer.v rtl/gpu_core.v"; ROM=fpga/selftest.mem ;;
esac
iverilog -g2012 -DSTEP=$S -DROM=\"$ROM\" -s tb_selftest -o build/tb_selftest_$S $FILES \
fpga/spi_test_host.v fpga/fpga_top.v sim/clk_wiz_sim.v sim/tb_selftest.v
vvp -n build/tb_selftest_$S | grep -E "PASS|FATAL"
TESTS="1 2 3 4 5 6"; [ $S = 2 ] && TESTS="1 2 3"
for n in $TESTS; do
vvp -n build/tb_fpga +demo=build/selftest/step${S}_test$n.cmd +frames=build/selftest/ref_${S}_$n | grep -q PASS
cmp -s build/selftest/board_$n.hex build/selftest/ref_${S}_${n}_000.hex || { echo "FAIL: step $S test $n"; exit 1; }
done
cmp -s build/selftest/auto.hex build/selftest/ref_${S}_1_000.hex || { echo "FAIL: step $S power-up"; exit 1; }
cmp -s build/selftest/board_2_loop.hex build/selftest/ref_${S}_2_000.hex || { echo "FAIL: step $S loopback"; exit 1; }
mkdir -p build/selftest/step$S && mv build/selftest/board_*.hex build/selftest/auto.hex build/selftest/step$S/
echo " step $S: power-up + $(echo $TESTS | wc -w) test frames + loopback == golden-model frames"
done
echo "=== 8/8 circle algorithm check + pin/connection cross-check"
python3 scripts/check_circle.py 200 > build/check_circle.log || { cat build/check_circle.log; exit 1; }
head -n 1 build/check_circle.log
python3 scripts/check_pins.py > build/check_pins.log || { cat build/check_pins.log; exit 1; }
tail -n 1 build/check_pins.log
echo "ALL SIMULATIONS PASSED"Expected (real output)
=== 1/8 FPGA config (320x240, RGB332, double buffer)
[1] reset + power-up clear of 153600 words OK
[2] line renderer: octants, axis, point, clipping OK
[3] rectangle filler + clipping OK
[4] circle renderer: outline, filled, r=0/1, clipping, extremes OK
[5] short / long / unknown frames ignored OK
[6] command during busy dropped OK
[7] SWAP at vblank + full 800x525 frame (pixels, HSYNC, VSYNC) OK
[8] reset during a command + second clear OK
PASS: all gpu_core tests (320x240, 8-bit, double buffer), 43 commands
=== 2/8 ASIC v1 config (40x30, RGB111, single buffer)
[1] reset + power-up clear of 1200 words OK
[2] line renderer: octants, axis, point, clipping OK
[3] rectangle filler + clipping OK
[4] circle renderer: outline, filled, r=0/1, clipping, extremes OK
[5] short / long / unknown frames ignored OK
[6] command during busy dropped OK
[7] SWAP at vblank + full 800x525 frame (pixels, HSYNC, VSYNC) OK
[8] reset during a command + second clear OK
PASS: all gpu_core tests (40x30, 3-bit, single buffer), 43 commands
=== 3/8 ASIC v2 config (80x60, RGB332, 5 SRAM macros)
[1] reset + power-up clear of 4800 words OK
[2] line renderer: octants, axis, point, clipping OK
[3] rectangle filler + clipping OK
[4] circle renderer: outline, filled, r=0/1, clipping, extremes OK
[5] short / long / unknown frames ignored OK
[6] command during busy dropped OK
[7] SWAP at vblank + full 800x525 frame (pixels, HSYNC, VSYNC) OK
[8] reset during a command + second clear OK
PASS: all gpu_core tests (80x60, 8-bit, single buffer), 43 commands
=== 4/8 short waveform run -> build/wave.vcd
wave.vcd written (open with: gtkwave sim/wave.gtkw)
=== 5/8 chip_top wiring with pad stand-ins
[1] pads tri-stated while power_good = 0
[2] three commands accepted through the SPI pads
[3] full frame on pad_rgb matches the framebuffer
PASS: chip_top wiring (11 GPIO + power-good + supplies + macro)
=== 6/8 demos on the FPGA config: circles + cube (6 frames)
24 commands -> build/demo/fpga_circles.cmd
PASS: demo build/demo/fpga_circles.cmd, 24 commands, 1 frames
84 commands -> build/demo/fpga_cube.cmd
PASS: demo build/demo/fpga_cube.cmd, 84 commands, 6 frames
=== 7/8 FPGA bring-up: step 1 VGA test, then fpga_top at steps 2, 3, 4 with its test host
PASS: step 1 (VGA controller + adapter) frames captured
RESULT: ALL 5 PICTURES MATCH THE MODEL
PASS: bring-up step 2: power-up test + 6 tests + loopback
step 2: power-up + 3 test frames + loopback == golden-model frames
PASS: bring-up step 3: power-up test + 6 tests + loopback
step 3: power-up + 6 test frames + loopback == golden-model frames
PASS: bring-up step 4: power-up test + 6 tests + loopback
step 4: power-up + 6 test frames + loopback == golden-model frames
=== 8/8 circle algorithm check + pin/connection cross-check
radii 0..200: ALL CHECKS PASSED
RESULT: ALL CONNECTIONS CONSISTENT
ALL SIMULATIONS PASSEDIf it fails
| Message | Meaning |
|---|---|
FB mismatch at pixel … | the RTL wrote a different pixel than the model — the x/y in the message tell you where |
cmd … wrote N pixels, model says M | a renderer wrote too many / too few pixels |
READY stuck low (line 1 rect 0 circle 0 swap 0) | the watchdog fired after 3 M clocks; the flags say which engine never finished (that is how the signed-compare bug above showed up) |
two engines plotting at once | a start pulse reached an engine while another was busy — check idle / accept |
buffer swap outside vblank | SWAP logic broken |
syntax error near before | before is a SystemVerilog keyword under -g2012 |
python3 scripts/hex2png.py fpga build/fpga_test.hex fpga_test.png (needs pip install pillow --break-system-packages), then explorer.exe . to see it in Windows.
Read the waveforms in GTKWave
run_sims.sh also ran sim/tb_wave.v: reset, one LINE, one RECT, an outline CIRCLE and a filled CIRCLE, then it jumps to screen line ~100 and records two video lines. The VCD is ~490 KB and sim/wave.gtkw already groups the signals.
cd ~/asic_projects/raster_gpu
gtkwave sim/wave.gtkw # if missing: sudo apt install gtkwave- The window opens with seven groups: RESET / INIT, SPI, LINE, RECT, CIRCLE, PIXEL WRITER, VGA. Signed values (x, y, err, d) are already shown as signed decimals.
- Click the Zoom Fit toolbar button (magnifier with a box) to see the whole run.
- Select
tb_wave.dut.u_gpu.u_line.busy, then press the toolbar Find next edge arrow to jump to the line. Zoom with Ctrl + mouse wheel. Do the same withu_circ.busyfor the two circles. - Right-click a bus → Data Format›Decimal to switch between hex and decimal.
- Drag the primary marker (left click in the wave area) onto a
sck_risepulse and read the values in the signal column. - Compare with the pictures in Part 1 — they were drawn from this same VCD.
▸ Show sim/tb_wave.v · 68 lines
`timescale 1ns / 1ps
// =============================================================
// Short waveform testbench (ASIC parameters, small VCD)
// Open build/wave.vcd in GTKWave (or load sim/wave.gtkw).
// 1) reset + power-up clear
// 2) LINE (2,1) -> (9,4) red
// 3) RECT x=3 y=6 w=4 h=2 green
// 4) CIRCLE outline (20,15) r=3 white
// 5) CIRCLE filled (31,6) r=3 blue
// 6) jumps to screen line 100 (FB row 6) and records two video lines
// =============================================================
module tb_wave;
reg clk = 1'b0;
always #20 clk = ~clk; // 25 MHz
reg rst_n = 1'b0;
reg cs_n = 1'b1, sck = 1'b0, mosi = 1'b0;
wire ready, hs, vs;
wire [2:0] rgb;
gpu_asic dut (
.clk(clk), .rst_n(rst_n),
.spi_cs_n(cs_n), .spi_sck(sck), .spi_mosi(mosi),
.gpu_ready(ready), .vga_hs(hs), .vga_vs(vs), .vga_rgb(rgb)
);
task spi_send(input [79:0] w);
integer i;
begin
wait (ready === 1'b1);
#300 cs_n = 1'b0;
#250;
for (i = 79; i >= 0; i = i - 1) begin
mosi = w[i];
#250 sck = 1'b1;
#250 sck = 1'b0;
end
#250 cs_n = 1'b1;
#500;
end
endtask
initial begin
$dumpfile("build/wave.vcd");
$dumpvars(0, tb_wave);
#400 rst_n = 1'b1;
// op x0/x y0/y x1/w y1/h colour
spi_send({8'h02, 16'd2, 16'd1, 16'd9, 16'd4, 8'hE0}); // LINE red
#10000;
spi_send({8'h03, 16'd3, 16'd6, 16'd4, 16'd2, 8'h1C}); // RECT green
#10000;
spi_send({8'h05, 16'd20, 16'd15, 16'd3, 16'd0, 8'hFF}); // CIRCLE outline white
#10000;
spi_send({8'h05, 16'd31, 16'd6, 16'd3, 16'd1, 8'h03}); // CIRCLE filled blue
wait (ready === 1'b1);
#2000;
// skip ahead to screen line 100 (FB row 6: rectangle + filled circle)
$dumpoff;
wait (dut.u_gpu.u_vga.v_count == 10'd99);
$dumpon;
#80000; // > two 32 us video lines
$finish;
end
endmodule▸ Show sim/wave.gtkw · 79 lines
[*] GTKWave save file for build/wave.vcd (tb_wave.v)
[dumpfile] "build/wave.vcd"
[timestart] 0
[size] 1500 900
[sst_width] 260
[signals_width] 300
[sst_expanded] 1
@200
-RESET / INIT
@28
tb_wave.rst_n
tb_wave.dut.u_gpu.reset
tb_wave.dut.u_gpu.init_done
tb_wave.ready
@200
-SPI (pins + receiver)
@28
tb_wave.cs_n
tb_wave.sck
tb_wave.mosi
tb_wave.dut.u_gpu.u_spi.sck_s[2:0]
tb_wave.dut.u_gpu.u_spi.sck_rise
@24
tb_wave.dut.u_gpu.u_spi.bit_count[6:0]
@28
tb_wave.dut.u_gpu.u_spi.cmd_valid
@22
tb_wave.dut.u_gpu.u_spi.cmd_word[79:0]
@200
-LINE
@28
tb_wave.dut.u_gpu.u_line.busy
@424
tb_wave.dut.u_gpu.u_line.x[11:0]
tb_wave.dut.u_gpu.u_line.y[11:0]
tb_wave.dut.u_gpu.u_line.err[13:0]
@28
tb_wave.dut.u_gpu.u_line.step_x
tb_wave.dut.u_gpu.u_line.step_y
@200
-RECT
@28
tb_wave.dut.u_gpu.u_rect.busy
@24
tb_wave.dut.u_gpu.u_rect.x[5:0]
tb_wave.dut.u_gpu.u_rect.y[4:0]
@200
-CIRCLE
@28
tb_wave.dut.u_gpu.u_circ.busy
@24
tb_wave.dut.u_gpu.u_circ.state[1:0]
tb_wave.dut.u_gpu.u_circ.k[2:0]
tb_wave.dut.u_gpu.u_circ.s[1:0]
@424
tb_wave.dut.u_gpu.u_circ.x[14:0]
tb_wave.dut.u_gpu.u_circ.y[14:0]
tb_wave.dut.u_gpu.u_circ.d[14:0]
@200
-PIXEL WRITER
@28
tb_wave.dut.u_gpu.plot
@424
tb_wave.dut.u_gpu.plot_x[14:0]
tb_wave.dut.u_gpu.plot_y[14:0]
@28
tb_wave.dut.u_gpu.fb_we
@24
tb_wave.dut.u_gpu.fb_waddr[10:0]
@200
-VGA
@24
tb_wave.dut.u_gpu.u_vga.h_count[9:0]
tb_wave.dut.u_gpu.u_vga.v_count[9:0]
@28
tb_wave.hs
tb_wave.vs
@22
tb_wave.rgb[2:0]Render the demos in simulation
scripts/gen_demo.py is a Python copy of the Arduino drawing code and writes the exact command stream the Arduino would send. The testbench sends it over simulated SPI, captures every frame from the VGA pins, and checks each frame against the model. This is what your monitor should show:
# 36 cube frames on the FPGA config (~1 minute)
python3 scripts/gen_demo.py fpga cube build/demo/fpga_cube.cmd 36
vvp -n build/tb_fpga +demo=build/demo/fpga_cube.cmd +frames=build/demo/fpga_cube
python3 scripts/hex2png.py fpga build/demo/fpga_cube_010.hex cube10.png
# demos: pattern | starburst | circles | cube N | orbit N targets: fpga | asic | sram
python3 scripts/gen_demo.py asic pattern build/demo/asic_pattern.cmd
vvp -n build/tb_asic +demo=build/demo/asic_pattern.cmd +frames=build/demo/asic_pattern▸ Show scripts/gen_demo.py · 138 lines
#!/usr/bin/env python3
"""Generate SPI command streams identical to arduino/gpu_demo.ino.
Usage: gen_demo.py <fpga|asic|sram> <pattern|starburst|circles|cube|orbit> <out.hex> [frames]
Each line of the output is one 80-bit command in hex.
Also importable (scripts/gen_selftest.py uses the drawing helpers).
"""
import math, sys
OP_CLEAR, OP_LINE, OP_RECT, OP_SWAP, OP_CIRCLE = 1, 2, 3, 4, 5
BLACK, WHITE, RED, GREEN, BLUE = 0x00, 0xFF, 0xE0, 0x1C, 0x03
YELLOW, CYAN, MAGENTA, ORANGE, GREY = 0xFC, 0x1F, 0xE3, 0xF0, 0x92
PALETTE = [WHITE, YELLOW, CYAN, GREEN, MAGENTA, RED, BLUE, ORANGE]
FPGA, W, H = True, 320, 240
cmds = []
def setup(target):
"""select the build: fpga (320x240), sram (80x60) or asic (40x30)"""
global FPGA, W, H
FPGA = target == "fpga"
W, H = (320, 240) if FPGA else ((80, 60) if target == "sram" else (40, 30))
cmds.clear()
def send(op, a=0, b=0, c=0, d=0, col=0):
w = op
for v in (a, b, c, d):
w = (w << 16) | (v & 0xFFFF)
w = (w << 8) | col
cmds.append(w)
clear = lambda c: send(OP_CLEAR, col=c)
line = lambda x0, y0, x1, y1, c: send(OP_LINE, x0, y0, x1, y1, c)
rect = lambda x, y, w, h, c: send(OP_RECT, x, y, w, h, c)
swap = lambda: send(OP_SWAP)
circle = lambda cx, cy, r, c: send(OP_CIRCLE, cx, cy, r, 0, c)
fill_circle = lambda cx, cy, r, c: send(OP_CIRCLE, cx, cy, r, 1, c)
begin_frame = lambda: None if FPGA else swap()
end_frame = lambda: swap() if FPGA else None
def ctrunc(v): # C (int16_t) cast truncates toward zero
return int(v)
def test_pattern():
begin_frame(); clear(BLACK)
bw = W // 8
for i in range(8):
rect(i * bw, 0, bw, (H * 2) // 3, PALETTE[i])
rect(0, (H * 2) // 3, W, H // 3, GREY)
line(0, 0, W - 1, 0, WHITE); line(W - 1, 0, W - 1, H - 1, WHITE)
line(W - 1, H - 1, 0, H - 1, WHITE); line(0, H - 1, 0, 0, WHITE)
line(0, 0, W - 1, H - 1, RED); line(W - 1, 0, 0, H - 1, BLUE)
circle(W // 2, H // 2, H // 3, WHITE)
end_frame()
def starburst():
begin_frame(); clear(BLACK)
cx, cy, k = W // 2, H // 2, 0
step = 16 if W >= 160 else 4
for x in range(0, W, step): line(cx, cy, x, 0, PALETTE[k & 7]); k += 1
for y in range(0, H, step): line(cx, cy, W - 1, y, PALETTE[k & 7]); k += 1
for x in range(W - 1, 0, -step): line(cx, cy, x, H - 1, PALETTE[k & 7]); k += 1
for y in range(H - 1, 0, -step): line(cx, cy, 0, y, PALETTE[k & 7]); k += 1
end_frame()
def circles():
begin_frame(); clear(BLACK)
r, cy = (H * 3) // 10, H // 2
for i in range(5):
fill_circle(W // 4, cy, r - i * (r // 5), WHITE if i & 1 else RED)
for i in range(8):
circle((W * 3) // 4, cy, r - i * (r // 8), PALETTE[i])
for i in range(9):
fill_circle(i * (W // 8), H - 1, H // 12, PALETTE[i & 7])
end_frame()
def orbit(t):
cx, cy = W // 2, H // 2
R, m = (H * 2) // 5, H // 10
px = ctrunc(cx + R * math.cos(t)); py = ctrunc(cy + R * math.sin(t))
mx = ctrunc(px + m * math.cos(4 * t)); my = ctrunc(py + m * math.sin(4 * t))
begin_frame(); clear(BLACK)
circle(cx, cy, R, GREY)
fill_circle(cx, cy, H // 8, YELLOW)
fill_circle(px, py, H // 16, BLUE)
fill_circle(mx, my, H // 40, WHITE)
end_frame()
V = [(-1,-1,-1),(1,-1,-1),(1,1,-1),(-1,1,-1),(-1,-1,1),(1,-1,1),(1,1,1),(-1,1,1)]
E = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),(0,4),(1,5),(2,6),(3,7)]
def cube(ax, ay):
sx, cx, sy, cy = math.sin(ax), math.cos(ax), math.sin(ay), math.cos(ay)
f = H * 0.6
px, py = [], []
for x, y, z in V:
y1 = y * cx - z * sx; z1 = y * sx + z * cx
x2 = x * cy + z1 * sy; z2 = -x * sy + z1 * cy
zc = z2 + 4.0
px.append(ctrunc(W / 2 + (x2 * f) / zc)); py.append(ctrunc(H / 2 + (y1 * f) / zc))
begin_frame(); clear(BLACK)
for e, (a, b) in enumerate(E):
c = BLUE if e < 4 else (YELLOW if e < 8 else MAGENTA)
line(px[a], py[a], px[b], py[b], c)
end_frame()
def main():
target, demo, out = sys.argv[1], sys.argv[2], sys.argv[3]
setup(target)
run_demo(demo)
if not FPGA: # single buffer: one extra vblank wait so the frame we capture is complete
swap()
with open(out, "w") as fh:
for w in cmds:
fh.write("%020x\n" % w)
print(f"{len(cmds)} commands -> {out}")
def run_demo(demo, frames=None, first=0):
if demo == "pattern":
test_pattern()
elif demo == "starburst":
starburst()
elif demo == "circles":
circles()
elif demo == "orbit":
n = frames if frames is not None else (int(sys.argv[4]) if len(sys.argv) > 4 else 1)
for i in range(n):
orbit(i * 0.157)
elif demo == "cube":
n = frames if frames is not None else (int(sys.argv[4]) if len(sys.argv) > 4 else 1)
first = int(sys.argv[5]) if frames is None and len(sys.argv) > 5 else first
for i in range(first, first + n):
cube(i * 0.035, i * 0.05)
else:
sys.exit("unknown demo")
if __name__ == "__main__":
main()Run it on the PYNQ-Z2 — first on its own, then with an Arduino
Pure programmable logic: no Zynq PS, no block design, no AXI. You bring the GPU up the way you would write it: the VGA controller first (tested on your adapter), then SPI + framebuffer + RECT, then LINE, then CIRCLE — each step with its own tests and pictures on your monitor, driven by a small SPI master inside the FPGA. Then the Arduino takes over.
Pinout: which connector does what (and why the Arduino header)
The question
Your video adapter already sits on PMOD A and PMOD B, so the GPU's command interface needs a different connector with at least 4 free 3.3 V pins (CS, SCK, MOSI, READY) and a ground. Here are the candidates on the PYNQ-Z2:
| Connector | Reachable from the fabric (PL)? | Free pins | Verdict |
|---|---|---|---|
| PMOD A (JA) | yes | only pins JA-1 (Y18) and JA-7 (U18) | 2 pins — not enough |
| PMOD B (JB) | yes | none | full |
| Raspberry Pi header | yes | many — but the PYNQ-Z2 shares 8 RPi pins with PMOD A | clashes with your video |
| Zynq PS (USB-UART, Ethernet) | no — belongs to the ARM processor | — | needs PS + AXI, which this design avoids |
| Arduino connector, sockets AR0–AR13 | yes — every AR socket is a PL I/O pin | 14 digital + GND | chosen for the Arduino |
| SPI header (2×3) | yes — AR_SS, AR_SCK, AR_MOSI, AR_MISO are PL pins | 4 | used by the on-board test host (loopback) |
The labels on the board are AR0 … AR13, not D0 … D13
An Arduino Uno prints its digital pins as plain numbers (13, 12, ~11, ~10 …) and Arduino code calls them D13, D11, D10. The PYNQ-Z2 names the same positions AR0 … AR13 — in its reference manual (tables 16–19), its schematic and its constraints file. The pin next to SDA, where an Uno has AREF, is called A on the PYNQ-Z2 and is also a PL pin (Y13). In this guide: Uno pin 13 on one side, PYNQ AR13 on the other.
| PYNQ-Z2 label | Connector · pin | FPGA pin | Used for | Uno position |
|---|---|---|---|---|
| AR8 · AR9 | J3 · 1, 2 | V17 · V18 | — | 8 · ~9 |
| AR10 | J3 · 3 | T16 | spi_cs_n (in) | ~10 (SS) |
| AR11 | J3 · 4 | R17 | spi_mosi (in) | ~11 (MOSI) |
| AR12 | J3 · 5 | P18 | gpu_ready (out) | 12 (MISO) |
| AR13 | J3 · 6 | N17 | spi_sck (in) | 13 (SCK) |
| GND | J3 · 7 | — | ground | GND |
| A · AR_SDA · AR_SCL | J3 · 8, 9, 10 | Y13 · P16 · P15 | — | AREF · SDA · SCL |
| AR0 … AR7 | J4 · 1 … 8 | T14 U12 U13 V13 V15 T15 R16 U17 | — | 0 … 7 |
| AR_SS · AR_SCK · AR_MOSI | SPI header · 5, 3, 4 | F16 · H15 · T12 | test host out (loopback) | ICSP header |
Is the Arduino connector really usable from the fabric?
Yes. Every AR socket is wired (through a 200 Ω protection resistor) straight to a Zynq programmable-logic pin on a 3.3 V bank. Your old design already proves it: your joystick shield's buttons were joy_btn_n_0[0..6] on U13 V13 V15 T15 R16 U17 V17 — exactly AR2 … AR8. A socket becomes an ordinary top-level port the moment you write one XDC line for it. (Avoid A0–A5: they double as XADC analog inputs.)
| PYNQ-Z2 header limits (reference manual, table 15) | Min | Max |
|---|---|---|
| Board powered — recommended | −0.2 V | 3.4 V |
| Board powered — absolute | −0.4 V | 3.75 V |
| Board unpowered — absolute | −0.4 V | 0.55 V |
Two consequences: a 5 V Arduino needs the dividers (Step 29), and nothing may drive the header while the PYNQ-Z2 is off — power the PYNQ first. TUL states it plainly: the PYNQ-Z2 is not compatible with shields that output 5 V.
The Arduino connector pins used
Your video adapter (unchanged)
Complete FPGA pin map
| fpga_top port | FPGA pin | Board connector · label | Connects to |
|---|---|---|---|
| sysclk | H16 | on-board 125 MHz | — |
| reset | D19 | BTN0 | — |
| btn[2:0] | L19 L20 D20 | BTN3 BTN2 BTN1 | start test 1/2/3 (or 4/5/6) |
| sw[1:0] | M19 M20 | SW1 SW0 | test bank · SPI source |
| spi_cs_n | T16 | J3 · AR10 | Uno pin ~10 (via divider) |
| spi_mosi | R17 | J3 · AR11 | Uno pin ~11 (via divider) |
| gpu_ready | P18 | J3 · AR12 | Uno pin 8 (direct) |
| spi_sck | N17 | J3 · AR13 | Uno pin 13 (via divider) |
| — | — | J3 · GND | Uno GND |
| test_cs_n / test_sck / test_mosi | F16 / H15 / T12 | SPI header · AR_SS / AR_SCK / AR_MOSI | loopback wires to AR10 / AR13 / AR11 |
| vga_hs / vga_vs | Y19 / U19 | PMOD A pin 2 / pin 8 | adapter HSYNC / VSYNC |
| vga_b[3:0] | W18 Y16 W19 Y17 | PMOD A pins 9 3 10 4 | adapter blue DAC |
| vga_r[3:0] | V12 T11 W13 T10 | PMOD B pins 9 3 10 4 | adapter red DAC |
| vga_g[3:0] | V16 W14 W16 Y14 | PMOD B pins 7 1 8 2 | adapter green DAC |
| led[3:0] | M14 N16 P14 R14 | LD3 … LD0 | — |
Every pin in pynq_gpu.xdc was cross-checked by script against the PYNQ-Z2 pin list (reference manual + base-overlay constraints): 32 of 32 match, including the AR / JA / JB / BTN / SW labels written in the XDC comments. Re-run it yourself: Step 27.
Connection reference: every connector, pin by pin
One place with every physical connection of the FPGA setup. The pin tables below are generated from the final pynq_gpu.xdc when this guide is built, and check_pins.py checks that file against the PYNQ-Z2 reference manual — so the tables, the constraints and the board cannot disagree.
0 · Board set-up (before any signal wire)
| Part | Setting | Why |
|---|---|---|
| JP1 boot-mode jumper | JTAG | the PL is loaded from Vivado; with SD the PYNQ image would load its own bitstream |
| J9 power jumper (next to SW1) | USB | power from the micro-USB port (REG = from the DC jack, 7–15 V, 12 V recommended) |
| micro-USB (PROG / UART) | to the PC | power + JTAG programming |
| Arduino shield (joystick) | removed | its buttons sit on AR2–AR8 and it may drive pins |
| SW0 / SW1 | both down (OFF) | start in "Arduino" mode with test bank 1–3; change when a step says so |
1 · Which wires exist in which mode
| Mode | SW0 | Wires on the PYNQ-Z2 | Who sends SPI | Step |
|---|---|---|---|---|
| Step 1 · VGA test | — | only the video adapter on PMOD A + B | nobody (separate top level vga_test_top, no SPI) | Step 22 |
| A · on-board tests (steps 2–4) | up (ON) | only the video adapter on PMOD A + B | built-in test host, inside the FPGA | Step 23 |
| B · loopback | down (OFF) | adapter + 3 jumpers SPI header → J3 (AR_SCK→AR13, AR_MOSI→AR11, AR_SS→AR10) | test host, through the real pins | Step 26 |
| C · Arduino | down (OFF) | adapter + 5 wires to J3 (AR10, AR11, AR12, AR13, GND) via the breadboard | the Uno | Step 29 |
In mode B the test host drives AR10/AR11/AR13 through the loopback wires. If the Arduino is also connected, two outputs fight on the same wire. Remove the loopback wires before wiring the Arduino.
2 · PMOD A (JA) — your video adapter: sync + blue
| Pin | Manual name | FPGA pin | fpga_top port | Adapter function | What a meter / scope sees |
|---|---|---|---|---|---|
| 1 | JA1_P | Y18 | — | unused (pull-down by default) | 0 V |
| 2 | JA1_N | Y19 | vga_hs | HSYNC | idle 3.3 V, 96-clock low pulse every line (31.25 kHz); DC meter ≈ 2.9 V |
| 3 | JA2_P | Y16 | vga_b[2] | blue bit 2 | 0 V on black; toggles with the picture |
| 4 | JA2_N | Y17 | vga_b[0] | blue bit 0 (LSB) | 0 V on black; toggles with the picture |
| 5 | GND | — | — | adapter ground (both rows) | 0 V |
| 6 | 3V3 | — | — | not needed by a resistor DAC | 3.3 V |
| 7 | JA3_P | U18 | — | unused (pull-down by default) | 0 V |
| 8 | JA3_N | U19 | vga_vs | VSYNC | idle 3.3 V, 2-line low pulse every frame (59.5 Hz); DC meter ≈ 3.3 V |
| 9 | JA4_P | W18 | vga_b[3] | blue bit 3 (MSB) | 0 V on black; toggles with the picture |
| 10 | JA4_N | W19 | vga_b[1] | blue bit 1 | 0 V on black; toggles with the picture |
| 11 | GND | — | — | adapter ground (both rows) | 0 V |
| 12 | 3V3 | — | — | not needed by a resistor DAC | 3.3 V |
3 · PMOD B (JB) — your video adapter: red + green
| Pin | Manual name | FPGA pin | fpga_top port | Adapter function | What a meter / scope sees |
|---|---|---|---|---|---|
| 1 | JB1_P | W14 | vga_g[2] | green bit 2 | 0 V on black; toggles with the picture |
| 2 | JB1_N | Y14 | vga_g[0] | green bit 0 (LSB) | 0 V on black; toggles with the picture |
| 3 | JB2_P | T11 | vga_r[2] | red bit 2 (weight 4) | 0 V on black; toggles with the picture |
| 4 | JB2_N | T10 | vga_r[0] | red bit 0 (LSB, weight 1) | 0 V on black; toggles with the picture |
| 5 | GND | — | — | adapter ground (both rows) | 0 V |
| 6 | 3V3 | — | — | not needed by a resistor DAC | 3.3 V |
| 7 | JB3_P | V16 | vga_g[3] | green bit 3 (MSB) | 0 V on black; toggles with the picture |
| 8 | JB3_N | W16 | vga_g[1] | green bit 1 | 0 V on black; toggles with the picture |
| 9 | JB4_P | V12 | vga_r[3] | red bit 3 (MSB, weight 8) | 0 V on black; toggles with the picture |
| 10 | JB4_N | W13 | vga_r[1] | red bit 1 (weight 2) | 0 V on black; toggles with the picture |
| 11 | GND | — | — | adapter ground (both rows) | 0 V |
| 12 | 3V3 | — | — | not needed by a resistor DAC | 3.3 V |
Bit order matters: if bit 3 and bit 0 of one colour are swapped, the 16-step DAC ramps of bring-up step 1 jump back instead of getting brighter evenly; if two colours are swapped (e.g. red ↔ blue), the colour bars come out in the wrong order. Step 1 (Step 22) is made for exactly this check.
4 · Arduino connector J3 — the SPI input
| Pin | Label | FPGA pin | fpga_top port | Dir | Connects to | Idle level |
|---|---|---|---|---|---|---|
| 1 | AR8 | V17 | — | — | leave empty | — |
| 2 | AR9 | V18 | — | — | leave empty | — |
| 3 | AR10 | T16 | spi_cs_n | in | Uno ~10 via divider · or loopback wire from AR_SS | 3.0 V idle (Uno) · 3.3 V (pull-up, nothing plugged) |
| 4 | AR11 | R17 | spi_mosi | in | Uno ~11 via divider · or loopback wire from AR_MOSI | 0 V idle |
| 5 | AR12 | P18 | gpu_ready | out | Uno pin 8, direct wire | 3.3 V when ready |
| 6 | AR13 | N17 | spi_sck | in | Uno 13 via divider · or loopback wire from AR_SCK | 0 V idle (mode 0) |
| 7 | GND | — | — | — | breadboard − rail (Uno GND) | 0 V |
| 8 | A | Y13 | — | — | leave empty | — |
| 9 | AR_SDA | P16 | — | — | leave empty | — |
| 10 | AR_SCL | P15 | — | — | leave empty | — |
5 · SPI header (2×3) — test host output, loopback only
| Pin | Label | FPGA pin | fpga_top port | Dir | Connects to |
|---|---|---|---|---|---|
| 1 | AR_MISO | W15 | — | — | leave empty |
| 2 | 3V3 | — | — | power | never connect (3.3 V supply) |
| 3 | AR_SCK | H15 | test_sck | out | wire → AR13 (loopback only) |
| 4 | AR_MOSI | T12 | test_mosi | out | wire → AR11 (loopback only) |
| 5 | AR_SS | F16 | test_cs_n | out | wire → AR10 (loopback only) |
| 6 | GND | — | — | — | not needed (same board) |
6 · Connectors that stay empty
| Connector | Pins | Why empty |
|---|---|---|
| Arduino J4 | AR0 … AR7 (T14 U12 U13 V13 V15 T15 R16 U17) | not used; no XDC lines, so the pins are unconnected inputs |
| Arduino J7 (power) | VU_CK, GND, 5V5, 3V3, AR_RST | never connect the Uno's 5 V or 3.3 V here — the boards share only GND |
| Arduino J1 (analog) | A0 … A5 | XADC inputs |
| Raspberry Pi header | — | shares 8 pins with PMOD A (your video) |
7 · Buttons, switches and LEDs
| Part | FPGA pin | Port | Function |
|---|---|---|---|
| BTN0 | D19 | reset | hold = everything in reset (the screen goes black, then the power-up clear runs) |
| BTN1 / BTN2 / BTN3 | D20 / L20 / L19 | btn[0..2] | run test 1 / 2 / 3 (with SW1 up: 4 / 5 / 6) · step 1: checkerboard / colour bars / DAC ramps |
| SW0 | M20 | sw[0] | up: GPU listens to the test host, test 1 runs by itself after reset · down: Arduino connector · step 1: invert |
| SW1 | M19 | sw[1] | test bank: down = the step’s new tests 1–3, up = tests 4–6 (the previous step’s) · step 1: grid |
| LD0 | R14 | led[0] | gpu_ready — on when the GPU accepts a command |
| LD1 | P14 | led[1] | clock locked — must always be on |
| LD2 | N16 | led[2] | toggles with every accepted command (flickers while drawing) |
| LD3 | M14 | led[3] | heartbeat ≈ 0.75 Hz; steady on while a test runs |
8 · The Uno side
| Uno pin (printed) | Arduino name | In the sketch | Mode | Goes to |
|---|---|---|---|---|
| 13 | D13 / SCK | hardware SPI (SPI.h) | output | breadboard col 2 → 2.2 kΩ → col 6 → PYNQ AR13 |
| ~11 | D11 / MOSI | hardware SPI | output | col 9 → 2.2 kΩ → col 13 → PYNQ AR11 |
| ~10 | D10 / SS | PIN_CS = 10 | output | col 16 → 2.2 kΩ → col 20 → PYNQ AR10 |
| 12 | D12 / MISO | (taken by SPI.h) | input | nothing — keep free |
| 8 | D8 | PIN_READY = 8 | input | PYNQ AR12, direct wire |
| GND | GND | — | — | breadboard − rail |
| 5V, 3.3V, VIN | — | — | — | nothing |
9 · Check before you power anything
| # | Check (boards unpowered, meter in continuity / Ω) | Expected |
|---|---|---|
| 1 | Uno GND ↔ PYNQ J3 pin 7 (GND) | beep |
| 2 | Uno pin 13 ↔ PYNQ AR13 | ≈ 2.2 kΩ (the series resistor) |
| 3 | Uno ~11 ↔ AR11 and Uno ~10 ↔ AR10 | ≈ 2.2 kΩ each |
| 4 | AR13, AR11, AR10 ↔ GND | ≈ 3.3 kΩ each (or a little less) |
| 5 | Uno pin 8 ↔ AR12 | beep (direct wire) |
| 6 | AR12 ↔ any other AR pin, any AR pin ↔ 5V / 3V3 | open — no beep |
| 7 | nothing on J7, J4, J1, the RPi header or the SPI header | look |
| # | Check (PYNQ powered and programmed, Arduino running the sketch, meter in DC V) | Expected |
|---|---|---|
| 8 | AR10 (CS) while idle | ≈ 3.0 V |
| 9 | AR13 (SCK), AR11 (MOSI) while idle | ≈ 0 V |
| 10 | AR12 (READY) | ≈ 3.3 V (LD0 on) |
| 11 | PMOD A pin 2 (HSYNC) · pin 8 (VSYNC) | ≈ 2.9 V · ≈ 3.3 V (pulses); 31.25 kHz · 59.5 Hz in Hz mode |
With the boards connected the meter also sees small paths through the unpowered chips, so readings a little below 2.2 / 3.3 kΩ are normal. What matters: each Uno pin reaches its own AR socket at about 2 kΩ, and the wrong sockets read open or much higher.
Vivado: create the project (empty — the bring-up fills it)
The plan
You do not drop the whole GPU into Vivado and hope. You bring it up the way you would if you were writing it now: the VGA controller first, tested on your adapter; then the command path — SPI receiver, framebuffer and the simplest engine, RECT — tested over real SPI; then LINE; then CIRCLE. Every step adds a few files, has its own tests made for exactly what is new, and ends with pictures on your monitor that you compare with the expected ones. From step 3 on, the previous step’s tests still run (SW1 up), so you also see that the new engine did not break the old ones.
| Step | What you add (in this order) | Top · constraints | Test ROM | On the monitor |
|---|---|---|---|---|
| 1 · VGA controller | rtl/vga_controller.v + bringup/step1_vga/vga_pattern.v, vga_test_top.v | vga_test_top · vga_test.xdc | — | checkerboard, colour bars, DAC ramps, grid |
| 2 · SPI + framebuffer + RECT | rtl/spi_cmd_rx.v, frame_buffer.v, rect_filler.v, bringup/step2_rect/gpu_core.v + fpga/fpga_top.v, spi_test_host.v | fpga_top · pynq_gpu.xdc | bringup/step2_rect/selftest.mem | “HI”, colour bars, blocks off the edges |
| 3 · + LINE | rtl/line_renderer.v; the core becomes bringup/step3_line/gpu_core.v | same | bringup/step3_line/selftest.mem | starburst, string art, a house |
| 4 · + CIRCLE | rtl/circle_renderer.v; the core becomes rtl/gpu_core.v (the final one) | same | fpga/selftest.mem | target, snowman, edge cases |
Steps 2–4 are driven by a small SPI master inside the FPGA (spi_test_host.v, written in step 2) that sends real 80-bit SPI frames from a ROM, exactly like the Arduino will. Only after step 4 does the Arduino get wired.
Do
- Copy the sources to a Windows folder (Vivado is happier with C: paths than with \\wsl$):terminalBashWSL
mkdir -p /mnt/c/fpga/raster_gpu cd ~/asic_projects/raster_gpu cp -r rtl fpga bringup /mnt/c/fpga/raster_gpu/ - Vivado → Quick Start›Create Project → Next. Name
raster_gpu_pynq, locationC:\fpga, tick Create project subdirectory → Next. - Project type RTL Project, tick Do not specify sources at this time → Next.
- Default Part: type
xc7z020clg400-1in Search, select the row → Next → Finish. No board file is needed.
When you add files, untick Copy sources into project. The project then points at C:\fpga\raster_gpu, so there is exactly one copy of every file: when you change a file there (or regenerate a test ROM), the next build uses it. For .mem files set the file-type filter to All Files; Vivado lists them under Memory Initialization Files and hands them to $readmemh.
Vivado: Clocking Wizard (125 → 25 MHz)
Every top level in this project — the step-1 test design and fpga_top — gets its 25 MHz from the same IP, so it is made once, before step 1.
Do
- Flow Navigator›PROJECT MANAGER›IP Catalog → search Clocking Wizard → double-click.
- Top of the dialog: Component Name =
clk_wiz_0(both top levels instantiate it by this name). - Tab Clocking Options: Primitive MMCM. Input Clock Information → Primary: Input Frequency 125.000 MHz, Source Single ended clock capable pin.
- Tab Output Clocks:
clk_out1Requested 25.000 MHz (Actual shows 25.000). Only clk_out1 ticked. - Same tab, bottom: keep reset and locked ticked, Reset Type Active High.
- Tabs Port Renaming / MMCM Settings: leave defaults. Summary shows VCO 1000 MHz, divide 40.
- OK → Generate (out-of-context is fine). Wait for
clk_wiz_0_synth_1in the Design Runs tab.
Expected
Sources › IP Sources lists clk_wiz_0. Nothing uses it yet; the step-1 top level does.
An MMCM from 125 MHz cannot hit 25.175 exactly. 25.000 MHz gives 59.5 Hz, accepted by every monitor for 640×480 (your old design ran at 25 MHz too). The ASIC uses a real 25.175 MHz oscillator.
Vivado: the build → program loop (you repeat it in every step)
Do
- Flow Navigator›PROGRAM AND DEBUG›Generate Bitstream → Yes (runs synthesis + implementation) → OK. A few minutes.
- The first time, choose View Reports and check the numbers below. Later: just continue.
- Set the PYNQ-Z2 boot jumper JP1 to JTAG (so the PYNQ Linux image does not reload the PL), connect micro-USB, power on.
- Open Hardware Manager›Open Target›Auto Connect → Program Device → the
.bitis pre-filled → Program. The Hardware Manager stays connected; next time only Program Device. - Your adapter on PMOD A + B, the monitor connected.
Expected
| Report | Step 1 | Steps 2–4 | If not |
|---|---|---|---|
| Timing Summary → WNS | positive, 0 failing endpoints | positive, 0 failing endpoints | clock constraint missing → the create_clock line of the XDC |
| Utilization → Block RAM | 0 | ~34–38 tiles of 140 (the double framebuffer) | ~64 → DEPTH became a power of two (do not edit frame_buffer.v) |
| Utilization → LUT / FF | a few hundred | step 4: ≈ 1,000–1,300 LUT, ≈ 550 FF, 0–2 DSP (of 53,200 / 106,400 / 220) | — |
| Methodology | no unconstrained clocks | no unconstrained clocks | — |
A multimeter in frequency mode or a scope on the sync pins, in every step: HSYNC (PMOD A pin 2) ≈ 31.25 kHz, VSYNC (pin 8) ≈ 59.5 Hz, both idle high with short low pulses (3.84 µs and 64 µs).
Bring-up step 1: the VGA controller, on your adapter
Why this first
vga_controller.v is the first module of the GPU you write, and the only one that touches the part you built by hand: the PMOD adapter, its resistor DAC, the cable and the monitor. Test them together before anything depends on them. There is no framebuffer yet, so vga_pattern.v stands where it will be: the controller asks for the colour of each pixel by address, the pattern answers one clock later — exactly like a framebuffer read.
| File | Role |
|---|---|
rtl/vga_controller.v | the real GPU module (Step 8), here with FB_WIDTH = 1024, SCALE_SHIFT = 0, 12-bit pixels: address = y · 1024 + x, so all 640 × 480 pixels are addressed |
bringup/step1_vga/vga_pattern.v | test pictures from x = address[9:0], y = address[18:10]; registered output |
bringup/step1_vga/vga_test_top.v | Clocking Wizard, reset, buttons/switches, LEDs; RGB444 straight to the adapter (all 4096 colours, every DAC bit) |
bringup/step1_vga/vga_test.xdc | the same pins as pynq_gpu.xdc of the later steps, only for these ports (check_pins.py checks that) |
▸ Show bringup/step1_vga/vga_pattern.v · 81 lines
`timescale 1ns / 1ps
// =============================================================
// vga_pattern : test pictures for bring-up step 1 (vga_controller + adapter only)
//
// Sits where the framebuffer normally is: vga_controller asks for
// "address" fb_addr and gets a colour one clock later. With
// FB_WIDTH = 1024 and SCALE_SHIFT = 0 the address is simply
// fb_addr = y * 1024 + x -> x = fb_addr[9:0], y = fb_addr[18:10]
// so every one of the 640 x 480 screen pixels can be addressed.
//
// sel 0 checkerboard, 40 x 40 squares, 1-pixel red frame on the
// outermost pixels (x = 0, 639 / y = 0, 479)
// sel 1 8 colour bars + a 16-step grey ramp underneath
// sel 2 DAC ramps: red, green, blue, grey, 16 steps of 40 pixels
// (step n = value n on the 4-bit DAC: every bit is visible)
// sel 3 1-pixel white grid every 40 pixels + centre cross
// invert inverts every colour (each pixel and each DAC bit both ways)
//
// Colour out is RGB444 = {R[3:0], G[3:0], B[3:0]}, straight to the adapter.
// =============================================================
module vga_pattern (
input wire clk,
input wire [1:0] sel,
input wire invert, // SW0: every colour inverted
input wire [18:0] fb_addr,
output reg [11:0] rgb
);
wire [9:0] x = fb_addr[9:0]; // 0 .. 639
wire [8:0] y = fb_addr[18:10]; // 0 .. 479
// 40-pixel cells: column cx 0..15, row cy 0..11, position inside 0..39.
// v / 40 without a divider: (v * 205) >> 13 is exact for every v < 1024.
/* verilator lint_off UNUSEDSIGNAL */ // only bits 16:13 are the quotient
wire [17:0] xm = {8'd0, x} * 18'd205;
wire [17:0] ym = {9'd0, y} * 18'd205;
/* verilator lint_on UNUSEDSIGNAL */
wire [3:0] cx = xm[16:13];
wire [3:0] cy = ym[16:13];
wire [9:0] ix = x - ({1'b0, cx, 5'd0} + {3'd0, cx, 3'd0}); // x - 40*cx
wire [8:0] iy = y - ({cy, 5'd0} + {2'd0, cy, 3'd0}); // y - 40*cy
wire border = (x == 10'd0) || (x == 10'd639) || (y == 9'd0) || (y == 9'd479);
// 8 colour bars, 80 pixels (2 cells) wide:
// white yellow cyan green magenta red blue black
reg [11:0] bar;
always @(*) begin
case (cx[3:1])
3'd0: bar = 12'hFFF;
3'd1: bar = 12'hFF0;
3'd2: bar = 12'h0FF;
3'd3: bar = 12'h0F0;
3'd4: bar = 12'hF0F;
3'd5: bar = 12'hF00;
3'd6: bar = 12'h00F;
default: bar = 12'h000;
endcase
end
reg [11:0] c;
always @(*) begin
case (sel)
2'd0: c = border ? 12'hF00 : ((cx[0] ^ cy[0]) ? 12'h000 : 12'hFFF);
2'd1: c = (y < 9'd320) ? bar : {3{cx}};
2'd2: if (y < 9'd120) c = {cx, 4'h0, 4'h0}; // red ramp
else if (y < 9'd240) c = {4'h0, cx, 4'h0}; // green ramp
else if (y < 9'd360) c = {4'h0, 4'h0, cx}; // blue ramp
else c = {cx, cx, cx}; // grey ramp
default: c = (ix == 10'd0 || iy == 9'd0 || x == 10'd639 || y == 9'd479 ||
x == 10'd320 || y == 9'd240) ? 12'hFFF : 12'h000;
endcase
end
// registered, like a framebuffer read: colour arrives one clock later
always @(posedge clk)
rgb <= invert ? ~c : c;
endmodule▸ Show bringup/step1_vga/vga_test_top.v · 90 lines
`timescale 1ns / 1ps
// =============================================================
// vga_test_top : BRING-UP STEP 1 - test vga_controller.v and your video adapter
//
// No SPI, no framebuffer, no GPU: the real vga_controller.v scans the
// screen and vga_pattern.v answers every pixel with a test colour.
// The checkerboard appears as soon as the bitstream is loaded.
//
// BTN1 checkerboard (default) BTN2 colour bars + grey ramp
// BTN3 DAC ramps (each colour, 16 levels)
// SW1 up: 1-pixel grid + centre cross (overrides the buttons)
// SW0 up: all colours inverted (every pixel and DAC bit seen both ways)
// BTN0 reset LD1 clock locked LD3 heartbeat LD0/LD2 pattern number
//
// Same pins as fpga_top (pynq_gpu.xdc), constraints in vga_test.xdc.
// =============================================================
module vga_test_top (
input wire sysclk, // 125 MHz
input wire reset, // BTN0
input wire [2:0] btn, // BTN1 .. BTN3
input wire [1:0] sw, // SW0 = invert colours, SW1 = grid
output wire vga_hs,
output wire vga_vs,
output wire [3:0] vga_r,
output wire [3:0] vga_g,
output wire [3:0] vga_b,
output wire [3:0] led
);
wire clk_25m, clk_locked;
clk_wiz_0 u_clk (
.clk_in1(sysclk), .reset(1'b0),
.clk_out1(clk_25m), .locked(clk_locked)
);
// reset: asynchronous assert, synchronous release
wire rst_n = clk_locked & ~reset;
(* ASYNC_REG = "TRUE" *) reg [1:0] rst_s;
always @(posedge clk_25m or negedge rst_n)
if (!rst_n) rst_s <= 2'b11;
else rst_s <= {rst_s[0], 1'b0};
wire top_reset = rst_s[1];
// buttons/switches: 2-flop synchronizer (no debounce needed:
// pressing "checkerboard" twice still shows the checkerboard)
(* ASYNC_REG = "TRUE" *) reg [4:0] in_m, in_s;
always @(posedge clk_25m) begin
in_m <= {sw, btn};
in_s <= in_m;
end
reg [1:0] pattern;
always @(posedge clk_25m) begin
if (top_reset) pattern <= 2'd0; // checkerboard after reset
else if (in_s[0]) pattern <= 2'd0;
else if (in_s[1]) pattern <= 2'd1;
else if (in_s[2]) pattern <= 2'd2;
end
wire [1:0] sel = in_s[4] ? 2'd3 : pattern; // SW1: grid
// the real VGA controller; the "framebuffer" is the pattern generator
wire [18:0] addr;
wire [11:0] rgb, pix;
/* verilator lint_off PINCONNECTEMPTY */
vga_controller #(
.FB_WIDTH(1024), .SCALE_SHIFT(0), .PIX_BITS(12), .ADDR_BITS(19)
) u_vga (
.clk(clk_25m), .reset(top_reset), .frame_valid(1'b1),
.fb_addr(addr), .fb_data(rgb),
.vblank_start(), // not needed here
.hsync(vga_hs), .vsync(vga_vs), .pixel(pix)
);
/* verilator lint_on PINCONNECTEMPTY */
vga_pattern u_pat (.clk(clk_25m), .sel(sel), .invert(in_s[3]), .fb_addr(addr), .rgb(rgb));
assign vga_r = pix[11:8];
assign vga_g = pix[7:4];
assign vga_b = pix[3:0];
reg [24:0] heartbeat = 25'd0;
always @(posedge clk_25m) heartbeat <= heartbeat + 1'b1;
assign led = {heartbeat[24], sel[1], clk_locked, sel[0]};
endmoduleDo
- Add Sources → design sources →
rtl\vga_controller.v,bringup\step1_vga\vga_pattern.v,bringup\step1_vga\vga_test_top.v(Copy sources: unticked). - Add Sources → constraints →
bringup\step1_vga\vga_test.xdc. - Sources:
vga_test_topis shown in bold as the top, withu_clk : clk_wiz_0andu_vga : vga_controllerbelow it. - Build and program (Step 21). Nothing else plugged in.
The tests
The checkerboard appears straight away. Then go through the buttons and switches:
| Control | Picture | What it proves |
|---|---|---|
| (after programming) · BTN1 | checkerboard, 40 × 40-pixel squares, 1-pixel red frame on the outermost pixels | HSYNC/VSYNC timing and polarity, 640 × 480 geometry: 16 × 12 whole squares and the red frame visible on all four edges (an edge missing → the monitor’s auto-adjust) |
| BTN2 | 8 colour bars + 16-step grey ramp | each colour reaches the right DAC: white yellow cyan green magenta red blue black, left to right |
| BTN3 | DAC ramps: red, green, blue, grey, 16 steps each | every one of the 12 DAC bits: each ramp gets brighter in 16 even steps; a swapped or open bit shows as a jump back or two equal steps |
| SW1 up | 1-pixel grid every 40 pixels + centre cross | sharpness: thin, even lines; the cross exactly in the centre |
| SW0 up | every picture inverted | each pixel and DAC bit both ways (a stuck bit shows in one of the two) |
| BTN0 | back to the checkerboard (reset) | reset path |
| LED | Meaning in step 1 |
|---|---|
| LD1 | clock locked — on |
| LD3 | heartbeat ≈ 0.75 Hz |
| LD0, LD2 | picture number in binary (00 checkerboard … 11 grid) |
If a picture is wrong
| Symptom | Cause | Fix |
|---|---|---|
| Monitor: no signal | HSYNC/VSYNC not arriving | LD1 on? PMOD A the right way round (pin 1 to pin 1)? HSYNC = JA-2, VSYNC = JA-8 (Step 18) |
| Picture rolls or tears | sync wiring on the adapter | HSYNC and VSYNC swapped, or not on VGA pins 13 / 14 |
| Bars in the wrong order | two colour channels swapped | e.g. red and blue: PMOD B and the blue half of PMOD A, or the adapter’s DE-15 pins 1 / 3 |
| A ramp jumps back or has equal steps | bits of one channel swapped or open | bit table in Step 18; the step tells you the bit (step 8 wrong = bit 3, step 1 = bit 0) |
| Everything too dark / too bright | DAC resistor values | your adapter’s resistors, not the RTL |
sim/tb_vga_test.v runs vga_test_top, captures all five pictures from the VGA pins and checks HSYNC is exactly 96 clocks wide; scripts/check_vga_test.py compares all 5 × 307,200 pixels with an independent model: ALL 5 PICTURES MATCH THE MODEL. The images above are those captures.
Done when all five pictures look like the ones above. The controller and the adapter are now trusted — from here on, a wrong picture is never the adapter’s fault.
Bring-up step 2: SPI receiver + framebuffer + RECT, over real SPI
Why these together
The next thing a GPU needs is a way in for commands and a memory to draw into. The smallest version that can show something: the SPI receiver, the framebuffer with double buffering, and one engine — RECT, the simplest, because CLEAR is a full-screen rectangle anyway. LINE and CIRCLE do not exist yet.
To send commands you need an SPI master. The Arduino would add a second board, dividers and wires as new sources of error, so the FPGA gets its own: spi_test_host.v sends 80-bit frames from a ROM with exactly the Arduino’s protocol (wait for READY, CS low, 80 bits, CS high). fpga_top.v is the board shell around the GPU — clock, reset, buttons, LEDs, the test host. Both are written once, in this step, and never change again.
What you add
| File | What it is |
|---|---|
rtl/spi_cmd_rx.v | SPI receiver with synchronizers, 80-bit framing (Step 7) |
rtl/frame_buffer.v | 1 write + 1 read port, block RAM (Step 9) |
rtl/rect_filler.v | the rectangle engine (Step 11) |
bringup/step2_rect/gpu_core.v | the first core: decode, power-up clear, RECT, SWAP + double buffering, VGA |
fpga/fpga_top.v, fpga/spi_test_host.v | board shell + on-board SPI master (below) |
bringup/step2_rect/selftest.mem | the step-2 tests (made by scripts/gen_selftest.py) |
fpga/pynq_gpu.xdc | constraints of the real design (SPI pins, buttons, switches, LEDs, adapter) |
The step-2 core
It is rtl/gpu_core.v as it looks with a single engine, and two things are simpler than in the final core:
- No clipping in the pixel writer. RECT is clipped to the screen before the engine starts, so every pixel it plots is on screen and is written as it is:
draw_we = rect_plot. - No engine selection. One engine, so no multiplexer. LINE (0x02) and CIRCLE (0x05) frames are still received and acknowledged with READY, they just do nothing — a host never hangs on an unknown command.
▸ Show bringup/step2_rect/gpu_core.v · 311 lines
`timescale 1ns / 1ps
// =============================================================
// gpu_core : SPI rasterizer GPU - BRING-UP STEP 2 (rect only)
// SPI receiver + framebuffer + VGA scan-out + CLEAR/RECT/SWAP
//
// The first core you build: one drawing engine (rect_filler), so the
// command path, the framebuffer, double buffering and the VGA read side
// can be tested with nothing else in the way. LINE (0x02) and CIRCLE
// (0x05) frames are received, acknowledged and ignored.
// Step 3 = bringup/step3_line/gpu_core.v, step 4 = rtl/gpu_core.v.
//
// Parameters as in the final core (the ASIC builds use only the final
// rtl/gpu_core.v):
//
// parameter FPGA (PYNQ-Z2) ASIC v1 (SKY130) ASIC v2 (SRAM)
// FB_W x FB_H 320 x 240 40 x 30 80 x 60
// SCALE_SHIFT 1 (2 x 2) 4 (16 x 16) 3 (8 x 8)
// PIX_BITS 8 (RGB332) 3 (RGB111) 8
// DOUBLE_BUF 1 0 0
//
// Host protocol: one 10-byte SPI frame per command (mode 0, MSB
// first, CS low for the whole frame). Wait for gpu_ready = 1
// before every frame.
//
// byte 0 opcode
// byte 1..2 A (int16, big endian)
// byte 3..4 B
// byte 5..6 C
// byte 7..8 D
// byte 9 colour, RGB332 (RRRGGGBB)
//
// 0x01 CLEAR - fill the whole back buffer
// 0x02 LINE (step 3) accepted and ignored here
// 0x03 RECT A=x B=y C=w D=h filled
// 0x04 SWAP - show the back buffer at the
// next vblank (single buffer:
// just wait for vblank)
// 0x05 CIRCLE (step 4) accepted and ignored here
//
// Coordinates use the low COORD_BITS bits as a signed number
// (-2048 .. 2047), w/h the low COORD_BITS bits unsigned.
// A rectangle that is partly off screen is clipped.
// =============================================================
module gpu_core #(
parameter FB_W = 320,
parameter FB_H = 240,
parameter SCALE_SHIFT = 1,
parameter PIX_BITS = 8,
parameter DOUBLE_BUF = 1,
parameter COORD_BITS = 12
)(
input wire clk, // 25 MHz pixel + system clock
input wire rst_n, // asynchronous, active low
input wire spi_cs_n, // SPI from the host MCU
input wire spi_sck,
input wire spi_mosi,
output wire gpu_ready,
output wire vga_hs,
output wire vga_vs,
output wire [PIX_BITS-1:0] vga_pix,
output reg dbg_cmd_toggle // LED on the FPGA, unused on the ASIC
);
// ---------------------------------------------------------
// Sizes
// ---------------------------------------------------------
localparam FB_PIXELS = FB_W * FB_H;
localparam DEPTH = DOUBLE_BUF ? 2 * FB_PIXELS : FB_PIXELS;
localparam ADDR_BITS = $clog2(DEPTH);
localparam XW = $clog2(FB_W); // bits of an on-screen x
localparam YW = $clog2(FB_H);
localparam CB = COORD_BITS;
localparam [7:0] OP_CLEAR = 8'h01;
localparam [7:0] OP_RECT = 8'h03;
localparam [7:0] OP_SWAP = 8'h04;
// ---------------------------------------------------------
// Reset synchronizer: assert at once, release on a clock edge
// ---------------------------------------------------------
(* ASYNC_REG = "TRUE" *) reg [1:0] reset_s;
always @(posedge clk or negedge rst_n) begin
if (!rst_n)
reset_s <= 2'b11;
else
reset_s <= {reset_s[0], 1'b0};
end
wire reset = reset_s[1];
// ---------------------------------------------------------
// Power-up clear: write 0 to every word once after reset
// (silicon has no initial values)
// ---------------------------------------------------------
localparam LAST_I = DEPTH - 1;
localparam [ADDR_BITS-1:0] LAST_ADDR = LAST_I[ADDR_BITS-1:0];
reg init_done;
reg [ADDR_BITS-1:0] init_addr;
always @(posedge clk) begin
if (reset) begin
init_done <= 1'b0;
init_addr <= 0;
end
else if (!init_done) begin
if (init_addr == LAST_ADDR)
init_done <= 1'b1;
else
init_addr <= init_addr + 1'b1;
end
end
// ---------------------------------------------------------
// SPI receiver
// ---------------------------------------------------------
wire bus_idle;
wire cmd_valid;
wire [79:0] cmd_word;
spi_cmd_rx #(.CMD_BITS(80)) u_spi (
.clk(clk), .reset(reset),
.spi_cs_n(spi_cs_n), .spi_sck(spi_sck), .spi_mosi(spi_mosi),
.bus_idle(bus_idle), .cmd_valid(cmd_valid), .cmd_word(cmd_word)
);
// ---------------------------------------------------------
// Command fields
// ---------------------------------------------------------
// The protocol carries int16 values; only the low bits are used.
/* verilator lint_off UNUSEDSIGNAL */
wire [7:0] op = cmd_word[79:72];
wire [15:0] arg_a = cmd_word[71:56];
wire [15:0] arg_b = cmd_word[55:40];
wire [15:0] arg_c = cmd_word[39:24];
wire [15:0] arg_d = cmd_word[23:8];
wire [7:0] rgb332 = cmd_word[7:0];
/* verilator lint_on UNUSEDSIGNAL */
wire signed [CB-1:0] a = arg_a[CB-1:0];
wire signed [CB-1:0] b = arg_b[CB-1:0];
// RGB332 -> framebuffer pixel (ASIC: keep the MSB of R, G and B)
wire [PIX_BITS-1:0] cmd_color;
generate
if (PIX_BITS == 3) begin : g_rgb111
assign cmd_color = {rgb332[7], rgb332[4], rgb332[1]};
end
else begin : g_rgb332
assign cmd_color = rgb332[PIX_BITS-1:0];
end
endgenerate
// ---------------------------------------------------------
// Accepting a command
// ---------------------------------------------------------
wire rect_busy;
reg swap_pending;
wire idle = init_done && !rect_busy && !swap_pending;
wire accept = cmd_valid && idle; // a command sent while busy is dropped
assign gpu_ready = idle && !cmd_valid && bus_idle;
wire is_clear = (op == OP_CLEAR);
wire is_rect = (op == OP_RECT);
wire is_swap = (op == OP_SWAP);
// colour for the whole command, latched once
reg [PIX_BITS-1:0] draw_color;
always @(posedge clk) begin
if (reset)
dbg_cmd_toggle <= 1'b0;
else if (accept) begin
dbg_cmd_toggle <= !dbg_cmd_toggle;
draw_color <= cmd_color;
end
end
// ---------------------------------------------------------
// RECT / CLEAR: clip [x, x+w) x [y, y+h) to the screen.
// The filler then only walks visible pixels.
// ---------------------------------------------------------
localparam BW = CB + 2; // holds x + w
localparam X_LAST = FB_W - 1;
localparam Y_LAST = FB_H - 1;
localparam signed [BW-1:0] B_ONE = 1;
localparam signed [BW-1:0] B_ZERO = 0;
localparam signed [BW-1:0] B_XMAX = X_LAST[BW-1:0];
localparam signed [BW-1:0] B_YMAX = Y_LAST[BW-1:0];
wire signed [BW-1:0] rx0 = {{2{a[CB-1]}}, a}; // sign-extended
wire signed [BW-1:0] ry0 = {{2{b[CB-1]}}, b};
wire signed [BW-1:0] rx1 = rx0 + $signed({2'b00, arg_c[CB-1:0]}) - B_ONE; // inclusive
wire signed [BW-1:0] ry1 = ry0 + $signed({2'b00, arg_d[CB-1:0]}) - B_ONE;
wire signed [BW-1:0] kx0 = (rx0 < B_ZERO) ? B_ZERO : rx0;
wire signed [BW-1:0] ky0 = (ry0 < B_ZERO) ? B_ZERO : ry0;
wire signed [BW-1:0] kx1 = (rx1 > B_XMAX) ? B_XMAX : rx1;
wire signed [BW-1:0] ky1 = (ry1 > B_YMAX) ? B_YMAX : ry1;
// w = 0 or h = 0 or completely off screen -> nothing to draw
wire rect_visible = (kx0 <= kx1) && (ky0 <= ky1);
/* verilator lint_off UNUSEDSIGNAL */
wire [XW-1:0] fill_x0 = is_clear ? {XW{1'b0}} : kx0[XW-1:0];
wire [YW-1:0] fill_y0 = is_clear ? {YW{1'b0}} : ky0[YW-1:0];
wire [XW-1:0] fill_x1 = is_clear ? B_XMAX[XW-1:0] : kx1[XW-1:0];
wire [YW-1:0] fill_y1 = is_clear ? B_YMAX[YW-1:0] : ky1[YW-1:0];
/* verilator lint_on UNUSEDSIGNAL */
// ---------------------------------------------------------
// Draw engine. It only says "plot (x, y)", one pixel per clock.
// ---------------------------------------------------------
wire rect_plot;
wire [XW-1:0] rect_x;
wire [YW-1:0] rect_y;
rect_filler #(.XW(XW), .YW(YW)) u_rect (
.clk(clk), .reset(reset),
.start(accept && (is_clear || (is_rect && rect_visible))),
.x0(fill_x0), .y0(fill_y0), .x1(fill_x1), .y1(fill_y1),
.busy(rect_busy), .plot(rect_plot), .x(rect_x), .y(rect_y)
);
// ---------------------------------------------------------
// Pixel writer: address = y * FB_W + x. The rect filler only
// walks pixels that were clipped to the screen already, so every
// plot can be written as it is (step 3 adds clipping here).
// ---------------------------------------------------------
wire draw_we = rect_plot;
localparam [ADDR_BITS-1:0] STRIDE = FB_W[ADDR_BITS-1:0];
wire [ADDR_BITS-1:0] draw_x = {{(ADDR_BITS-XW){1'b0}}, rect_x};
wire [ADDR_BITS-1:0] draw_y = {{(ADDR_BITS-YW){1'b0}}, rect_y};
// ---------------------------------------------------------
// SWAP and double buffering
// front_buf = the buffer on screen; we always draw the other one
// ---------------------------------------------------------
reg front_buf;
wire vblank_start;
always @(posedge clk) begin
if (reset) begin
front_buf <= 1'b0;
swap_pending <= 1'b0;
end
else if (accept && is_swap)
swap_pending <= 1'b1;
else if (swap_pending && vblank_start) begin
swap_pending <= 1'b0;
if (DOUBLE_BUF)
front_buf <= !front_buf;
end
end
localparam BUF1_I = DOUBLE_BUF ? FB_PIXELS : 0;
localparam [ADDR_BITS-1:0] BUF1 = BUF1_I[ADDR_BITS-1:0];
wire [ADDR_BITS-1:0] front_base = front_buf ? BUF1 : {ADDR_BITS{1'b0}};
wire [ADDR_BITS-1:0] back_base = front_buf ? {ADDR_BITS{1'b0}} : BUF1;
// ---------------------------------------------------------
// Framebuffer: the init sweep has the write port until done
// ---------------------------------------------------------
wire fb_we = (!init_done && !reset) || draw_we;
wire [ADDR_BITS-1:0] fb_waddr = init_done ? back_base + draw_y * STRIDE + draw_x : init_addr;
wire [PIX_BITS-1:0] fb_wdata = init_done ? draw_color : {PIX_BITS{1'b0}};
wire [ADDR_BITS-1:0] scan_addr;
wire [PIX_BITS-1:0] scan_data;
frame_buffer #(.PIX_BITS(PIX_BITS), .DEPTH(DEPTH), .ADDR_BITS(ADDR_BITS)) u_fb (
.clk(clk),
.write_en(fb_we), .addr_write(fb_waddr), .write_data(fb_wdata),
.addr_read(front_base + scan_addr), .read_data(scan_data)
);
// ---------------------------------------------------------
// VGA scan-out
// ---------------------------------------------------------
vga_controller #(
.FB_WIDTH(FB_W), .SCALE_SHIFT(SCALE_SHIFT),
.PIX_BITS(PIX_BITS), .ADDR_BITS(ADDR_BITS)
) u_vga (
.clk(clk), .reset(reset), .frame_valid(init_done),
.fb_addr(scan_addr), .fb_data(scan_data),
.vblank_start(vblank_start),
.hsync(vga_hs), .vsync(vga_vs), .pixel(vga_pix)
);
endmodulefpga_top.v — the board shell
- Clock:
sysclk(125 MHz) →clk_wiz_0→clk_25m. Everything runs on that single clock. - Reset:
rst_n = clk_locked & ~reset. The GPU stays in reset until the MMCM is locked and while BTN0 is pressed. The logic infpga_topuses the same reset through its own 2-flop synchronizer. - Buttons and switches: synchronized (2 flops), then debounced by sampling slowly — every 217 clocks = 5.2 ms. A contact bounces for less than that, so between two samples a button is clearly up or down. A button that is down now and was up at the last sample starts one test.
- Test number: BTN1/BTN2/BTN3 → test 1/2/3, or 4/5/6 when SW1 is up.
- Autorun: the first time
gpu_readyrises after reset (the power-up clear is done), test 1 starts by itself if SW0 is up — a picture appears without touching anything. - SPI source: SW0 up → the GPU listens to the test host; SW0 down → to the Arduino connector (AR10/AR11/AR13). A plain multiplexer is fine: both sources are asynchronous to the GPU’s synchronizers anyway.
- Loopback outputs: the test host’s SPI is always also driven out on the 2×3 SPI header (AR_SS, AR_SCK, AR_MOSI) — three jumper wires back into AR10/AR13/AR11 test the real input pins (Step 26).
- Colour: RGB332 → RGB444 by repeating the top bits (
{r2,r1,r0,r2}), so full red really isFon your 4-bit DAC. - LEDs: LD0 READY, LD1 MMCM locked, LD2 toggles per accepted command, LD3 heartbeat (~0.75 Hz) — steady on while a test runs.
▸ Show fpga/fpga_top.v · 194 lines
`timescale 1ns / 1ps
// =============================================================
// PYNQ-Z2 top level for the SPI rasterizer GPU
//
// 125 MHz sysclk (H16) -> Clocking Wizard -> 25 MHz core/pixel clock
// 12-bit VGA on PMOD A / PMOD B (your video adapter, pins unchanged)
//
// SPI from an external Arduino on the PYNQ-Z2 Arduino header
// (the board labels these sockets AR0 .. AR13):
// AR10 -> spi_cs_n (T16) AR11 -> spi_mosi (R17)
// AR13 -> spi_sck (N17) AR12 <- gpu_ready (P18)
//
// On-board test host (no Arduino needed):
// SW0 = 1 : the GPU listens to the built-in test host, and test 1
// runs by itself after power-up / BTN0
// SW0 = 0 : the GPU listens to the Arduino header pins
// SW1 = 0 : BTN1 / BTN2 / BTN3 = tests 1 / 2 / 3 (the new tests of
// this bring-up step)
// SW1 = 1 : BTN1 / BTN2 / BTN3 = tests 4 / 5 / 6 (the tests of the
// previous step again: regression)
// The tests are in selftest.mem; each bring-up step has its own.
// The test host's SPI is also driven out on the 2x3 SPI header
// (AR_SS F16, AR_SCK H15, AR_MOSI T12) for the loopback test:
// wire AR_SS -> AR10, AR_SCK -> AR13, AR_MOSI -> AR11, set SW0 = 0.
//
// LD0 READY, LD1 clock locked, LD2 toggles per command,
// LD3 heartbeat (steady on while a test runs), BTN0 reset.
//
// This file is written once, in bring-up step 2, and does not change after
// that: steps 3 and 4 only add an engine to gpu_core and swap selftest.mem.
//
// Pure PL design: no Zynq PS, no AXI, no block design needed.
// =============================================================
module fpga_top #(
parameter DEBOUNCE_BITS = 17, // buttons sampled every 2^17 clocks = 5.2 ms
parameter ROM_FILE = "selftest.mem" // test commands (add the file to Vivado)
)(
input wire sysclk, // 125 MHz
input wire reset, // BTN0, active high
input wire [2:0] btn, // BTN1 .. BTN3: start a test
input wire [1:0] sw, // SW0: SPI source, SW1: test bank
// SPI from the Arduino (PYNQ Arduino header AR10 / AR11 / AR13)
input wire spi_cs_n,
input wire spi_sck,
input wire spi_mosi,
output wire gpu_ready, // AR12
// test host SPI out on the 2x3 SPI header (loopback test)
output wire test_cs_n, // AR_SS
output wire test_sck, // AR_SCK
output wire test_mosi, // AR_MOSI
// VGA (PMOD A + PMOD B)
output wire vga_hs,
output wire vga_vs,
output wire [3:0] vga_r,
output wire [3:0] vga_g,
output wire [3:0] vga_b,
output wire [3:0] led
);
// ---------------------------------------------------------
// Clock
// ---------------------------------------------------------
wire clk_25m;
wire clk_locked;
clk_wiz_0 u_clk ( // Clocking Wizard IP (see the guide)
.clk_in1(sysclk),
.reset(1'b0),
.clk_out1(clk_25m),
.locked(clk_locked)
);
// core stays in reset until the clock is stable and BTN0 is released
wire rst_n = clk_locked & ~reset;
// the same reset, synchronized, for the logic in this file
(* ASYNC_REG = "TRUE" *) reg [1:0] rst_s;
always @(posedge clk_25m or negedge rst_n)
if (!rst_n) rst_s <= 2'b11;
else rst_s <= {rst_s[0], 1'b0};
wire top_reset = rst_s[1];
// ---------------------------------------------------------
// Buttons and switches: synchronize, then debounce by sampling
// slowly (a bouncing contact settles in well under 5 ms)
// ---------------------------------------------------------
(* ASYNC_REG = "TRUE" *) reg [4:0] in_m, in_s; // {sw1, sw0, btn3, btn2, btn1}
reg [DEBOUNCE_BITS-1:0] tick;
reg [2:0] btn_q; // buttons at the last sample
reg test_start;
reg [2:0] test_sel;
reg autorun_done; // test 1 once after reset
always @(posedge clk_25m) begin
in_m <= {sw, btn};
in_s <= in_m;
end
wire [2:0] btn_s = in_s[2:0];
wire sw0_s = in_s[3];
wire sw1_s = in_s[4];
wire [2:0] press = btn_s & ~btn_q; // newly pressed at this sample
always @(posedge clk_25m) begin
test_start <= 1'b0;
if (top_reset) begin
tick <= 0;
btn_q <= 3'b000;
autorun_done <= 1'b0;
end
else begin
tick <= tick + 1'b1;
// power-up picture: as soon as the GPU is ready (power-up clear
// done), run test 1 once - only when SW0 selects the test host
if (!autorun_done && gpu_ready) begin
autorun_done <= 1'b1;
if (sw0_s) begin
test_start <= 1'b1;
test_sel <= 3'd0;
end
end
if (tick == 0) begin // one sample per period
btn_q <= btn_s;
if (press != 3'b000) begin
test_start <= 1'b1;
// BTN1/2/3 -> test 0/1/2, +3 when SW1 is up
test_sel <= (press[0] ? 3'd0 : press[1] ? 3'd1 : 3'd2) + (sw1_s ? 3'd3 : 3'd0);
end
end
end
end
// ---------------------------------------------------------
// On-board SPI test host
// ---------------------------------------------------------
wire test_busy;
spi_test_host #(.ROM_FILE(ROM_FILE)) u_test (
.clk(clk_25m), .reset(top_reset),
.start(test_start), .test_sel(test_sel), .gpu_ready(gpu_ready),
.busy(test_busy),
.spi_cs_n(test_cs_n), .spi_sck(test_sck), .spi_mosi(test_mosi)
);
// SPI source for the GPU. Both sources are asynchronous to the GPU's
// synchronizers anyway, so a plain multiplexer is fine here.
wire core_cs_n = sw0_s ? test_cs_n : spi_cs_n;
wire core_sck = sw0_s ? test_sck : spi_sck;
wire core_mosi = sw0_s ? test_mosi : spi_mosi;
// ---------------------------------------------------------
// The GPU
// ---------------------------------------------------------
wire [7:0] pix; // RGB332
wire cmd_toggle;
gpu_core #(
.FB_W(320), .FB_H(240), .SCALE_SHIFT(1), .PIX_BITS(8), .DOUBLE_BUF(1)
) u_gpu (
.clk(clk_25m), .rst_n(rst_n),
.spi_cs_n(core_cs_n), .spi_sck(core_sck), .spi_mosi(core_mosi),
.gpu_ready(gpu_ready),
.vga_hs(vga_hs), .vga_vs(vga_vs), .vga_pix(pix),
.dbg_cmd_toggle(cmd_toggle)
);
// RGB332 -> RGB444 for the 12-bit adapter (repeat MSBs into the LSBs)
assign vga_r = {pix[7:5], pix[7]};
assign vga_g = {pix[4:2], pix[4]};
assign vga_b = {pix[1:0], pix[1:0]};
// ---------------------------------------------------------
// Status LEDs
// ---------------------------------------------------------
reg [24:0] heartbeat = 25'd0;
always @(posedge clk_25m)
heartbeat <= heartbeat + 1'b1;
assign led[0] = gpu_ready;
assign led[1] = clk_locked;
assign led[2] = cmd_toggle;
assign led[3] = test_busy | heartbeat[24];
endmodulespi_test_host.v — an SPI master that behaves like the Arduino
A 256 × 80-bit ROM holds the tests (selftest.mem). Tests are stored one after the other, each ended by an all-zero word. On start the host skips forward to the selected test, then for each command: wait for gpu_ready → CS low → 80 bits MSB first, SPI mode 0 at 25 MHz / 12 = 2.08 MHz → CS high → 32-clock gap. Exactly what gpuSend() does in the sketch, so the GPU cannot tell the difference.
| State | What it does |
|---|---|
| S_IDLE | wait for start; remember the test number |
| S_SEEK | walk the ROM, counting all-zero end markers, until test N begins |
| S_WAIT | end marker → done; else wait for gpu_ready, then CS low with the first bit on MOSI |
| S_SHIFT | 6 clocks SCK low, 6 clocks high, per bit; MOSI changes on the falling edge, the GPU samples on the rising edge |
| S_GAP | CS high after half a bit, then 32 clocks before looking at READY again |
▸ Show fpga/spi_test_host.v · 143 lines
`timescale 1ns / 1ps
// =============================================================
// spi_test_host : on-board SPI master for testing without an Arduino
//
// A ROM holds test command streams (80-bit commands, generated by
// scripts/gen_selftest.py into selftest.mem). A test is a run of
// commands ended by an all-zero word:
//
// <test 0 commands> 0000..00 <test 1 commands> 0000..00 ...
//
// On start, the host skips to test number test_sel and sends its
// commands exactly like the Arduino does:
// wait for gpu_ready -> CS low -> 80 bits, SPI mode 0, MSB first
// -> CS high -> short gap -> next command
//
// SCK = clk / (2 * HALF) = 25 MHz / 12 = 2.08 MHz (the GPU allows clk/8).
// The frames go through the GPU's normal SPI receiver, so a test run
// exercises synchronizers, framing, READY flow control and the engines.
// =============================================================
module spi_test_host #(
parameter ROM_FILE = "selftest.mem",
parameter ROM_DEPTH = 256,
parameter HALF = 6, // clocks per SCK half period
parameter GAP = 32 // clocks between CS high and READY check
)(
input wire clk,
input wire reset,
input wire start, // 1-clock pulse
input wire [2:0] test_sel, // which test (0 .. 7)
input wire gpu_ready,
output reg busy,
output reg spi_cs_n,
output reg spi_sck,
output reg spi_mosi
);
localparam AW = $clog2(ROM_DEPTH);
localparam LAST_I = ROM_DEPTH - 1;
localparam [AW-1:0] LAST = LAST_I[AW-1:0];
// ---- command ROM (Vivado: distributed ROM, contents from the .mem) ----
reg [79:0] rom [0:ROM_DEPTH-1];
initial $readmemh(ROM_FILE, rom);
reg [AW-1:0] addr;
wire [79:0] word = rom[addr];
wire is_end = (word == 80'd0);
localparam [2:0] S_IDLE = 3'd0,
S_SEEK = 3'd1, // skip to the selected test
S_WAIT = 3'd2, // wait for READY
S_SHIFT = 3'd3, // send 80 bits
S_GAP = 3'd4; // CS high + gap
reg [2:0] state;
reg [2:0] target, seen; // test wanted / end markers passed
reg [78:0] shreg; // bits still to send after the first
reg [6:0] nbit;
reg [5:0] timer;
wire half_done = (timer == HALF - 1);
always @(posedge clk) begin
if (reset) begin
state <= S_IDLE;
busy <= 1'b0;
spi_cs_n <= 1'b1;
spi_sck <= 1'b0;
spi_mosi <= 1'b0;
end
else case (state)
S_IDLE:
if (start) begin
busy <= 1'b1;
addr <= 0;
seen <= 0;
target <= test_sel;
state <= S_SEEK;
end
S_SEEK:
if (seen == target)
state <= S_WAIT; // addr = first command
else if (addr == LAST) begin
busy <= 1'b0; // test not in the ROM
state <= S_IDLE;
end
else begin
if (is_end) seen <= seen + 1'b1;
addr <= addr + 1'b1;
end
S_WAIT:
if (is_end) begin // end of this test
busy <= 1'b0;
state <= S_IDLE;
end
else if (gpu_ready) begin // start a frame
shreg <= word[78:0];
spi_mosi <= word[79]; // first bit, set up before SCK
spi_cs_n <= 1'b0;
nbit <= 0;
timer <= 0;
state <= S_SHIFT;
end
S_SHIFT:
if (!half_done)
timer <= timer + 1'b1;
else begin
timer <= 0;
if (!spi_sck)
spi_sck <= 1'b1; // rising edge: GPU samples MOSI
else begin
spi_sck <= 1'b0; // falling edge: next bit
spi_mosi <= shreg[78];
shreg <= {shreg[77:0], 1'b0};
if (nbit == 7'd79)
state <= S_GAP;
else
nbit <= nbit + 1'b1;
end
end
default: begin // S_GAP
timer <= timer + 1'b1;
if (timer == HALF - 1)
spi_cs_n <= 1'b1; // end of frame
if (timer == GAP - 1) begin
timer <= 0;
addr <= addr + 1'b1;
state <= S_WAIT;
end
end
endcase
end
endmodulepynq_gpu.xdc
Your adapter pins exactly as in your old pynq.xdc (and as in step 1). New: the four Arduino-connector pins, BTN1–BTN3, SW0–SW1 and the three SPI-header outputs. Every line carries its board label as a comment:
| Signal | Board label | FPGA pin | Dir | Note |
|---|---|---|---|---|
| spi_cs_n | AR10 | T16 | in | internal pull-up → idle high |
| spi_mosi | AR11 | R17 | in | pull-down |
| spi_sck | AR13 | N17 | in | pull-down → idle low (mode 0) |
| gpu_ready | AR12 | P18 | out | 3.3 V, 8 mA |
| test_cs_n / test_sck / test_mosi | AR_SS / AR_SCK / AR_MOSI | F16 / H15 / T12 | out | test host (loopback) |
| btn[2:0] · sw[1:0] | BTN3–1 · SW1–0 | L19 L20 D20 · M19 M20 | in | asynchronous, synchronized + debounced |
| sysclk | — | H16 | in | 125 MHz oscillator |
| reset | BTN0 | D19 | in | active high |
| vga_* | PMOD A + B | unchanged | out | your video adapter |
▸ Show fpga/pynq_gpu.xdc · 80 lines
## =============================================================================
## pynq_gpu.xdc - PYNQ-Z2 constraints for fpga_top (SPI rasterizer GPU)
##
## All pins are 3.3 V LVCMOS33 programmable-logic pins. Names in the ;# comments
## are the labels of the PYNQ-Z2 reference manual / schematic.
##
## PMOD A (JA) : your video adapter -> HSYNC, VSYNC, BLUE[3:0]
## PMOD B (JB) : your video adapter -> RED[3:0], GREEN[3:0]
## Arduino header : SPI from the external Arduino (board labels AR0 .. AR13)
## AR10 = CS_N, AR11 = MOSI, AR12 = READY (out), AR13 = SCK
## SPI header 2x3 : on-board test host OUT (loopback test)
## AR_SS (pin 5), AR_SCK (pin 3), AR_MOSI (pin 4)
## BTN0 reset, BTN1..BTN3 run a test, SW0 SPI source, SW1 test bank
## LD0..LD3 status LEDs
##
## PMOD pins: JA-2 means PMOD A physical pin 2. The PYNQ-Z2 manual calls that
## pin JA1_N (pins come in P/N pairs: 1/2 = JA1_P/N, 3/4 = JA2_P/N, 7/8 = JA3_P/N,
## 9/10 = JA4_P/N), so "JA2" alone is ambiguous. Pins 5/11 = GND, 6/12 = 3.3 V.
## =============================================================================
## ---------------------------------------------------------------- clock / reset
## 125 MHz oscillator (from the Ethernet PHY) on PL pin H16
set_property -dict { PACKAGE_PIN H16 IOSTANDARD LVCMOS33 } [get_ports sysclk]
create_clock -add -name sys_clk_pin -period 8.00 -waveform {0 4} [get_ports sysclk]
## BTN0, active high
set_property -dict { PACKAGE_PIN D19 IOSTANDARD LVCMOS33 } [get_ports reset] ;# BTN0
## ---------------------------------------------------------------- test buttons / switches
set_property -dict { PACKAGE_PIN D20 IOSTANDARD LVCMOS33 } [get_ports {btn[0]}] ;# BTN1
set_property -dict { PACKAGE_PIN L20 IOSTANDARD LVCMOS33 } [get_ports {btn[1]}] ;# BTN2
set_property -dict { PACKAGE_PIN L19 IOSTANDARD LVCMOS33 } [get_ports {btn[2]}] ;# BTN3
set_property -dict { PACKAGE_PIN M20 IOSTANDARD LVCMOS33 } [get_ports {sw[0]}] ;# SW0
set_property -dict { PACKAGE_PIN M19 IOSTANDARD LVCMOS33 } [get_ports {sw[1]}] ;# SW1
## ---------------------------------------------------------------- LEDs
## LD0 = READY LD1 = clock locked LD2 = toggles per command LD3 = heartbeat / test running
set_property -dict { PACKAGE_PIN R14 IOSTANDARD LVCMOS33 } [get_ports {led[0]}] ;# LD0
set_property -dict { PACKAGE_PIN P14 IOSTANDARD LVCMOS33 } [get_ports {led[1]}] ;# LD1
set_property -dict { PACKAGE_PIN N16 IOSTANDARD LVCMOS33 } [get_ports {led[2]}] ;# LD2
set_property -dict { PACKAGE_PIN M14 IOSTANDARD LVCMOS33 } [get_ports {led[3]}] ;# LD3
## ---------------------------------------------------------------- VGA, PMOD A (JA)
## unchanged from your old pynq.xdc. JA-1 (Y18) and JA-7 (U18) stay unused.
set_property -dict { PACKAGE_PIN Y19 IOSTANDARD LVCMOS33 } [get_ports vga_hs] ;# JA-2 (JA1_N)
set_property -dict { PACKAGE_PIN U19 IOSTANDARD LVCMOS33 } [get_ports vga_vs] ;# JA-8 (JA3_N)
set_property -dict { PACKAGE_PIN Y17 IOSTANDARD LVCMOS33 } [get_ports {vga_b[0]}] ;# JA-4 (JA2_N)
set_property -dict { PACKAGE_PIN W19 IOSTANDARD LVCMOS33 } [get_ports {vga_b[1]}] ;# JA-10 (JA4_N)
set_property -dict { PACKAGE_PIN Y16 IOSTANDARD LVCMOS33 } [get_ports {vga_b[2]}] ;# JA-3 (JA2_P)
set_property -dict { PACKAGE_PIN W18 IOSTANDARD LVCMOS33 } [get_ports {vga_b[3]}] ;# JA-9 (JA4_P)
## ---------------------------------------------------------------- VGA, PMOD B (JB)
set_property -dict { PACKAGE_PIN T10 IOSTANDARD LVCMOS33 } [get_ports {vga_r[0]}] ;# JB-4 (JB2_N)
set_property -dict { PACKAGE_PIN W13 IOSTANDARD LVCMOS33 } [get_ports {vga_r[1]}] ;# JB-10 (JB4_N)
set_property -dict { PACKAGE_PIN T11 IOSTANDARD LVCMOS33 } [get_ports {vga_r[2]}] ;# JB-3 (JB2_P)
set_property -dict { PACKAGE_PIN V12 IOSTANDARD LVCMOS33 } [get_ports {vga_r[3]}] ;# JB-9 (JB4_P)
set_property -dict { PACKAGE_PIN Y14 IOSTANDARD LVCMOS33 } [get_ports {vga_g[0]}] ;# JB-2 (JB1_N)
set_property -dict { PACKAGE_PIN W16 IOSTANDARD LVCMOS33 } [get_ports {vga_g[1]}] ;# JB-8 (JB3_N)
set_property -dict { PACKAGE_PIN W14 IOSTANDARD LVCMOS33 } [get_ports {vga_g[2]}] ;# JB-1 (JB1_P)
set_property -dict { PACKAGE_PIN V16 IOSTANDARD LVCMOS33 } [get_ports {vga_g[3]}] ;# JB-7 (JB3_P)
## ---------------------------------------------------------------- SPI in, Arduino header
## The sockets an Arduino SPI shield uses (AR10..AR13). 3.3 V ONLY - see the wiring step.
## Pull-ups/downs keep the bus idle when nothing is plugged in.
set_property -dict { PACKAGE_PIN T16 IOSTANDARD LVCMOS33 PULLUP true } [get_ports spi_cs_n] ;# AR10
set_property -dict { PACKAGE_PIN R17 IOSTANDARD LVCMOS33 PULLDOWN true } [get_ports spi_mosi] ;# AR11
set_property -dict { PACKAGE_PIN N17 IOSTANDARD LVCMOS33 PULLDOWN true } [get_ports spi_sck] ;# AR13
set_property -dict { PACKAGE_PIN P18 IOSTANDARD LVCMOS33 DRIVE 8 } [get_ports gpu_ready] ;# AR12
## ---------------------------------------------------------------- SPI out, 2x3 SPI header
## The on-board test host's SPI, for the loopback test (jumper these to AR10/AR13/AR11).
set_property -dict { PACKAGE_PIN F16 IOSTANDARD LVCMOS33 DRIVE 8 } [get_ports test_cs_n] ;# AR_SS
set_property -dict { PACKAGE_PIN H15 IOSTANDARD LVCMOS33 DRIVE 8 } [get_ports test_sck] ;# AR_SCK
set_property -dict { PACKAGE_PIN T12 IOSTANDARD LVCMOS33 DRIVE 8 } [get_ports test_mosi] ;# AR_MOSI
## ---------------------------------------------------------------- timing exceptions
## SPI pins, buttons and switches are asynchronous: they only enter 2-flop synchronizers.
set_false_path -from [get_ports {spi_cs_n spi_sck spi_mosi reset btn[*] sw[*]}]
## Board outputs have no timing relationship we need to analyse.
set_false_path -to [get_ports {vga_* gpu_ready led[*] test_*}]Do
- Add Sources → design sources →
rtl\spi_cmd_rx.v,rtl\frame_buffer.v,rtl\rect_filler.v,bringup\step2_rect\gpu_core.v,fpga\fpga_top.v,fpga\spi_test_host.v. - Add Sources → design sources → filter All Files →
bringup\step2_rect\selftest.mem. - Add Sources → constraints →
fpga\pynq_gpu.xdc. Then right-clickvga_test.xdc→ Disable File (one XDC per top level). - Sources: right-click
fpga_top→ Set as Top. Below it:u_clk,u_test : spi_test_host,u_gpu : gpu_corewithu_spi,u_rect,u_fb,u_vga. The step-1 files stay in the project unused — to go back to step 1, setvga_test_topas top and swap which XDC is disabled. - SW0 up, SW1 down. Build and program (Step 21).
The tests
Test 1 appears by itself after programming (and after every BTN0). The others: SW1 down, then BTN1 / BTN2 / BTN3. While a test runs LD3 is on and LD2 flickers once per command; the picture appears at the SWAP — it is drawn in the hidden buffer.
| Test | Commands | If it looks right, these work | If not, look at |
|---|---|---|---|
| 1 · HI | CLEAR, 10 RECT, SWAP | SPI receiver + synchronizers, 80-bit framing, READY handshake, CLEAR, the rect engine, address = y · 320 + x (the letters sit where the numbers say), SWAP, the 2× scaling (the border sits exactly on the screen edge) | nothing at all: SW0 up? LD0 on? LD2 flickers? · border missing on one side: the RECT clip limits |
| 2 · colours | CLEAR, 15 RECT, SWAP | all 8 palette colours through RGB332 → RGB444, rectangles down to 2 × 2 and 1 × 1 | colours wrong although step 1 was right: the RGB332 expansion in fpga_top · 1 × 1 missing: the - 1 of the inclusive corner |
| 3 · blocks | CLEAR, 12 RECT, SWAP | RECT clipping on all four edges and both corners, bars with both ends off screen, a fully off-screen rectangle and a width-0 rectangle draw nothing | colour on the opposite edge (wrap-around): the clamp of x0/x1 · a red square appears: the off-screen check (rect_visible) |
SW1 up: no tests in step 2 (there is no earlier step); the buttons do nothing.
run_sims.sh stage 7 compiles fpga_top with exactly the step-2 files (no line or circle engine anywhere), lets test 1 run by itself, presses BTN1–BTN3, checks that tests 4–6 send nothing, and runs test 2 once more through the loopback pins. Every frame captured from the VGA pins is byte-identical to the frame of tb_gpu, which checks every pixel against its golden model. The pictures above are those captures.
Done when all three pictures match. The command path, the framebuffer, double buffering and RECT are proven on the real FPGA.
Bring-up step 3: add the line engine
What is new about lines
Lines bring two things the core did not need before. There are now two engines, so the pixel writer has to take its pixel from whichever one is busy. And a line can run off the screen: Bresenham has to walk through the off-screen part to stay exact (Step 10), so its pixels can no longer be written blindly — every plotted pixel is checked against the screen first. That check sits in the shared pixel writer, so it is written once and will serve the circle too.
Do
- Add Sources → design sources →
rtl\line_renderer.v. - Swap the core and the tests: in Sources, right-click
bringup/step2_rect/gpu_core.v→ Remove File from Project, same for the step-2selftest.mem(the files stay on disk). Then Add Sources →bringup\step3_line\gpu_core.vandbringup\step3_line\selftest.mem. - Read the change below — that is the whole difference between the two cores.
- Build and program (Step 21). SW0 up.
What changes in gpu_core.v
··· bringup/step3_line/gpu_core.v, line 2
// =============================================================
// gpu_core : SPI rasterizer GPU - BRING-UP STEP 2 (rect only)
// SPI receiver + framebuffer + VGA scan-out + CLEAR/RECT/SWAP
//
// The first core you build: one drawing engine (rect_filler), so the
// command path, the framebuffer, double buffering and the VGA read side
// can be tested with nothing else in the way. LINE (0x02) and CIRCLE
// (0x05) frames are received, acknowledged and ignored.
// Step 3 = bringup/step3_line/gpu_core.v, step 4 = rtl/gpu_core.v.
// gpu_core : SPI rasterizer GPU - BRING-UP STEP 3 (rect + line)
// VGA scan-out + framebuffer + rectangle + line
//
// Step 2 plus the line engine. New compared with step 2:
// * line_renderer instance, started by opcode 0x02
// * the pixel writer picks the busy engine (line or rect)
// * the pixel writer clips: a line may run off the screen, so every
// plotted pixel is checked before it is written
// CIRCLE (0x05) is still accepted and ignored. Step 4 = rtl/gpu_core.v.
//
// Parameters as in the final core (the ASIC builds use only the final
··· bringup/step3_line/gpu_core.v, line 33
//
// 0x01 CLEAR - fill the whole back buffer
// 0x02 LINE (step 3) accepted and ignored here
// 0x02 LINE A=x0 B=y0 C=x1 D=y1 Bresenham, both ends drawn
// 0x03 RECT A=x B=y C=w D=h filled
// 0x04 SWAP - show the back buffer at the
··· bringup/step3_line/gpu_core.v, line 42
// Coordinates use the low COORD_BITS bits as a signed number
// (-2048 .. 2047), w/h the low COORD_BITS bits unsigned.
// A rectangle that is partly off screen is clipped.
// Anything off screen is clipped.
// =============================================================
··· bringup/step3_line/gpu_core.v, line 77
localparam YW = $clog2(FB_H);
localparam CB = COORD_BITS;
localparam PW = COORD_BITS; // pixel coordinate width
localparam [7:0] OP_CLEAR = 8'h01;
localparam [7:0] OP_LINE = 8'h02;
localparam [7:0] OP_RECT = 8'h03;
localparam [7:0] OP_SWAP = 8'h04;
··· bringup/step3_line/gpu_core.v, line 153
wire signed [CB-1:0] a = arg_a[CB-1:0];
wire signed [CB-1:0] b = arg_b[CB-1:0];
wire signed [CB-1:0] c = arg_c[CB-1:0];
wire signed [CB-1:0] d = arg_d[CB-1:0];
// RGB332 -> framebuffer pixel (ASIC: keep the MSB of R, G and B)
··· bringup/step3_line/gpu_core.v, line 171
// Accepting a command
// ---------------------------------------------------------
wire rect_busy;
wire line_busy, rect_busy;
reg swap_pending;
wire idle = init_done && !rect_busy && !swap_pending;
wire idle = init_done && !line_busy && !rect_busy && !swap_pending;
wire accept = cmd_valid && idle; // a command sent while busy is dropped
··· bringup/step3_line/gpu_core.v, line 180
wire is_clear = (op == OP_CLEAR);
wire is_line = (op == OP_LINE);
wire is_rect = (op == OP_RECT);
wire is_swap = (op == OP_SWAP);
··· bringup/step3_line/gpu_core.v, line 232
// ---------------------------------------------------------
// Draw engine. It only says "plot (x, y)", one pixel per clock.
// ---------------------------------------------------------
wire rect_plot;
// Draw engines. Each one only says "plot (x, y)", one pixel
// per clock. Exactly one engine is busy at a time.
// ---------------------------------------------------------
wire line_plot, rect_plot;
wire signed [CB-1:0] line_x, line_y;
wire [XW-1:0] rect_x;
wire [YW-1:0] rect_y;
line_renderer #(.CW(CB)) u_line (
.clk(clk), .reset(reset),
.start(accept && is_line),
.x0(a), .y0(b), .x1(c), .y1(d),
.busy(line_busy), .plot(line_plot), .x(line_x), .y(line_y)
);
rect_filler #(.XW(XW), .YW(YW)) u_rect (
··· bringup/step3_line/gpu_core.v, line 256
// ---------------------------------------------------------
// Pixel writer: address = y * FB_W + x. The rect filler only
// walks pixels that were clipped to the screen already, so every
// plot can be written as it is (step 3 adds clipping here).
// ---------------------------------------------------------
wire draw_we = rect_plot;
// Pixel writer, shared by both engines:
// pick the active engine -> clip -> address = y * FB_W + x
// ---------------------------------------------------------
localparam signed [PW-1:0] P_ZERO = 0;
localparam signed [PW-1:0] P_W = FB_W[PW-1:0];
localparam signed [PW-1:0] P_H = FB_H[PW-1:0];
wire signed [PW-1:0] rect_xs = $signed({{(PW-XW){1'b0}}, rect_x});
wire signed [PW-1:0] rect_ys = $signed({{(PW-YW){1'b0}}, rect_y});
wire plot = line_plot || rect_plot;
wire signed [PW-1:0] plot_x = line_plot ? line_x : rect_xs;
wire signed [PW-1:0] plot_y = line_plot ? line_y : rect_ys;
wire on_screen = (plot_x >= P_ZERO) && (plot_x < P_W) &&
(plot_y >= P_ZERO) && (plot_y < P_H);
wire draw_we = plot && on_screen;
// only used when on_screen, so the low XW / YW bits are the whole value
localparam [ADDR_BITS-1:0] STRIDE = FB_W[ADDR_BITS-1:0];
wire [ADDR_BITS-1:0] draw_x = {{(ADDR_BITS-XW){1'b0}}, rect_x};
wire [ADDR_BITS-1:0] draw_y = {{(ADDR_BITS-YW){1'b0}}, rect_y};
wire [ADDR_BITS-1:0] draw_x = {{(ADDR_BITS-XW){1'b0}}, plot_x[XW-1:0]};
wire [ADDR_BITS-1:0] draw_y = {{(ADDR_BITS-YW){1'b0}}, plot_y[YW-1:0]};
| Change | Why |
|---|---|
OP_LINE, is_line, arguments c, d | LINE uses all four arguments (x0, y0, x1, y1); RECT only needed A and B signed |
line_busy in idle | READY stays low while a line is drawn, so the host waits |
u_line instance | started by accept && is_line, like the rect engine by its opcode |
plot_x / plot_y multiplexer | one writer, two engines; only one is ever busy, so “line if it plots, else rect” is enough |
on_screen and draw_we = plot && on_screen | line pixels can be off screen; without this they would wrap into the next row or the other buffer |
draw_x from plot_x[XW-1:0] | only used when on_screen, so the low bits are the whole value |
The tests
| Test | Commands | If it looks right, these work | If not, look at |
|---|---|---|---|
| 1 · starburst | CLEAR, 38 LINE, SWAP | Bresenham in all 8 octants, horizontal and vertical lines, both end points drawn (the frame corners are closed, the rays meet in one centre pixel) | a group of rays missing or mirrored: sx/sy · gaps: the error term · open frame corners: the last pixel |
| 2 · string art | CLEAR, 52 LINE, SWAP | many lines back to back at READY speed, exact end points on the screen edges (the curves are smooth only if every end point is right) | kinks in a curve: an end point off by one · missing lines: a command dropped while busy |
| 3 · house | CLEAR, 7 RECT, 27 LINE, SWAP | both engines in one frame through the shared writer, line clipping: sun rays and road lines start or end hundreds of pixels off screen | a line reappears on the other side: on_screen · rectangles broken now: the plot_x multiplexer |
Regression: step 2 still works
SW1 up + BTN1 / BTN2 / BTN3 runs the three step-2 tests on the new core. You must get exactly the step-2 pictures (“HI”, colours, blocks). If one of them changed, the new code broke the old path — most likely the multiplexer or the clipping in the pixel writer.
Stage 7 compiles fpga_top with the step-3 files only (no circle engine), runs the power-up test, tests 1–6 (new + regression) and the loopback; every frame is byte-identical to the golden-model frame.
Bring-up step 4: add the circle engine — the complete GPU
What is new about circles
A third engine for the multiplexer — and wider coordinates. A circle’s pixels are cx ± r and cy ± r: with a 12-bit centre and an 11-bit radius they can reach ±4095, beyond what 12 signed bits hold. So the pixel writer’s width PW grows from 12 to 15 bits and the line coordinates are sign-extended into it. Without that a big circle would wrap around: test 3 draws one (r = 1000, centre 900 pixels below the screen, its lowest point at y = 2140) on purpose.
Do
- Add Sources → design sources →
rtl\circle_renderer.v. - Swap the core and the tests: remove
bringup/step3_line/gpu_core.vand itsselftest.memfrom the project; addrtl\gpu_core.vandfpga\selftest.mem. These two are the final files — the same core the ASIC uses. - Build and program (Step 21). SW0 up.
What changes in gpu_core.v
··· rtl/gpu_core.v, line 2
// =============================================================
// gpu_core : SPI rasterizer GPU - BRING-UP STEP 3 (rect + line)
// VGA scan-out + framebuffer + rectangle + line
//
// Step 2 plus the line engine. New compared with step 2:
// * line_renderer instance, started by opcode 0x02
// * the pixel writer picks the busy engine (line or rect)
// * the pixel writer clips: a line may run off the screen, so every
// plotted pixel is checked before it is written
// CIRCLE (0x05) is still accepted and ignored. Step 4 = rtl/gpu_core.v.
//
// Parameters as in the final core (the ASIC builds use only the final
// rtl/gpu_core.v):
// gpu_core : SPI rasterizer GPU
// VGA scan-out + framebuffer + line + rectangle + circle
//
// The SAME file is used on the PYNQ-Z2 and in the SKY130 ASIC,
// only the parameters change:
//
// parameter FPGA (PYNQ-Z2) ASIC v1 (SKY130) ASIC v2 (SRAM)
··· rtl/gpu_core.v, line 13
// PIX_BITS 8 (RGB332) 3 (RGB111) 8
// DOUBLE_BUF 1 0 0
//
// This is the complete core (bring-up step 4). The FPGA bring-up builds
// it up in steps: bringup/step2_rect/gpu_core.v (RECT only), then
// bringup/step3_line/gpu_core.v (+ LINE), then this file (+ CIRCLE).
//
// Host protocol: one 10-byte SPI frame per command (mode 0, MSB
··· rtl/gpu_core.v, line 35
// next vblank (single buffer:
// just wait for vblank)
// 0x05 CIRCLE (step 4) accepted and ignored here
// 0x05 CIRCLE A=cx B=cy C=r D=fill midpoint circle, D bit 0:
// 0 = outline, 1 = filled
//
// Coordinates use the low COORD_BITS bits as a signed number
// (-2048 .. 2047), w/h the low COORD_BITS bits unsigned.
// Anything off screen is clipped.
// (-2048 .. 2047), w/h the low COORD_BITS bits unsigned, r the low
// COORD_BITS-1 bits (0 .. 2047). Anything off screen is clipped.
// =============================================================
··· rtl/gpu_core.v, line 75
localparam YW = $clog2(FB_H);
localparam CB = COORD_BITS;
localparam PW = COORD_BITS; // pixel coordinate width
localparam PW = COORD_BITS + 3; // pixel coordinate width
// (circle: cx +- r)
localparam [7:0] OP_CLEAR = 8'h01;
··· rtl/gpu_core.v, line 82
localparam [7:0] OP_RECT = 8'h03;
localparam [7:0] OP_SWAP = 8'h04;
localparam [7:0] OP_CIRCLE = 8'h05;
··· rtl/gpu_core.v, line 171
// Accepting a command
// ---------------------------------------------------------
wire line_busy, rect_busy;
wire line_busy, rect_busy, circ_busy;
reg swap_pending;
wire idle = init_done && !line_busy && !rect_busy && !swap_pending;
wire idle = init_done && !line_busy && !rect_busy && !circ_busy && !swap_pending;
wire accept = cmd_valid && idle; // a command sent while busy is dropped
··· rtl/gpu_core.v, line 183
wire is_rect = (op == OP_RECT);
wire is_swap = (op == OP_SWAP);
wire is_circle = (op == OP_CIRCLE);
// colour for the whole command, latched once
··· rtl/gpu_core.v, line 236
// per clock. Exactly one engine is busy at a time.
// ---------------------------------------------------------
wire line_plot, rect_plot;
wire line_plot, rect_plot, circ_plot;
wire signed [CB-1:0] line_x, line_y;
wire [XW-1:0] rect_x;
wire [YW-1:0] rect_y;
wire signed [PW-1:0] circ_x, circ_y;
line_renderer #(.CW(CB)) u_line (
··· rtl/gpu_core.v, line 256
);
// ---------------------------------------------------------
// Pixel writer, shared by both engines:
wire signed [PW-1:0] cx_p = {{3{a[CB-1]}}, a}; // sign-extend to PW
wire signed [PW-1:0] cy_p = {{3{b[CB-1]}}, b};
circle_renderer #(.CW(PW), .RW(CB - 1), .SCREEN_W(FB_W), .SCREEN_H(FB_H)) u_circ (
.clk(clk), .reset(reset),
.start(accept && is_circle),
.fill(arg_d[0]),
.cx_in(cx_p), .cy_in(cy_p),
.r_in(arg_c[CB-2:0]),
.busy(circ_busy), .plot(circ_plot), .px(circ_x), .py(circ_y)
);
// ---------------------------------------------------------
// Pixel writer, shared by all engines:
// pick the active engine -> clip -> address = y * FB_W + x
// ---------------------------------------------------------
··· rtl/gpu_core.v, line 280
wire signed [PW-1:0] rect_ys = $signed({{(PW-YW){1'b0}}, rect_y});
wire plot = line_plot || rect_plot;
wire signed [PW-1:0] plot_x = line_plot ? line_x : rect_xs;
wire signed [PW-1:0] plot_y = line_plot ? line_y : rect_ys;
wire signed [PW-1:0] line_xs = {{3{line_x[CB-1]}}, line_x};
wire signed [PW-1:0] line_ys = {{3{line_y[CB-1]}}, line_y};
wire plot = line_plot || rect_plot || circ_plot;
wire signed [PW-1:0] plot_x = line_plot ? line_xs : circ_plot ? circ_x : rect_xs;
wire signed [PW-1:0] plot_y = line_plot ? line_ys : circ_plot ? circ_y : rect_ys;
wire on_screen = (plot_x >= P_ZERO) && (plot_x < P_W) &&| Change | Why |
|---|---|
PW = COORD_BITS + 3 | cx ± r needs 15 signed bits; every coordinate in the writer gets this width |
OP_CIRCLE, is_circle, circ_busy in idle | same pattern as LINE in step 3 |
cx_p, cy_p and u_circ | centre sign-extended to 15 bits; fill = D[0], radius = the low 11 bits of C |
line_xs / line_ys | line coordinates sign-extended from 12 to 15 bits |
3-way plot_x / plot_y | line, else circle, else rect |
The tests
| Test | Commands | If it looks right, these work | If not, look at |
|---|---|---|---|
| 1 · target | CLEAR, 22 CIRCLE, SWAP | outline and filled circles, discs with no holes and no double rows (rings of alternating colour stay clean), clipping at the bottom edge | holes or stripes in a disc: the span rules (Step 12) · rings not round: the d update |
| 2 · snowman | CLEAR, 18 CIRCLE, 5 RECT, 4 LINE, SWAP | all three engines in one frame, overdraw (the crescent moon is a yellow disc minus a dark one, cut by the top edge), radius 0 = one pixel and radius 1 = a small ring (the snowflakes) | moon wraps to the bottom: circle clipping · snowflakes missing: r = 0 / 1 |
| 3 · edges | CLEAR, 6 RECT, 1 LINE, 9 CIRCLE, SWAP | every engine clipped on every edge, centres on and outside the screen, the r = 1000 arc (needs the 15-bit writer), a fully off-screen disc draws nothing | colour on the opposite edge or a stray arc: PW too narrow or on_screen |
Regression: step 3 still works
SW1 up + BTN1 / BTN2 / BTN3 runs the step-3 tests (starburst, string art, house) on the final core — the house also re-checks RECT.
Stage 7 runs the final fpga_top + rtl/gpu_core.v with fpga/selftest.mem: power-up test, tests 1–6, loopback — all byte-identical to the golden-model frames.
This is the final bitstream. The Arduino uses exactly this design: SW0 down, and the SPI comes from the Arduino connector instead of the test host. Before wiring it, check the real input pins with the loopback test (Step 26).
The test host: loopback through the real pins, and your own tests
Why a test host instead of Vitis
In your old project you would have written a Vitis program on the ARM core — but then the commands would arrive over AXI, not over SPI, and the part you most want to test would be skipped. spi_test_host.v sits in the fabric and talks real SPI to the GPU, exactly like the Arduino. No software, no PS, no wires.
The three ROMs
| ROM | Step | Tests 1–3 (SW1 down) | Tests 4–6 (SW1 up) | Words |
|---|---|---|---|---|
bringup/step2_rect/selftest.mem | 2 | HI · colours · blocks | — (empty) | 49 / 256 |
bringup/step3_line/selftest.mem | 3 | starburst · string art · house | step 2 again | 179 / 256 |
fpga/selftest.mem | 4 (final) | target · snowman · edges | step 3 again | 207 / 256 |
A ROM contains only commands its step’s core can draw; check_pins.py section [G] checks that, the sizes and that every test starts with CLEAR and ends with SWAP.
Loopback: test the real input pins, still without an Arduino
With SW0 up the frames never leave the FPGA. To also test the Arduino-connector pins, their pull-ups and the XDC, let the test host’s SPI go out on the SPI header and come back in through AR10, AR11 and AR13 (any step from 2 on; best with the final bitstream):
- Board powered off. Wire AR_SCK → AR13, AR_MOSI → AR11, AR_SS → AR10. Leave AR12 (READY) and both 3V3/GND pins of the SPI header unconnected.
- Power on, program, SW0 down (the GPU listens to the Arduino connector again).
- Press any test button: the same pictures appear — now through the real pins. Remove the wires before connecting the Arduino.
Write your own tests
Tests are Python functions using the same helpers as the demos (clear, rect, line, circle, fill_circle, swap). Each starts with clear() and ends with swap() — the FPGA build is double buffered, nothing shows before the SWAP.
def r1_hello():
# Hello over SPI - blue screen, white border, HI in block letters
g.clear(g.BLUE)
g.rect(0, 0, W, 1, g.WHITE) # top row
...
g.swap()
STEPS = {
2: ("bringup/step2_rect/selftest.mem", [r1_hello, r2_colours, r3_blocks], {1, 3, 4}),
3: ("bringup/step3_line/selftest.mem", [l1_starburst, l2_string_art, l3_house], {1, 2, 3, 4}),
4: ("fpga/selftest.mem", [c1_target, c2_snowman, c3_edges], {1, 2, 3, 4, 5}),
}- Edit or add a function in
scripts/gen_selftest.pyand put it inSTEPS(three new tests per step; the previous step’s three become tests 4–6 automatically). The script refuses an opcode the step’s core does not have. - Regenerate the ROMs and copy them to the folder Vivado reads:terminalBashWSL
cd ~/asic_projects/raster_gpu python3 scripts/gen_selftest.py cp -r fpga bringup /mnt/c/fpga/raster_gpu/ - Optional but quick: see the result before building —
bash run_sims.shstage 7 keeps the frames inbuild/selftest/step2,step3,step4/board_N.hex; turn one into a PNG withpython3 scripts/hex2png.py fpga build/selftest/step4/board_2.hex snowman.png. - Vivado → Generate Bitstream. It sees the changed
.memand re-runs synthesis. Program, press the button.
▸ Show scripts/gen_selftest.py · 258 lines
#!/usr/bin/env python3
"""
gen_selftest.py - builds the command ROMs of the on-board SPI test host
(fpga/spi_test_host.v), one per bring-up step:
bringup/step2_rect/selftest.mem step 2: SPI + framebuffer + RECT
bringup/step3_line/selftest.mem step 3: + LINE
fpga/selftest.mem step 4: + CIRCLE (the final GPU)
python3 scripts/gen_selftest.py # writes the three ROMs
# + build/selftest/step<S>_test<N>.cmd
On the board (SW0 up), every step works the same way:
test 1 runs by itself after programming / BTN0
SW1 down: BTN1 / BTN2 / BTN3 = tests 1 / 2 / 3 the NEW tests of this step
SW1 up: BTN1 / BTN2 / BTN3 = tests 4 / 5 / 6 the tests of the step
before (regression: the new
engine must not break the
old ones). Empty in step 2.
A ROM only contains commands its step's gpu_core can draw.
Each test is a list of 80-bit commands followed by an all-zero word.
To add your own test: write a function like the ones below (same helpers as
the demos: clear, rect, line, circle, fill_circle, swap), put it in STEPS,
run this script, then rebuild the bitstream in Vivado (the .mem file is read
when the bitstream is built). Start every test with clear() and end it with
swap(): the FPGA build is double buffered, nothing shows before the SWAP.
"""
import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import gen_demo as g
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROM_DEPTH = 256
g.setup("fpga")
W, H = g.W, g.H # 320 x 240
# a few extra RGB332 colours (RRRGGGBB)
SKY, GRASS, CREAM, BROWN = 0x53, 0x0C, 0xF9, 0x88
NIGHT, MOON, GLASS = 0x02, 0xFD, 0x9F
# ================================================================ step 2: RECT
# CLEAR, RECT and SWAP only.
def r1_hello():
"""Hello over SPI - blue screen, 1-pixel white border, "HI" in block letters."""
g.clear(g.BLUE)
g.rect(0, 0, W, 1, g.WHITE) # top row 0
g.rect(0, H - 1, W, 1, g.WHITE) # bottom row 239
g.rect(0, 0, 1, H, g.WHITE) # left column 0
g.rect(W - 1, 0, 1, H, g.WHITE) # right column 319
x, y, s, h = 90, 80, 16, 80 # letter origin, stroke, height
g.rect(x, y, s, h, g.WHITE) # H: left bar
g.rect(x + 44, y, s, h, g.WHITE) # right bar
g.rect(x, y + 32, 60, s, g.WHITE) # middle
x = 170
g.rect(x, y, 60, s, g.WHITE) # I: top
g.rect(x + 22, y, s, h, g.WHITE) # stem
g.rect(x, y + h - s, 60, s, g.WHITE) # bottom
g.swap()
def r2_colours():
"""Colours and sizes - 8 colour bars, a grey band, squares from 32x32 down to 1x1."""
g.clear(g.BLACK)
bw = W // 8
for i in range(8):
g.rect(i * bw, 0, bw, H // 2, g.PALETTE[i])
g.rect(0, H // 2, W, H // 6, g.GREY)
cx, cy = W // 2, (H * 5) // 6
for i, sz in enumerate((32, 24, 16, 8, 2, 1)):
g.rect(cx - sz // 2, cy - sz // 2, sz, sz, g.PALETTE[i])
g.swap()
def r3_blocks():
"""Blocks off the edges - a Mondrian-style composition whose blocks and bars
run off all four edges (clipping); two rectangles that must draw nothing."""
g.clear(g.WHITE)
g.rect(-40, -30, 160, 120, g.RED) # off the top-left corner
g.rect(226, 186, 140, 100, g.BLUE) # off the bottom-right corner
g.rect(226, -20, 120, 70, g.YELLOW) # off top and right
g.rect(-20, 186, 146, 80, g.YELLOW) # off left and bottom
g.rect(126, 96, 100, 90, g.BLUE) # fully inside
g.rect(120, -100, 6, 500, g.BLACK) # vertical bars, both ends off
g.rect(220, -100, 6, 500, g.BLACK)
g.rect(-100, 90, 600, 6, g.BLACK) # horizontal bars, both ends off
g.rect(-100, 180, 600, 6, g.BLACK)
g.rect(226, 50, 200, 6, g.BLACK) # short bar off the right edge
g.rect(400, 300, 50, 50, g.RED) # fully off screen: nothing
g.rect(60, 130, 0, 40, g.RED) # width 0: nothing
g.swap()
# ================================================================ step 3: LINE
def l1_starburst():
"""Starburst - 32 rays from the centre in every direction (all 8 octants),
a frame drawn with 4 lines, both diagonals."""
g.clear(g.BLACK)
cx, cy, r = W // 2, H // 2, H // 2 - 4
for i in range(32):
a = i * 2 * math.pi / 32
g.line(cx, cy, g.ctrunc(cx + r * math.cos(a)), g.ctrunc(cy + r * math.sin(a)), g.PALETTE[i % 7])
g.line(0, 0, W - 1, 0, g.WHITE); g.line(W - 1, 0, W - 1, H - 1, g.WHITE)
g.line(W - 1, H - 1, 0, H - 1, g.WHITE); g.line(0, H - 1, 0, 0, g.WHITE)
g.line(0, 0, W - 1, H - 1, g.GREY); g.line(W - 1, 0, 0, H - 1, g.GREY)
g.swap()
def l2_string_art():
"""String art - 52 straight lines whose ends walk along the screen edges;
together they bend into a smooth curve in each corner."""
g.clear(g.BLACK)
n, xm, ym = 12, W - 1, H - 1
for i in range(n + 1):
t = i / n
x, y = round(t * xm), round(t * ym)
xr, yr = round((1 - t) * xm), round((1 - t) * ym)
g.line(0, y, xr, 0, g.CYAN) # top-left corner
g.line(xm, y, x, 0, g.MAGENTA) # top-right corner
g.line(0, yr, xr, ym, g.YELLOW) # bottom-left corner
g.line(xm, yr, x, ym, g.GREEN) # bottom-right corner
g.swap()
def l3_house():
"""House - rectangles and lines together: walls, door, windows, a hatched
roof, a sun in the corner with rays and a road whose lines start far off
screen (line clipping)."""
g.clear(SKY)
for dx, dy in ((-1, 0), (-3, 1), (-1, 1), (-1, 3), (0, 1)):
g.line(300, 20, 300 + dx * 400, 20 + dy * 400, g.YELLOW) # sun rays leave the screen
g.rect(268, -12, 64, 64, g.YELLOW) # sun, off the top-right corner
g.rect(-20, 190, 360, 70, GRASS) # ground, off 3 edges
g.line(-400, 300, 150, 190, g.WHITE) # road: both lines start
g.line(720, 300, 170, 190, g.WHITE) # below and beside the screen
g.rect(100, 110, 120, 80, CREAM) # walls
g.rect(196, 60, 14, 40, BROWN) # chimney
g.line(90, 110, 160, 56, g.RED) # roof outline
g.line(160, 56, 230, 110, g.RED)
g.line(90, 110, 230, 110, g.RED)
for x in range(100, 230, 10): # roof hatching
g.line(160, 56, x, 110, g.RED)
g.rect(148, 146, 24, 44, BROWN) # door
for wx in (114, 186): # windows with crosses
g.rect(wx - 12, 126, 24, 24, GLASS)
g.line(wx, 126, wx, 149, g.WHITE)
g.line(wx - 12, 138, wx + 11, 138, g.WHITE)
g.swap()
# ================================================================ step 4: CIRCLE
def c1_target():
"""Target and rings - a filled target, 8 outlines, bubbles cut by the bottom edge."""
g.circles()
def c2_snowman():
"""Snowman at night - every engine in one picture: a crescent moon (two
filled circles, cut by the top edge), snowman, hat, scarf, stick arms,
snowflakes of radius 0 and 1."""
g.clear(NIGHT)
g.fill_circle(292, 22, 40, MOON) # moon ...
g.fill_circle(310, 10, 38, NIGHT) # ... minus a circle = crescent
g.rect(-10, 200, 340, 50, g.WHITE) # snow on the ground
g.fill_circle(160, 170, 40, g.WHITE) # body
g.fill_circle(160, 113, 28, g.WHITE)
g.fill_circle(160, 70, 19, g.WHITE) # head
g.rect(138, 50, 44, 4, g.BLACK) # hat brim
g.rect(148, 24, 24, 26, g.BLACK) # hat
g.fill_circle(153, 66, 2, g.BLACK) # eyes
g.fill_circle(167, 66, 2, g.BLACK)
g.rect(160, 71, 12, 3, g.ORANGE) # nose
g.rect(141, 86, 38, 6, g.RED) # scarf
for y in (104, 116, 128): # buttons
g.fill_circle(160, y, 3, g.BLACK)
g.line(134, 108, 96, 82, BROWN) # arms
g.line(96, 82, 86, 74, BROWN)
g.line(186, 108, 224, 84, BROWN)
g.line(224, 84, 236, 78, BROWN)
for i, (x, y) in enumerate(((30, 40), (70, 110), (40, 170), (110, 30),
(230, 140), (270, 100), (290, 175), (215, 30))):
g.circle(x, y, i & 1, g.WHITE) # r = 0: one pixel, r = 1: a ring
g.swap()
def c3_edges():
"""Edges and extremes - every shape partly or fully off every edge, a huge
circle (r = 1000) whose centre is far below the screen, r = 0 and r = 1.
Nothing may wrap around to the other side."""
g.clear(g.BLACK)
g.rect(0, 0, W, 1, g.GREEN); g.rect(0, H - 1, W, 1, g.GREEN)
g.rect(0, 0, 1, H, g.GREEN); g.rect(W - 1, 0, 1, H, g.GREEN)
g.rect(-40, 20, 80, 40, g.RED) # off the left edge
g.rect(W - 40, 20, 80, 40, g.YELLOW) # off the right edge
g.line(-50, H // 2, W + 50, H // 2 + 30, g.ORANGE) # both ends off screen
g.circle(W // 2, H + 900, 1000, g.CYAN) # top of a huge circle: an arc
g.fill_circle(0, H - 1, 50, g.BLUE) # centre on the corner
g.circle(W - 1, H // 2, 60, g.WHITE) # centre on the right edge
g.fill_circle(W // 2, -10, 40, g.MAGENTA) # centre above the screen
g.fill_circle(W // 2, H // 2, 30, g.ORANGE)
g.circle(W // 2, H // 2, 45, g.CYAN)
g.fill_circle(40, 120, 0, g.WHITE) # r = 0: one pixel
g.circle(60, 120, 1, g.WHITE) # r = 1
g.fill_circle(W + 200, H + 200, 100, g.RED) # fully off: draws nothing
g.swap()
# ================================================================ the ROMs
STEPS = {
2: ("bringup/step2_rect/selftest.mem", [r1_hello, r2_colours, r3_blocks], {1, 3, 4}),
3: ("bringup/step3_line/selftest.mem", [l1_starburst, l2_string_art, l3_house], {1, 2, 3, 4}),
4: ("fpga/selftest.mem", [c1_target, c2_snowman, c3_edges], {1, 2, 3, 4, 5}),
}
def build(t):
g.cmds.clear()
t()
if any(w == 0 for w in g.cmds):
sys.exit(f"{t.__name__}: an all-zero command would end the test early")
return list(g.cmds)
def main():
out = os.path.join(ROOT, "build", "selftest")
os.makedirs(out, exist_ok=True)
for step, (path, new, ops) in STEPS.items():
old = STEPS[step - 1][1] if step - 1 in STEPS else []
words = []
print(f"step {step}: {path}")
for n, t in enumerate(new + old + [None] * (3 - len(old)), 1):
cmds = build(t) if t else []
if any((w >> 72) not in ops for w in cmds):
sys.exit(f"step {step} test {n}: uses an opcode this step's gpu_core does not have")
words += cmds + [0]
with open(os.path.join(out, f"step{step}_test{n}.cmd"), "w") as fh:
fh.writelines("%020x\n" % w for w in cmds)
if t:
tag = "new" if n <= 3 else f"regression (step {step - 1})"
print(f" test {n} {t.__name__:14s} {len(cmds):3d} commands [{tag}] {t.__doc__.split(' - ')[0]}")
else:
print(f" test {n} (empty: no earlier step)")
if len(words) > ROM_DEPTH:
sys.exit(f"{len(words)} words do not fit the {ROM_DEPTH}-word ROM")
print(f" {len(words)} of {ROM_DEPTH} ROM words used")
words += [0] * (ROM_DEPTH - len(words))
with open(os.path.join(ROOT, path), "w") as fh:
fh.writelines("%020x\n" % w for w in words)
if __name__ == "__main__":
main()sim/tb_selftest.v runs the real fpga_top (only the Clocking Wizard replaced by a stand-in), compiled three times with exactly the files of step 2, 3 and 4. Each time: the power-up test, BTN1–BTN3 with SW1 down and up, test 2 again in loopback mode — all from the VGA pins, every frame byte-identical to the golden-model frame of the same commands (run_sims.sh stage 7).
If a test does not run
| Symptom | Cause | Fix |
|---|---|---|
| Button does nothing, LD3 keeps blinking | test host never started | BTN0 not held; LD1 on? the step’s selftest.mem in the project? (synthesis warns could not open $readmem data file if not) · in step 2, SW1 must be down |
| LD3 lights and stays on, nothing drawn | GPU not listening, so READY never comes back | SW0 must be up (or the loopback wires in place with SW0 down) |
| Loopback: nothing drawn, works with SW0 up | a wire on the wrong socket | AR_SCK→AR13, AR_MOSI→AR11, AR_SS→AR10; check pin 1 of the SPI header |
| Pictures of the previous step after swapping | the old selftest.mem or gpu_core.v is still in the project | exactly one gpu_core.v and one selftest.mem in Sources; two files with the same name: remove the old one |
| Old picture after editing a test | Vivado still has the old ROM | copied the new .mem to C:\fpga? added with “Copy sources” ticked by mistake? |
Before the Arduino: cross-check every pin and connection by script
Why
A pin plan lives in six places that must agree: fpga_top.v, pynq_gpu.xdc, the sketch, pin_order.cfg, chip_top.v and 01_floorplan.tcl. A single swapped pin in any of them costs an evening of debugging. scripts/check_pins.py reads all six files (plus the step-1 vga_test_top.v / vga_test.xdc and the three test ROMs) and checks them against each other and against the official PYNQ-Z2 pin list. run_sims.sh runs it in stage 8/8.
| Section | Compares | Catches |
|---|---|---|
| [A] FPGA | fpga_top ports ↔ XDC ↔ PYNQ-Z2 pin list (manual tables 9–19 + base overlay), incl. the manual's PMOD P/N names | unconstrained or doubly constrained bits, a pin used twice, a wrong ;# JA2-style comment |
| [A2] Step 1 | vga_test_top ports ↔ vga_test.xdc ↔ pynq_gpu.xdc | the step-1 adapter test using a different pin than the GPU build — then a working checkerboard would prove nothing |
| [B] Arduino | sketch PIN_CS/PIN_READY ↔ the XDC sockets (AR10…AR13) ↔ the test host's SPI-header pins | CS not on AR10/Uno 10, READY on an SPI pin; prints the cable list and the loopback wires |
| [C] Macro | gpu_asic ports ↔ pin_order.cfg | a macro pin left out or placed twice |
| [D] Chip | every pad in chip_top.v (after iverilog -E) | wrong DM/OE_N/INP_DIS for the direction, pad wired to the wrong macro pin, shared tie_lo index, missing power-good |
| [E] Layout | place_pads rows ↔ macro pin sides | a pad missing from the floorplan, or on a different side than its macro pin (long wires across the core) |
| [F] Electrical | divider, READY level, VGA DAC | out-of-spec voltages (PYNQ-Z2 limits from its manual) and the pad current limit |
| [G] Test ROMs | the three selftest.mem (steps 2, 3, 4) | wrong size, a test without CLEAR/SWAP, an opcode the step’s core does not have |
Do
cd ~/asic_projects/raster_gpu
python3 scripts/check_pins.py # exit code 0 = consistentExpected (real output)
▸ Show check_pins.py · full output · 119 lines
[A] FPGA: fpga_top.v <-> pynq_gpu.xdc
ok all 32 port bits constrained exactly once
ok no FPGA pin used twice
ok sysclk -> H16 = sysclk
ok reset -> D19 = BTN0 (comment BTN0)
ok btn[0] -> D20 = BTN1 (comment BTN1)
ok btn[1] -> L20 = BTN2 (comment BTN2)
ok btn[2] -> L19 = BTN3 (comment BTN3)
ok sw[0] -> M20 = SW0 (comment SW0)
ok sw[1] -> M19 = SW1 (comment SW1)
ok led[0] -> R14 = LD0 (comment LD0)
ok led[1] -> P14 = LD1 (comment LD1)
ok led[2] -> N16 = LD2 (comment LD2)
ok led[3] -> M14 = LD3 (comment LD3)
ok vga_hs -> Y19 = JA-2 (comment JA-2)
ok vga_vs -> U19 = JA-8 (comment JA-8)
ok vga_b[0] -> Y17 = JA-4 (comment JA-4)
ok vga_b[1] -> W19 = JA-10 (comment JA-10)
ok vga_b[2] -> Y16 = JA-3 (comment JA-3)
ok vga_b[3] -> W18 = JA-9 (comment JA-9)
ok vga_r[0] -> T10 = JB-4 (comment JB-4)
ok vga_r[1] -> W13 = JB-10 (comment JB-10)
ok vga_r[2] -> T11 = JB-3 (comment JB-3)
ok vga_r[3] -> V12 = JB-9 (comment JB-9)
ok vga_g[0] -> Y14 = JB-2 (comment JB-2)
ok vga_g[1] -> W16 = JB-8 (comment JB-8)
ok vga_g[2] -> W14 = JB-1 (comment JB-1)
ok vga_g[3] -> V16 = JB-7 (comment JB-7)
ok spi_cs_n -> T16 = AR10 (comment AR10)
ok spi_mosi -> R17 = AR11 (comment AR11)
ok spi_sck -> N17 = AR13 (comment AR13)
ok gpu_ready -> P18 = AR12 (comment AR12)
ok test_cs_n -> F16 = AR_SS (comment AR_SS)
ok test_sck -> H15 = AR_SCK (comment AR_SCK)
ok test_mosi -> T12 = AR_MOSI (comment AR_MOSI)
ok 14 PMOD comments: physical pin <-> manual name (e.g. JA-2 = JA1_N) all consistent
[A2] bring-up step 1: vga_test_top.v <-> vga_test.xdc (same pins as pynq_gpu.xdc)
ok all 25 port bits constrained exactly once
ok every step-1 pin is identical to pynq_gpu.xdc (same adapter, buttons, LEDs)
[B] Arduino sketch <-> PYNQ Arduino header
Uno D13 (hw SCK) <-> PYNQ-Z2 AR13 spi_sck
Uno D11 (hw MOSI) <-> PYNQ-Z2 AR11 spi_mosi
Uno D10 (CS) <-> PYNQ-Z2 AR10 spi_cs_n
Uno D8 (READY in) <-> PYNQ-Z2 AR12 gpu_ready
ok sketch CS = Uno D10 (SS) and READY on a free GPIO (D8)
ok PYNQ-Z2 side uses the shield SPI sockets AR10 / AR11 / AR13 (same positions as Uno D10 / D11 / D13)
loopback wire: AR_SS (test_cs_n) -> AR10 (spi_cs_n)
loopback wire: AR_SCK (test_sck) -> AR13 (spi_sck)
loopback wire: AR_MOSI (test_mosi) -> AR11 (spi_mosi)
ok test host SPI goes out on the SPI header AR_SS / AR_SCK / AR_MOSI
[C] gpu_asic ports <-> pin_order.cfg
ok all 11 macro pins placed exactly once
clk side S
gpu_ready side E
rst_n side S
spi_cs_n side W
spi_mosi side W
spi_sck side W
vga_hs side E
vga_rgb[0] side N
vga_rgb[1] side N
vga_rgb[2] side N
vga_vs side E
[D] chip_top.v pad configuration and macro hookup
ok 11 signal GPIOs (+ u_power_good)
ok u_b OUT pad_rgb[0] <-> macro vga_rgb[0] (DM {cfg_hi,cfg_hi,cfg_lo})
ok u_clk IN pad_clk <-> macro clk (DM {cfg_lo,cfg_lo,cfg_hi})
ok u_cs_n IN pad_cs_n <-> macro spi_cs_n (DM {cfg_lo,cfg_lo,cfg_hi})
ok u_g OUT pad_rgb[1] <-> macro vga_rgb[1] (DM {cfg_hi,cfg_hi,cfg_lo})
ok u_hs OUT pad_hs <-> macro vga_hs (DM {cfg_hi,cfg_hi,cfg_lo})
ok u_mosi IN pad_mosi <-> macro spi_mosi (DM {cfg_lo,cfg_lo,cfg_hi})
ok u_r OUT pad_rgb[2] <-> macro vga_rgb[2] (DM {cfg_hi,cfg_hi,cfg_lo})
ok u_ready OUT pad_ready <-> macro gpu_ready (DM {cfg_hi,cfg_hi,cfg_lo})
ok u_rst_n IN pad_rst_n <-> macro rst_n (DM {cfg_lo,cfg_lo,cfg_hi})
ok u_sck IN pad_sck <-> macro spi_sck (DM {cfg_lo,cfg_lo,cfg_hi})
ok u_vs OUT pad_vs <-> macro vga_vs (DM {cfg_hi,cfg_hi,cfg_lo})
ok every GPIO uses its own tie_lo[] index
ok u_power_good drives por_h / por_lv and keeps its own input enabled
ok macro VPWR/VGND -> VCCD/VSSD
ok 6 supply pads: u_vccd u_vdda u_vddio u_vssa u_vssd u_vssio
[E] 01_floorplan.tcl pad sides <-> macro pin sides
ok all 18 pads placed exactly once
ok u_clk on SOUTH <-> macro clk on side S
ok u_rst_n on SOUTH <-> macro rst_n on side S
ok u_cs_n on WEST <-> macro spi_cs_n on side W
ok u_sck on WEST <-> macro spi_sck on side W
ok u_mosi on WEST <-> macro spi_mosi on side W
ok u_ready on EAST <-> macro gpu_ready on side E
ok u_hs on EAST <-> macro vga_hs on side E
ok u_vs on EAST <-> macro vga_vs on side E
ok u_r on NORTH <-> macro vga_rgb[2] on side N
ok u_g on NORTH <-> macro vga_rgb[1] on side N
ok u_b on NORTH <-> macro vga_rgb[0] on side N
[F] Electrical: level dividers (FPGA) and VGA DAC (ASIC board)
ok divider 2.2k/3.3k: 5 V -> 3.00 V (VIH >= 2.0 V; PYNQ-Z2 header: 3.4 V recommended max, 3.75 V abs. max)
ok divider source 1320 ohm, 10-90 % rise 29 ns << 250 ns SCK half period
ok READY 3.3 V >= ATmega328P VIH (0.6 x 5 V = 3.0 V)
ok 3.3 V through 270 ohm into 75 ohm = 0.717 V (VGA full scale 0.7 V)
ok DAC current 9.6 mA: above the 4 mA GPIO pad rating -> driven by a 74LVC244A (24 mA)
[G] on-board test ROMs (one selftest.mem per bring-up step)
ok bringup/step2_rect/selftest.mem: 256 words, 6 test slots, 49 words used
ok bringup/step2_rect/selftest.mem: only opcodes [1, 3, 4] (what this step's gpu_core draws)
ok bringup/step2_rect/selftest.mem: tests 1-3 new, 4-6 empty (no earlier step); every test starts with CLEAR and ends with SWAP
ok bringup/step3_line/selftest.mem: 256 words, 6 test slots, 179 words used
ok bringup/step3_line/selftest.mem: only opcodes [1, 2, 3, 4] (what this step's gpu_core draws)
ok bringup/step3_line/selftest.mem: tests 1-3 new, 4-6 = previous step; every test starts with CLEAR and ends with SWAP
ok fpga/selftest.mem: 256 words, 6 test slots, 207 words used
ok fpga/selftest.mem: only opcodes [1, 2, 3, 4, 5] (what this step's gpu_core draws)
ok fpga/selftest.mem: tests 1-3 new, 4-6 = previous step; every test starts with CLEAR and ends with SWAP
RESULT: ALL CONNECTIONS CONSISTENT[A] FPGA: fpga_top.v <-> pynq_gpu.xdc
ok all 32 port bits constrained exactly once
ok 14 PMOD comments: physical pin <-> manual name (e.g. JA-2 = JA1_N) all consistent
[A2] bring-up step 1: vga_test_top.v <-> vga_test.xdc (same pins as pynq_gpu.xdc)
ok all 25 port bits constrained exactly once
[B] Arduino sketch <-> PYNQ Arduino header
[C] gpu_asic ports <-> pin_order.cfg
ok all 11 macro pins placed exactly once
[D] chip_top.v pad configuration and macro hookup
[E] 01_floorplan.tcl pad sides <-> macro pin sides
ok all 18 pads placed exactly once
[F] Electrical: level dividers (FPGA) and VGA DAC (ASIC board)
ok DAC current 9.6 mA: above the 4 mA GPIO pad rating -> driven by a 74LVC244A (24 mA)
[G] on-board test ROMs (one selftest.mem per bring-up step)
RESULT: ALL CONNECTIONS CONSISTENTTested by breaking copies on purpose: moving gpu_ready to N17 gives no FPGA pin used twice + gpu_ready → N17 = AR13 (comment AR12); moving u_b to the east row gives u_b on EAST ↔ macro vga_rgb[0] on side N.
▸ Show scripts/check_pins.py · 216 lines
#!/usr/bin/env python3
"""
check_pins.py - cross-checks every pin / connection in the project.
cd ~/asic_projects/raster_gpu
python3 scripts/check_pins.py
A. FPGA : every fpga_top port bit is constrained exactly once in the XDC,
(A2: the step-1 vga_test_top / vga_test.xdc use the same pins)
no pin is used twice, every pin is a real PYNQ-Z2 pin with the
connector label written in the XDC comment
B. Arduino: the sketch pins + the XDC header sockets form the wiring table;
the on-board test host drives the SPI header (loopback wires)
C. Macro : pin_order.cfg places every gpu_asic signal port exactly once
D. Chip : every GPIO pad in chip_top.v is configured for its direction
(DM / OE_N / INP_DIS), drives / is driven by the right macro
pin, has its own tie_lo[] index, and is enabled by power-good
E. Layout : 01_floorplan.tcl places every pad once, on the same die side as
the macro pin it is wired to
F. Electr.: divider level + rise time, READY level at the Uno, VGA DAC
level and why the ASIC board needs a buffer after the pads
G. ROMs : the three selftest.mem files (bring-up steps 2, 3, 4) fit the
test host ROM and use only the opcodes their gpu_core has
Exit code 0 = everything consistent.
"""
import os, re, subprocess, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def rd(p): return open(os.path.join(ROOT, p), encoding='utf-8').read()
errors = []
def check(cond, msg):
print((' ok ' if cond else ' FAIL ') + msg)
if not cond: errors.append(msg)
# Official PYNQ-Z2 PL pins and their board labels (PYNQ-Z2 reference manual,
# tables 16-19, and the base overlay constraints). The Arduino header sockets
# are labelled AR0..AR13 on the PYNQ-Z2 (not D0..D13 as on an Uno).
PYNQ = {'H16': 'sysclk', 'D19': 'BTN0', 'D20': 'BTN1', 'L20': 'BTN2', 'L19': 'BTN3', 'M20': 'SW0', 'M19': 'SW1',
'R14': 'LD0', 'P14': 'LD1', 'N16': 'LD2', 'M14': 'LD3',
# PMOD labels: <connector>-<physical pin> (the manual's names in brackets in the XDC)
'Y18': 'JA-1', 'Y19': 'JA-2', 'Y16': 'JA-3', 'Y17': 'JA-4', 'U18': 'JA-7', 'U19': 'JA-8', 'W18': 'JA-9', 'W19': 'JA-10',
'W14': 'JB-1', 'Y14': 'JB-2', 'T11': 'JB-3', 'T10': 'JB-4', 'V16': 'JB-7', 'W16': 'JB-8', 'V12': 'JB-9', 'W13': 'JB-10',
'T14': 'AR0', 'U12': 'AR1', 'U13': 'AR2', 'V13': 'AR3', 'V15': 'AR4', 'T15': 'AR5', 'R16': 'AR6', 'U17': 'AR7',
'V17': 'AR8', 'V18': 'AR9', 'T16': 'AR10', 'R17': 'AR11', 'P18': 'AR12', 'N17': 'AR13',
'Y13': 'A', 'P16': 'AR_SDA', 'P15': 'AR_SCL',
'W15': 'AR_MISO', 'H15': 'AR_SCK', 'T12': 'AR_MOSI', 'F16': 'AR_SS'}
def ports_of(verilog, module):
"""{name: (dir, width)} from an ANSI-style module header."""
m = re.search(r'module\s+' + module + r'\s*(?:#\(.*?\))?\s*\((.*?)\);', verilog, re.S)
body = re.sub(r'//[^\n]*', '', m.group(1))
body = re.sub(r'`ifdef USE_POWER_PINS.*?`endif', '', body, flags=re.S)
out = {}
for d, rng, names in re.findall(r'(input|output|inout)\s+(?:wire|reg)?\s*(\[\d+:\d+\])?\s*([\w\s,]+?)(?=,\s*(?:input|output|inout)|$)', body.strip(), re.S):
w = 1
if rng:
a, b = map(int, rng[1:-1].split(':')); w = abs(a - b) + 1
for n in [x.strip() for x in names.split(',') if x.strip()]:
out[n] = (d, w)
return out
# ======================================================================= A
print('\n[A] FPGA: fpga_top.v <-> pynq_gpu.xdc')
top = ports_of(rd('fpga/fpga_top.v'), 'fpga_top')
xdc = rd('fpga/pynq_gpu.xdc')
cons = re.findall(r'PACKAGE_PIN\s+(\w+).*?get_ports\s+\{?([\w\[\]]+)\}?\]\s*(?:;#\s*(\S+))?', xdc)
bits_needed = {f'{n}[{i}]' if w > 1 else n for n, (d, w) in top.items() for i in range(w)}
bits_have = [p for _, p, _ in cons]
check(sorted(bits_needed) == sorted(set(bits_have)) and len(bits_have) == len(set(bits_have)),
f'all {len(bits_needed)} port bits constrained exactly once')
pins = [pin for pin, _, _ in cons]
check(len(pins) == len(set(pins)), 'no FPGA pin used twice')
for pin, port, cmt in cons:
lab = PYNQ.get(pin)
check(lab is not None and (not cmt or cmt == lab), f'{port:11s} -> {pin:4s} = {lab}' + (f' (comment {cmt})' if cmt else ''))
# PMOD pins: the manual's P/N signal name in brackets must match the physical pin
# (manual tables 13/14: pins 1/2 = J?1_P/N, 3/4 = J?2_P/N, 7/8 = J?3_P/N, 9/10 = J?4_P/N)
PAIR = {1: '1_P', 2: '1_N', 3: '2_P', 4: '2_N', 7: '3_P', 8: '3_N', 9: '4_P', 10: '4_N'}
pm = re.findall(r';#\s*(J[AB])-(\d+)\s*\((J[AB]\d_[PN])\)', xdc)
check(len(pm) == 14 and all(nm == c + PAIR[int(n)] for c, n, nm in pm),
f'{len(pm)} PMOD comments: physical pin <-> manual name (e.g. JA-2 = JA1_N) all consistent')
# ======================================================================= A2
print('\n[A2] bring-up step 1: vga_test_top.v <-> vga_test.xdc (same pins as pynq_gpu.xdc)')
vt = ports_of(rd('bringup/step1_vga/vga_test_top.v'), 'vga_test_top')
xdc0 = rd('bringup/step1_vga/vga_test.xdc')
cons0 = re.findall(r'PACKAGE_PIN\s+(\w+).*?get_ports\s+\{?([\w\[\]]+)\}?\]\s*(?:;#\s*(\S+))?', xdc0)
need0 = {f'{n}[{i}]' if w > 1 else n for n, (d, w) in vt.items() for i in range(w)}
have0 = [p for _, p, _ in cons0]
check(sorted(need0) == sorted(set(have0)) and len(have0) == len(set(have0)), f'all {len(need0)} port bits constrained exactly once')
main = {port: pin for pin, port, _ in cons}
check(all(main.get(port) == pin for pin, port, _ in cons0), 'every step-1 pin is identical to pynq_gpu.xdc (same adapter, buttons, LEDs)')
# ======================================================================= B
print('\n[B] Arduino sketch <-> PYNQ Arduino header')
ino = rd('arduino/gpu_demo/gpu_demo.ino')
cs = int(re.search(r'const\s+\w+\s+PIN_CS\s*=\s*(\d+)', ino).group(1))
rdy = int(re.search(r'const\s+\w+\s+PIN_READY\s*=\s*(\d+)', ino).group(1))
sock = {port: PYNQ[pin] for pin, port, _ in cons if re.fullmatch(r'AR\d+', PYNQ.get(pin, ''))}
wiring = [('D13 (hw SCK)', sock['spi_sck'], 'spi_sck'), ('D11 (hw MOSI)', sock['spi_mosi'], 'spi_mosi'),
(f'D{cs} (CS)', sock['spi_cs_n'], 'spi_cs_n'), (f'D{rdy} (READY in)', sock['gpu_ready'], 'gpu_ready')]
for a, s, sig in wiring:
print(f' Uno {a:15s} <-> PYNQ-Z2 {s:5s} {sig}')
check(cs == 10 and rdy not in (10, 11, 12, 13), 'sketch CS = Uno D10 (SS) and READY on a free GPIO (D8)')
check(sock['spi_cs_n'] == 'AR10' and sock['spi_mosi'] == 'AR11' and sock['spi_sck'] == 'AR13',
'PYNQ-Z2 side uses the shield SPI sockets AR10 / AR11 / AR13 (same positions as Uno D10 / D11 / D13)')
# on-board test host: drives the 2x3 SPI header, loopback wires go to the AR sockets
hdr = {port: PYNQ[pin] for pin, port, _ in cons if PYNQ.get(pin, '').startswith('AR_')}
loop = [('test_cs_n', 'spi_cs_n'), ('test_sck', 'spi_sck'), ('test_mosi', 'spi_mosi')]
for src, dst in loop:
print(f' loopback wire: {hdr.get(src, "?"):7s} ({src}) -> {sock[dst]:4s} ({dst})')
check(hdr.get('test_cs_n') == 'AR_SS' and hdr.get('test_sck') == 'AR_SCK' and hdr.get('test_mosi') == 'AR_MOSI',
'test host SPI goes out on the SPI header AR_SS / AR_SCK / AR_MOSI')
# ======================================================================= C
print('\n[C] gpu_asic ports <-> pin_order.cfg')
asic = ports_of(rd('asic/src/gpu_asic.v'), 'gpu_asic')
cfg = rd('asic/pin_order.cfg')
side, side_of = None, {}
for line in cfg.splitlines():
line = line.strip()
if line.startswith('#'): side = line[1]; continue
if line: side_of.setdefault(line.replace('\\', ''), side)
asic_bits = {f'{n}[{i}]' if w > 1 else n for n, (d, w) in asic.items() for i in range(w)}
check(set(side_of) == asic_bits, f'all {len(asic_bits)} macro pins placed exactly once')
for b in sorted(asic_bits):
print(f' {b:12s} side {side_of.get(b)}')
# ======================================================================= D
print('\n[D] chip_top.v pad configuration and macro hookup')
exp = subprocess.run(['iverilog', '-E', '-o', '-', os.path.join(ROOT, 'chip/rtl/chip_top.v')],
capture_output=True, text=True, check=True).stdout
INST_RE = r'(sky130_ef_io__\w+|sky130_fd_sc_hd__conb_1|gpu_asic)\s+(\w+)\s*\((.*?)\);'
insts = {i: (c, b) for c, i, b in re.findall(INST_RE, exp, re.S)}
def conns(body):
return {p: re.sub(r'\s+', '', v) for p, v in re.findall(r'\.(\w+)\s*\(([^()]*)\)', body)}
core = conns(insts['u_core'][1])
net2pin = {}
for p, v in core.items(): # expand buses: .vga_rgb(rgb) -> rgb[i] = vga_rgb[i]
w = asic.get(p, ('', 1))[1]
if w > 1:
for i in range(w): net2pin[f'{v}[{i}]'] = f'{p}[{i}]'
else:
net2pin[v] = p
gpios = {i: conns(b) for i, (c, b) in insts.items() if c == 'sky130_ef_io__gpiov2_pad_wrapped' and i != 'u_power_good'}
check(len(gpios) == 11, f'{len(gpios)} signal GPIOs (+ u_power_good)')
ties = []
pad_to_macro = {}
for name, c in sorted(gpios.items()):
is_out = c.get('OUT') not in (None, 'cfg_lo')
net = c['OUT'] if is_out else c['IN']
mpin = net2pin.get(net)
want_dir = 'output' if is_out else 'input'
mdir = asic.get(re.sub(r'\[\d+\]', '', mpin or ''), ('?',))[0]
cfg_ok = (c['DM'] == '{cfg_hi,cfg_hi,cfg_lo}' and c['OE_N'] == 'cfg_lo' and c['INP_DIS'] == 'cfg_hi') if is_out else \
(c['DM'] == '{cfg_lo,cfg_lo,cfg_hi}' and c['OE_N'] == 'cfg_hi' and c['INP_DIS'] == 'cfg_lo')
en_ok = c['ENABLE_H'] == 'por_h' and c['ENABLE_VDDIO'] == 'por_lv'
tie = c['TIE_LO_ESD']; ties.append(tie)
tie_ok = c['ENABLE_INP_H'] == tie and c['ENABLE_VDDA_H'] == tie and c['ENABLE_VSWITCH_H'] == tie
pad_to_macro[name] = mpin or '?'
check(mpin is not None and mdir == want_dir and cfg_ok and en_ok and tie_ok,
f'{name:8s} {"OUT" if is_out else "IN ":3s} {c["PAD"]:12s} <-> macro {mpin} (DM {c["DM"]})')
check(len(set(ties)) == len(ties), 'every GPIO uses its own tie_lo[] index')
pg = conns(insts['u_power_good'][1])
check(pg['IN_H'] == 'por_h' and pg['IN'] == 'por_lv' and pg['ENABLE_INP_H'] == pg['TIE_HI_ESD'],
'u_power_good drives por_h / por_lv and keeps its own input enabled')
check(core.get('VPWR') == 'VCCD' and core.get('VGND') == 'VSSD', 'macro VPWR/VGND -> VCCD/VSSD')
supplies = {i: c for i, (c, b) in insts.items() if 'clamped_pad' in c}
check(len(supplies) == 6, f'{len(supplies)} supply pads: ' + ' '.join(sorted(supplies)))
# ======================================================================= E
print('\n[E] 01_floorplan.tcl pad sides <-> macro pin sides')
fp = rd('chip/tcl/01_floorplan.tcl')
rows = {s: l.split() for s, l in re.findall(r'^place_pads\s+-row\s+IO_(\w+)\s+-mode\s+uniform\s+\{([^}]*)\}', fp, re.M)}
placed = [p for l in rows.values() for p in l]
all_pads = [i for i, (c, b) in insts.items() if c.startswith('sky130_ef_io__')]
check(sorted(placed) == sorted(all_pads), f'all {len(all_pads)} pads placed exactly once')
S = {'NORTH': 'N', 'SOUTH': 'S', 'EAST': 'E', 'WEST': 'W'}
for row, pads in rows.items():
for p in pads:
if p in pad_to_macro:
mside = side_of.get(pad_to_macro[p])
check(mside == S[row], f'{p:8s} on {row:5s} <-> macro {pad_to_macro[p]} on side {mside}')
# ======================================================================= F
print('\n[F] Electrical: level dividers (FPGA) and VGA DAC (ASIC board)')
v_div = 5.0 * 3.3 / (2.2 + 3.3) # Uno 5 V -> PYNQ 3.3 V input
check(2.0 <= v_div <= 3.4, f'divider 2.2k/3.3k: 5 V -> {v_div:.2f} V (VIH >= 2.0 V; PYNQ-Z2 header: 3.4 V recommended max, 3.75 V abs. max)')
r_th = 2.2e3 * 3.3e3 / (2.2e3 + 3.3e3); t_r = 2.2 * r_th * 10e-12
check(t_r < 0.25 * 0.5 / 2e6, f'divider source {r_th:.0f} ohm, 10-90 % rise {t_r*1e9:.0f} ns << 250 ns SCK half period')
check(3.3 >= 0.6 * 5.0, 'READY 3.3 V >= ATmega328P VIH (0.6 x 5 V = 3.0 V)')
v = 3.3 * 75 / (270 + 75); i = 3.3 / (270 + 75)
check(0.6 <= v <= 0.75, f'3.3 V through 270 ohm into 75 ohm = {v:.3f} V (VGA full scale 0.7 V)')
check(i > 4e-3 and i < 24e-3, f'DAC current {i*1e3:.1f} mA: above the 4 mA GPIO pad rating -> driven by a 74LVC244A (24 mA)')
print('\n[G] on-board test ROMs (one selftest.mem per bring-up step)')
for path, ops, empty_ok in (('bringup/step2_rect/selftest.mem', {1, 3, 4}, True),
('bringup/step3_line/selftest.mem', {1, 2, 3, 4}, False),
('fpga/selftest.mem', {1, 2, 3, 4, 5}, False)):
words = [int(l, 16) for l in rd(path).split()]
tests, cur = [], []
for w in words:
if len(tests) == 6: break
if w == 0: tests.append(cur); cur = []
else: cur.append(w >> 72)
used = sum(len(t) for t in tests) + 6
ok_ops = all(op in ops for t in tests for op in t)
nonempty = [len(t) > 0 for t in tests]
shape = all(nonempty[:3]) and (all(nonempty[3:]) or (empty_ok and not any(nonempty[3:])))
check(len(words) == 256 and len(tests) == 6, f'{path}: 256 words, 6 test slots, {used} words used')
check(ok_ops, f'{path}: only opcodes {sorted(ops)} (what this step\'s gpu_core draws)')
check(shape and all(t[0] == 1 and t[-1] == 4 for t in tests if t), f'{path}: tests 1-3 new' + (', 4-6 empty (no earlier step)' if empty_ok else ', 4-6 = previous step') + '; every test starts with CLEAR and ends with SWAP')
print('\nRESULT:', 'ALL CONNECTIONS CONSISTENT' if not errors else f'{len(errors)} PROBLEM(S)')
sys.exit(1 if errors else 0)Parts list for the FPGA setup
Everything you need on the desk before wiring. Items 1–3 you already have from your old GPU project; the rest is a few euros.
| # | Part | Qty | Exact spec | Used for |
|---|---|---|---|---|
| 1 | PYNQ-Z2 + micro-USB cable | 1 | data-capable cable (not charge-only); power jumper on USB, boot jumper on JTAG | runs the GPU bitstream |
| 2 | Your VGA video adapter | 1 | 12-bit RGB444 resistor DAC on PMOD A + PMOD B (unchanged) | turns 4-bit colours into 0–0.7 V |
| 3 | VGA cable + monitor | 1 | must accept 640 × 480 @ 60 Hz (almost all VGA monitors do); an HDMI-only monitor needs an active VGA→HDMI converter | shows the picture |
| 4 | Arduino Uno R3 (or Nano) + USB cable | 1 | ATmega328P, 16 MHz, 5 V logic · USB-B for the Uno, mini/micro/USB-C for Nano clones | host that sends commands |
| 5 | Resistor 2.2 kΩ | 3 | ¼ W, 5 % carbon film · bands red red red gold | series arm of each divider |
| 6 | Resistor 3.3 kΩ | 3 | ¼ W, 5 % · bands orange orange red gold | lower arm (to GND) of each divider |
| 7 | Breadboard | 1 | half size, 400 tie points (any size works) | holds the three dividers |
| 8 | Jumper wires, male–male | 9 used | 10–15 cm; buy a pack of 20+. Both the Uno headers and the PYNQ-Z2 sockets are female, so male–male everywhere | connections (counted below) |
| 9 | Multimeter | 1 | DC volts; a Hz range is a bonus (checks HSYNC/VSYNC) | checking the dividers before connecting |
The 9 jumpers, counted
| # | From | To | Suggested colour |
|---|---|---|---|
| 1 | Uno pin 13 | breadboard column 2 | yellow (SCK) |
| 2 | breadboard column 6 | PYNQ AR13 | yellow |
| 3 | Uno pin ~11 | breadboard column 9 | green (MOSI) |
| 4 | breadboard column 13 | PYNQ AR11 | green |
| 5 | Uno pin ~10 | breadboard column 16 | blue (CS) |
| 6 | breadboard column 20 | PYNQ AR10 | blue |
| 7 | Uno pin 8 | PYNQ AR12 | red/orange (READY) — direct, no breadboard |
| 8 | Uno GND | breadboard − rail | black |
| 9 | PYNQ GND (J3 pin 7, next to AR13) | breadboard − rail | black |
The three 3.3 kΩ resistors plug straight from their column into the − rail, so they need no wires.
Optional, but useful
| Part | Why you might want it |
|---|---|
| 3.3 V board instead of the Uno: ESP32 DevKitC, Raspberry Pi Pico, Arduino Nano 33 IoT | no dividers at all — 4 direct wires + GND (pin changes in Step 29) |
| Logic analyser, 8 channels / 24 MHz (fx2-based) + PulseView (sigrok) | decodes SPI frames: you can see every 10-byte command and the READY handshake |
| TXS0108E level-shifter module | alternative to the dividers (not the BSS138 type — too slow above ~1 MHz) |
| E12 resistor kit | 1.8 k + 3.3 k, 1 k + 2 k or 10 k + 20 k (slow!) also make 5 V → 3.0–3.3 V |
| 3 more jumper wires | for the loopback test in Step 26 (SPI header → AR sockets) |
Wire the Arduino to the PYNQ-Z2
The PYNQ-Z2 Arduino connector is 3.3 V only: 3.4 V recommended maximum, 3.75 V absolute (reference manual, table 15). An Uno/Nano drives 5 V. Use the dividers below, or a 3.3 V board (Nano 33, Pico, ESP32) wired directly. Remove the joystick shield and any loopback wires first.
Every pin of every connector, with idle levels and a pre-power checklist, is in Step 18.
Pin for pin
Only four signals and ground cross between the boards. Three go into the FPGA (5 V → divider → 3.0 V) and one comes out of the FPGA (3.3 V, straight into the Uno):
Schematic
On the breadboard
Why these values work — the numbers
| Quantity | Value | Requirement | OK? |
|---|---|---|---|
| Divider output, Arduino HIGH | 5 V × 3.3 / (2.2 + 3.3) = 3.00 V | VIH ≥ 2.0 V; PYNQ-Z2 header ≤ 3.4 V recommended | ✔ |
| Board series resistor | 200 Ω between socket and FPGA pin (reference manual) | input current is tiny, so no voltage drop | ✔ |
| Divider output, Arduino LOW | 0 V | VIL ≤ 0.8 V | ✔ |
| Current per divider (HIGH) | 5 V / 5.5 kΩ = 0.9 mA | Uno pin ≤ 20 mA | ✔ |
| Edge speed | source 2.2 k ∥ 3.3 k = 1.32 kΩ; with ~10 pF pin + wire: 10–90 % ≈ 29 ns | SCK half period at 2 MHz = 250 ns | ✔ 8× margin |
| READY HIGH at the Uno | ≈ 3.3 V | ATmega328P VIH ≥ 0.6 × 5 V = 3.0 V | ◐ 0.3 V margin — fine with short wires |
| READY LOW at the Uno | ≈ 0 V | VIL ≤ 0.3 × 5 V = 1.5 V | ✔ |
scripts/check_pins.py recomputes these numbers (section F) — see Step 27.
Cable list
| # | From (Uno pin, as printed) | Through | To (PYNQ-Z2 socket, as printed) | FPGA pin | Signal |
|---|---|---|---|---|---|
| 1 | 13 | col 2 → 2.2 kΩ → col 6 (3.3 kΩ to GND) | AR13 | N17 | SCK |
| 2 | ~11 | col 9 → 2.2 kΩ → col 13 (3.3 kΩ to GND) | AR11 | R17 | MOSI |
| 3 | ~10 | col 16 → 2.2 kΩ → col 20 (3.3 kΩ to GND) | AR10 | T16 | CS_N |
| 4 | 8 | direct wire | AR12 | P18 | READY (PYNQ → Arduino) |
| 5 | GND | breadboard − rail | GND (J3 pin 7, next to AR13) | — | common ground |
Do — in this order
- Unplug the joystick shield from the PYNQ-Z2. Both boards unpowered.
- Push the three 2.2 kΩ resistors into row c across columns 2–6, 9–13 and 16–20; push the three 3.3 kΩ from row a of columns 6, 13 and 20 into the − rail.
- Connect the − rail to Arduino GND (jumper 8).
- Test the dividers before touching the PYNQ: power only the Arduino (USB), put a wire from the Uno 5V pin into column 2, measure column 6 to GND → 2.9–3.1 V. Repeat for columns 9/13 and 16/20. Remove the 5V wire.
- Connect Uno pins 13, ~11, ~10 to columns 2, 9, 16 (jumpers 1, 3, 5).
- Unplug the Arduino. Connect columns 6, 13, 20 to PYNQ AR13, AR11, AR10, Uno pin 8 to PYNQ AR12, and the − rail to PYNQ GND (jumpers 2, 4, 6, 7, 9).
- SW0 down on the PYNQ-Z2 (the GPU listens to the Arduino connector; SW0 up = on-board test host).
- Power on in this order: PYNQ first (program the bitstream), then plug in the Arduino. Unplug in the reverse order.
Why the power order matters
- With the PYNQ-Z2 off, its header may see at most 0.55 V (reference manual). An Arduino driving 3 V through the divider pushes about 2 mA into the unpowered FPGA pin's protection diode and tries to power the 3.3 V bank backwards. So: PYNQ on first, Arduino second; Arduino off first.
- While the Uno sits in its bootloader (~1 s after reset) its pins float: the 3.3 kΩ pulls CS low, and Optiboot blinks the LED on Uno pin 13 (= SCK) a few times. The GPU shifts in a handful of bits — and throws them away, because
spi_cmd_rxonly executes frames of exactly 80 bits. Thensetup()drives CS high and everything starts clean. - Never connect the 5 V or 3.3 V pins of the two boards together — only GND.
Check with a multimeter
| Measure (black probe on GND) | Expected | If not |
|---|---|---|
| PYNQ AR10 while the sketch idles | ≈ 3.0 V (CS idle high) | 0 V → CS wire or divider column wrong |
| PYNQ AR13 / AR11 while idle | ≈ 0 V (SPI mode 0, idle low) | — |
| Uno pin 8 (= PYNQ AR12) | ≈ 3.3 V once LD0 is on | 0 V → bitstream not loaded, BTN0 held, or READY wire on the wrong socket |
| Continuity Arduino GND ↔ PYNQ GND | beep | no common ground → garbage or nothing |
Cheap BSS138 boards use 10 kΩ pull-ups and slow down above ~1 MHz. The 1.32 kΩ divider source gives ≈ 29 ns edges — fine at 2 MHz. A TXS0108E module also works.
Four direct wires + GND. ESP32 DevKit: SCK GPIO 18, MOSI GPIO 23, and in the sketch PIN_CS = 5, PIN_READY = 4 (avoid GPIO 6–11, the flash). Pico (arduino-pico core): SCK GP18, MOSI GP19, PIN_CS = 17, PIN_READY = 20 (GP16 is SPI0 RX — keep it free).
The Arduino sketch
A tiny "GL" on top of the protocol — gpuClear, gpuLine, gpuRect, gpuCircle, gpuFillCircle, gpuSwap — plus five demos: test pattern, starburst, circles, a rotating 3D cube (perspective projection in float on the Arduino, lines drawn by the GPU) and an orbit animation (sine/cosine on the Arduino, filled circles drawn by the GPU).
// =============================================================
// gpu_demo.ino - host for the SPI rasterizer GPU (PYNQ-Z2 or SKY130 ASIC)
//
// Board : Arduino Uno / Nano (ATmega328P, 5 V) -> needs the 3 dividers
// from the wiring step, or any 3.3 V board wired directly.
//
// Uno pin (printed) PYNQ-Z2 socket (printed) FPGA pin GPU signal
// ----------------- ------------------------ -------- ----------
// 13 (SCK) --> AR13 (via divider) N17 spi_sck
// ~11 (MOSI) --> AR11 (via divider) R17 spi_mosi
// ~10 (CS) --> AR10 (via divider) T16 spi_cs_n
// 8 <-- AR12 (direct) P18 gpu_ready
// GND --- GND (must be shared!)
//
// The Uno prints its pins as plain numbers (13, 12, ~11, ~10 ...); Arduino
// code calls them D13, D11, D10. The PYNQ-Z2 prints AR0 .. AR13.
//
// Serial Monitor (115200 baud):
// 1 = test pattern 2 = starburst 3 = cube (300 frames)
// 4 = circles 5 = orbit (120 frames)
// a = auto loop (default after reset) s = stop auto loop
// =============================================================
#include <SPI.h>
// ---------------- pick the target ----------------
#define TARGET_FPGA 1 // 1 = PYNQ-Z2 (320x240, RGB332, double buffer)
// 0 = SKY130 ASIC (40x30, RGB111, single buffer)
#if TARGET_FPGA
const int16_t SCREEN_W = 320;
const int16_t SCREEN_H = 240;
#else
const int16_t SCREEN_W = 40;
const int16_t SCREEN_H = 30;
#endif
// ---------------- pins (Uno hardware SPI: SCK = D13, MOSI = D11) ----------------
// 3.3 V boards, no dividers needed (SCK/MOSI are the board's default SPI pins):
// ESP32 DevKit : SCK GPIO18, MOSI GPIO23 -> PIN_CS = 5, PIN_READY = 4
// Pico (arduino-pico core): SCK GP18, MOSI GP19 -> PIN_CS = 17, PIN_READY = 20
const uint8_t PIN_CS = 10;
const uint8_t PIN_READY = 8;
const uint32_t SPI_HZ = 2000000; // keep <= GPU clock / 8 (25 MHz / 8 = 3.1 MHz)
// ---------------- protocol (see gpu_core.v) ----------------
const uint8_t OP_CLEAR = 0x01; // fill the (back) buffer
const uint8_t OP_LINE = 0x02; // A=x0 B=y0 C=x1 D=y1
const uint8_t OP_RECT = 0x03; // A=x B=y C=w D=h
const uint8_t OP_SWAP = 0x04; // flip buffers / wait for vblank
const uint8_t OP_CIRCLE = 0x05; // A=cx B=cy C=r D=fill (0 outline, 1 filled)
// RGB332 colours (RRRGGGBB). The ASIC keeps only the MSB of each channel.
const uint8_t BLACK = 0x00;
const uint8_t WHITE = 0xFF;
const uint8_t RED = 0xE0;
const uint8_t GREEN = 0x1C;
const uint8_t BLUE = 0x03;
const uint8_t YELLOW = 0xFC;
const uint8_t CYAN = 0x1F;
const uint8_t MAGENTA = 0xE3;
const uint8_t ORANGE = 0xF0;
const uint8_t GREY = 0x92;
const uint8_t PALETTE[8] = { WHITE, YELLOW, CYAN, GREEN, MAGENTA, RED, BLUE, ORANGE };
uint32_t timeouts = 0; // READY never came back (should stay 0)
uint32_t commands = 0; // commands sent since reset
// =============================================================
// Low level: one 10-byte frame per command
// =============================================================
bool gpuWaitReady(uint16_t limit_ms = 100) {
uint32_t t0 = millis();
while (digitalRead(PIN_READY) == LOW) {
if (millis() - t0 > limit_ms) { // CLEAR takes ~3 ms, SWAP <= 17 ms
timeouts++;
return false;
}
}
return true;
}
void spi16(int16_t v) {
SPI.transfer((uint8_t)(v >> 8)); // big endian: high byte first
SPI.transfer((uint8_t)(v & 0xFF));
}
void gpuSend(uint8_t op, int16_t a, int16_t b, int16_t c, int16_t d, uint8_t color) {
gpuWaitReady();
SPI.beginTransaction(SPISettings(SPI_HZ, MSBFIRST, SPI_MODE0));
digitalWrite(PIN_CS, LOW);
SPI.transfer(op);
spi16(a);
spi16(b);
spi16(c);
spi16(d);
SPI.transfer(color);
digitalWrite(PIN_CS, HIGH); // the GPU executes the command now
SPI.endTransaction();
delayMicroseconds(2); // let the GPU see CS high before polling READY
commands++;
}
// =============================================================
// "GL" style API
// =============================================================
void gpuClear(uint8_t c) { gpuSend(OP_CLEAR, 0, 0, 0, 0, c); }
void gpuLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint8_t c) { gpuSend(OP_LINE, x0, y0, x1, y1, c); }
void gpuRect(int16_t x, int16_t y, int16_t w, int16_t h, uint8_t c) { gpuSend(OP_RECT, x, y, w, h, c); }
void gpuSwap() { gpuSend(OP_SWAP, 0, 0, 0, 0, 0); }
void gpuCircle(int16_t cx, int16_t cy, int16_t r, uint8_t c) { gpuSend(OP_CIRCLE, cx, cy, r, 0, c); }
void gpuFillCircle(int16_t cx, int16_t cy, int16_t r, uint8_t c) { gpuSend(OP_CIRCLE, cx, cy, r, 1, c); }
// FPGA: draw into the hidden back buffer, then SWAP.
// ASIC: one buffer -> wait for vblank first, then draw quickly.
void beginFrame() {
#if !TARGET_FPGA
gpuSwap();
#endif
}
void endFrame() {
#if TARGET_FPGA
gpuSwap();
#endif
}
// =============================================================
// Demos (scripts/gen_demo.py draws exactly the same things)
// =============================================================
void demoTestPattern() {
beginFrame();
gpuClear(BLACK);
int16_t bar_w = SCREEN_W / 8;
for (int16_t i = 0; i < 8; i++)
gpuRect(i * bar_w, 0, bar_w, (SCREEN_H * 2) / 3, PALETTE[i]);
gpuRect(0, (SCREEN_H * 2) / 3, SCREEN_W, SCREEN_H / 3, GREY);
// border + diagonals
gpuLine(0, 0, SCREEN_W - 1, 0, WHITE);
gpuLine(SCREEN_W - 1, 0, SCREEN_W - 1, SCREEN_H - 1, WHITE);
gpuLine(SCREEN_W - 1, SCREEN_H - 1, 0, SCREEN_H - 1, WHITE);
gpuLine(0, SCREEN_H - 1, 0, 0, WHITE);
gpuLine(0, 0, SCREEN_W - 1, SCREEN_H - 1, RED);
gpuLine(SCREEN_W - 1, 0, 0, SCREEN_H - 1, BLUE);
gpuCircle(SCREEN_W / 2, SCREEN_H / 2, SCREEN_H / 3, WHITE);
endFrame();
}
void demoStarburst() {
beginFrame();
gpuClear(BLACK);
int16_t cx = SCREEN_W / 2, cy = SCREEN_H / 2;
uint8_t k = 0;
int16_t step = (SCREEN_W >= 160) ? 16 : 4;
for (int16_t x = 0; x < SCREEN_W; x += step) gpuLine(cx, cy, x, 0, PALETTE[(k++) & 7]);
for (int16_t y = 0; y < SCREEN_H; y += step) gpuLine(cx, cy, SCREEN_W - 1, y, PALETTE[(k++) & 7]);
for (int16_t x = SCREEN_W - 1; x > 0; x -= step) gpuLine(cx, cy, x, SCREEN_H - 1, PALETTE[(k++) & 7]);
for (int16_t y = SCREEN_H - 1; y > 0; y -= step) gpuLine(cx, cy, 0, y, PALETTE[(k++) & 7]);
endFrame();
}
void demoCircles() {
beginFrame();
gpuClear(BLACK);
int16_t r = (SCREEN_H * 3) / 10;
int16_t cy = SCREEN_H / 2;
// left: a target of filled discs, biggest first
for (int16_t i = 0; i < 5; i++)
gpuFillCircle(SCREEN_W / 4, cy, r - i * (r / 5), (i & 1) ? WHITE : RED);
// right: 8 concentric outlines
for (int16_t i = 0; i < 8; i++)
gpuCircle((SCREEN_W * 3) / 4, cy, r - i * (r / 8), PALETTE[i]);
// bottom: a row of bubbles, cut off by the screen edge (clipping)
for (int16_t i = 0; i < 9; i++)
gpuFillCircle(i * (SCREEN_W / 8), SCREEN_H - 1, SCREEN_H / 12, PALETTE[i & 7]);
endFrame();
}
// ---- a planet and its moon going round the sun ----
void drawOrbit(float t) {
int16_t cx = SCREEN_W / 2, cy = SCREEN_H / 2;
int16_t R = (SCREEN_H * 2) / 5; // orbit radius
int16_t m = SCREEN_H / 10; // moon distance
int16_t px = (int16_t)(cx + R * cos(t));
int16_t py = (int16_t)(cy + R * sin(t));
int16_t mx = (int16_t)(px + m * cos(4 * t));
int16_t my = (int16_t)(py + m * sin(4 * t));
beginFrame();
gpuClear(BLACK);
gpuCircle(cx, cy, R, GREY); // orbit path
gpuFillCircle(cx, cy, SCREEN_H / 8, YELLOW); // sun
gpuFillCircle(px, py, SCREEN_H / 16, BLUE); // planet
gpuFillCircle(mx, my, SCREEN_H / 40, WHITE); // moon
endFrame();
}
void demoOrbit(uint16_t frames) {
for (uint16_t n = 0; n < frames; n++)
drawOrbit(n * 0.157f); // 40 frames per turn
}
// ---- rotating wireframe cube (the "3D" demo) ----
const int8_t CUBE_V[8][3] = {
{-1,-1,-1}, { 1,-1,-1}, { 1, 1,-1}, {-1, 1,-1},
{-1,-1, 1}, { 1,-1, 1}, { 1, 1, 1}, {-1, 1, 1}
};
const uint8_t CUBE_E[12][2] = {
{0,1},{1,2},{2,3},{3,0}, // back face
{4,5},{5,6},{6,7},{7,4}, // front face
{0,4},{1,5},{2,6},{3,7} // connecting edges
};
void drawCube(float ax, float ay) {
int16_t px[8], py[8];
float sx = sin(ax), cx = cos(ax), sy = sin(ay), cy = cos(ay);
float f = SCREEN_H * 0.6f; // focal length in pixels (cube fits on screen)
for (uint8_t i = 0; i < 8; i++) {
float x = CUBE_V[i][0], y = CUBE_V[i][1], z = CUBE_V[i][2];
float y1 = y * cx - z * sx; // rotate around X
float z1 = y * sx + z * cx;
float x2 = x * cy + z1 * sy; // rotate around Y
float z2 = -x * sy + z1 * cy;
float zc = z2 + 4.0f; // push away from the camera
px[i] = (int16_t)(SCREEN_W / 2 + (x2 * f) / zc); // perspective divide
py[i] = (int16_t)(SCREEN_H / 2 + (y1 * f) / zc);
}
beginFrame();
gpuClear(BLACK);
for (uint8_t e = 0; e < 12; e++) {
uint8_t a = CUBE_E[e][0], b = CUBE_E[e][1];
uint8_t c = (e < 4) ? BLUE : (e < 8) ? YELLOW : MAGENTA;
gpuLine(px[a], py[a], px[b], py[b], c);
}
endFrame();
}
void demoCube(uint16_t frames) {
uint32_t t0 = millis();
for (uint16_t n = 0; n < frames; n++)
drawCube(n * 0.035f, n * 0.05f);
Serial.print(F(" cube fps = "));
Serial.println(frames * 1000.0 / (millis() - t0));
}
// =============================================================
// Start-up wiring check: tells you WHAT is wrong instead of hanging
// =============================================================
void wiringCheck() {
Serial.println(F("Waiting for READY (GPU clears its framebuffer after reset)..."));
uint32_t t0 = millis();
while (digitalRead(PIN_READY) == LOW) {
if (millis() - t0 > 3000) {
Serial.println(F("READY is still LOW after 3 s. Check:"));
Serial.println(F(" - FPGA programmed? LD1 (locked) on, LD0 (READY) on?"));
Serial.println(F(" - PYNQ-Z2 AR12 -> Uno pin 8 wire"));
Serial.println(F(" - GND of both boards connected"));
Serial.println(F(" - BTN0 not pressed, SW0 DOWN (SW0 up = on-board test host)"));
t0 = millis();
}
}
Serial.println(F("READY is HIGH - link OK."));
}
void printStats() {
Serial.print(F(" commands = "));
Serial.print(commands);
Serial.print(F(" READY timeouts = "));
Serial.println(timeouts); // must stay 0
}
// =============================================================
// setup / loop
// =============================================================
bool autoLoop = true;
void setup() {
Serial.begin(115200);
digitalWrite(PIN_CS, HIGH); // set the HIGH level first ...
pinMode(PIN_CS, OUTPUT); // ... so CS never glitches low (idle high before SPI.begin())
pinMode(PIN_READY, INPUT);
SPI.begin();
Serial.println(F("\n=== SPI rasterizer GPU demo ==="));
Serial.print(F("target "));
Serial.print(TARGET_FPGA ? F("FPGA ") : F("ASIC "));
Serial.print(SCREEN_W);
Serial.print('x');
Serial.print(SCREEN_H);
Serial.print(F(", SPI "));
Serial.print(SPI_HZ / 1000);
Serial.println(F(" kHz"));
wiringCheck();
Serial.println(F("keys: 1 pattern, 2 starburst, 3 cube, 4 circles, 5 orbit, a auto, s stop"));
}
void loop() {
if (Serial.available()) {
char c = Serial.read();
if (c == '1') { Serial.println(F("test pattern")); demoTestPattern(); printStats(); }
if (c == '2') { Serial.println(F("starburst")); demoStarburst(); printStats(); }
if (c == '3') { Serial.println(F("cube")); demoCube(300); printStats(); }
if (c == '4') { Serial.println(F("circles")); demoCircles(); printStats(); }
if (c == '5') { Serial.println(F("orbit")); demoOrbit(120); printStats(); }
if (c == 'a') { autoLoop = true; Serial.println(F("auto loop on")); }
if (c == 's') { autoLoop = false; Serial.println(F("auto loop off")); }
}
if (!autoLoop) return;
Serial.println(F("test pattern"));
demoTestPattern();
delay(3000);
Serial.println(F("starburst"));
demoStarburst();
delay(3000);
Serial.println(F("circles"));
demoCircles();
delay(3000);
Serial.println(F("cube"));
demoCube(600);
Serial.println(F("orbit"));
demoOrbit(240);
printStats();
}Do
- Copy the sketch folder to Windows:
cp -r ~/asic_projects/raster_gpu/arduino/gpu_demo /mnt/c/fpga/ - Arduino IDE → File›Open →
C:\fpga\gpu_demo\gpu_demo.ino. - Check line 23:
#define TARGET_FPGA 1(0 for the ASIC). - Tools›Board›Arduino AVR Boards›Arduino Uno, Tools›Port → your COM port.
- Upload (Ctrl+U). Then Tools›Serial Monitor at 115200 baud.
Expected
=== SPI rasterizer GPU demo ===
target FPGA 320x240, SPI 2000 kHz
Waiting for READY (GPU clears its framebuffer after reset)...
READY is HIGH - link OK.
keys: 1 pattern, 2 starburst, 3 cube, 4 circles, 5 orbit, a auto, s stop
test pattern
starburst
circles
cube
cube fps = ...
orbit
commands = ... READY timeouts = 0How the sketch is organised
| Section | What it does |
|---|---|
| pins / protocol / colours | one place to change pins (ESP32), opcodes as in gpu_core.v, RGB332 colour constants |
gpuSend() | wait for READY → CS low → 10 bytes MSB-first → CS high → 2 µs pause |
gpuClear / Line / Rect / Circle / FillCircle / Swap | one-line wrappers, the "GL" API you draw with; a circle is one 10-byte command whatever its size |
beginFrame/endFrame | FPGA: SWAP after drawing (double buffer) · ASIC: wait for vblank before drawing |
| demos | identical to scripts/gen_demo.py, so the simulator pictures are what you should see |
wiringCheck() | if READY never rises it prints a checklist every 3 s instead of hanging silently |
demoCircles(), drawOrbit(t) | the circle demos: a filled target, outlines, bubbles clipped by the screen edge; a planet + moon going round the sun |
loop() | auto demo loop; type 1…5 in the Serial Monitor to run one demo, s to stop, a to resume |
The monitor shows the pattern, the starburst, the circles, the spinning cube and the orbit — the same images as the simulation in Part 2. LD2 flickers with every command.
On the FPGA endFrame() sends SWAP, so the 3 ms CLEAR happens in the hidden buffer and you never see a half-drawn cube. The ASIC has one buffer, so beginFrame() waits for vblank first and clear + 12 lines (~0.8 ms of SPI) mostly fit into the 1.4 ms vertical blank.
FPGA bring-up checklist
Bring-up order (test one thing at a time)
- Step 1 — VGA controller (Step 22):
vga_test_top, only the adapter plugged in. Checkerboard with a red frame, colour bars, even DAC ramps, grid → clock, VGA timing, the adapter, cable and monitor are fine. - Sync check (optional, multimeter in Hz mode or scope): PMOD A pin 2 ≈ 31.25 kHz (HSYNC), pin 8 ≈ 59.5 Hz (VSYNC).
- Step 2 — SPI + framebuffer + RECT (Step 23):
fpga_top+ the step-2 core, SW0 up. “HI” appears by itself; BTN2 / BTN3 → colours, blocks. - Step 3 — + LINE (Step 24): starburst, string art, house; SW1 up → the step-2 pictures again.
- Step 4 — + CIRCLE (Step 25): target, snowman, edges; SW1 up → the step-3 pictures again. The complete GPU works on the real FPGA.
- Loopback (optional): three wires SPI header → AR10/11/13, SW0 down, same pictures → the input pins and XDC are right. Remove the wires.
- READY: PYNQ AR12 measures ≈ 3.3 V.
- Arduino alone: upload the sketch with the PYNQ unpowered and not wired: the Serial Monitor prints the READY checklist every 3 s — that proves the sketch and the serial link.
- Together: wire it (Step 29), SW0 down, power the PYNQ, program it, then plug in the Arduino → "READY is HIGH - link OK." and the test pattern appears.
Symptoms and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Monitor: "no signal" | bitstream not loaded / LD1 off | check LD1, re-program, check PMOD orientation |
| Picture rolls or is shifted | adapter or cable | same pins as your old design — compare with your old bitstream |
| Serial stuck at "waiting for READY" | READY not reaching Uno pin 8, no common GND, BTN0 held | AR12 must read 3.3 V; check GND; LD0 must be on |
| READY ok, nothing drawn, LD2 never toggles | SW0 up, SPI wires swapped or divider wrong | SW0 down; Uno 13→AR13, ~11→AR11, ~10→AR10; ≈3.0 V high at the AR sockets |
| On-board tests fine, Arduino draws nothing | the problem is outside the FPGA | wiring, dividers, GND or the sketch — the GPU itself is proven |
| Garbage shapes / wrong colours | SPI edges too slow / long wires | set SPI_HZ to 1000000, keep wires < 15 cm |
| READY timeouts > 0 | a command was sent while busy | only if you removed gpuWaitReady() |
| Cube flickers | TARGET_FPGA 0 on the FPGA | set it to 1 |
From FPGA RTL to ASIC RTL
Nothing in rtl/ changes. The ASIC version is a 50-line wrapper that sets the parameters, plus a pin plan.
What changes, and why
| Topic | FPGA | ASIC | Why |
|---|---|---|---|
| Framebuffer | BRAM 320×240×8 ×2 | flip-flops 40×30×3 | no SRAM yet; ≈30 µm² + mux per bit |
| Initial contents | could use initial | cleared by logic after reset | silicon has no init values |
| Clock | MMCM 25.000 MHz | 25.175 MHz oscillator | no PLL; VGA needs the pixel rate |
| Reset | locked & ~BTN0 | pad rst_n from a supervisor | same reset synchronizer inside |
| SPI | 2-FF sync | 2-FF sync + SDC false paths | STA must not time async pins (CDC step) |
| Colour out | 12 pins RGB444 | 3 pins RGB111 | each pin is an 80 µm GPIO pad |
The logic would meet timing far slower, but the monitor needs 25.175 MHz pixels for 640×480. 40 ns per clock is already very relaxed for SKY130 (gate delays 0.1–0.5 ns), so there is nothing to gain.
`timescale 1ns / 1ps
// =============================================================
// gpu_asic : the block we harden with LibreLane (Classic flow)
//
// Same gpu_core as the FPGA, smaller framebuffer (standard-cell
// flip-flops, no SRAM yet):
// 40 x 30 pixels, 3 bits (RGB111), single buffer, 16x16 scaling
//
// 11 signal pins -> 11 GPIO pads later in chip_top.v
// in : clk, rst_n, spi_cs_n, spi_sck, spi_mosi
// out: gpu_ready, vga_hs, vga_vs, vga_rgb[2:0]
// =============================================================
module gpu_asic (
`ifdef USE_POWER_PINS
inout wire VPWR, // only visible in powered netlists / chip_top sim
inout wire VGND,
`endif
input wire clk, // 25.175 MHz oscillator
input wire rst_n,
input wire spi_cs_n,
input wire spi_sck,
input wire spi_mosi,
output wire gpu_ready,
output wire vga_hs,
output wire vga_vs,
output wire [2:0] vga_rgb // {R, G, B}
);
gpu_core #(
.FB_W(40),
.FB_H(30),
.SCALE_SHIFT(4),
.PIX_BITS(3),
.DOUBLE_BUF(0)
) u_gpu (
.clk(clk),
.rst_n(rst_n),
.spi_cs_n(spi_cs_n),
.spi_sck(spi_sck),
.spi_mosi(spi_mosi),
.gpu_ready(gpu_ready),
.vga_hs(vga_hs),
.vga_vs(vga_vs),
.vga_pix(vga_rgb),
/* verilator lint_off PINCONNECTEMPTY */
.dbg_cmd_toggle() // debug LED output, not needed on the chip
/* verilator lint_on PINCONNECTEMPTY */
);
endmoduleThe `ifdef USE_POWER_PINS ports follow the LibreLane convention: synthesis does not see them, the PDN adds VPWR/VGND to the macro, and chip_top.v connects them. LibreLane's Verilator lint runs with the define — this file is lint-clean both ways.
Pin plan: 11 GPIOs for a GPU chip
| # | Macro pin | Pad | Dir | Function | Side |
|---|---|---|---|---|---|
| 0 | clk | u_clk | in | 25.175 MHz oscillator | S |
| 1 | rst_n | u_rst_n | in | reset (low = reset) | S |
| 2 | spi_cs_n | u_cs_n | in | SPI chip select | W |
| 3 | spi_sck | u_sck | in | SPI clock | W |
| 4 | spi_mosi | u_mosi | in | SPI data | W |
| 5 | gpu_ready | u_ready | out | flow control to the MCU | E |
| 6 | vga_hs | u_hs | out | HSYNC | E |
| 7 | vga_vs | u_vs | out | VSYNC | E |
| 8–10 | vga_rgb[2:0] | u_r u_g u_b | out | R, G, B (resistor to the VGA pins) | N |
| — | — | u_power_good | in | POR from a board supervisor → ENABLE_H of all pads | S |
A host needs 4 wires (CS, SCK, MOSI, READY), the monitor 5. This is how the finished chip would sit on a small PCB as a "GPU for an MCU":
All 18 bond pads
| Side (die) | Order | Pad instance | Cell | Net / function |
|---|---|---|---|---|
| South L→R | 1 | u_vccd | vccd_lvc_clamped_pad | VCCD 1.8 V core supply |
| South | 2 | u_clk | gpiov2_pad_wrapped (in) | clock |
| South | 3 | u_rst_n | gpiov2 (in) | reset, active low |
| South | 4 | u_power_good | gpiov2 (in) | POR → ENABLE_H |
| South | 5 | u_vssd | vssd_lvc_clamped_pad | core ground |
| West B→T | 1 | u_vddio | vddio_hvc_clamped_pad | VDDIO 3.3 V pad supply |
| West | 2 | u_cs_n | gpiov2 (in) | SPI CS |
| West | 3 | u_sck | gpiov2 (in) | SPI SCK |
| West | 4 | u_mosi | gpiov2 (in) | SPI MOSI |
| West | 5 | u_vssio | vssio_hvc_clamped_pad | pad ground |
| East B→T | 1 | u_vdda | vdda_hvc_clamped_pad | VDDA 3.3 V |
| East | 2 | u_ready | gpiov2 (out) | READY |
| East | 3 | u_hs | gpiov2 (out) | HSYNC |
| East | 4 | u_vs | gpiov2 (out) | VSYNC |
| East | 5 | u_vssa | vssa_hvc_clamped_pad | analog ground |
| North L→R | 1 | u_r | gpiov2 (out) | RED |
| North | 2 | u_g | gpiov2 (out) | GREEN |
| North | 3 | u_b | gpiov2 (out) | BLUE |
The macro's own pins sit on the side that faces their pads, so the top-level wires stay short:
#S
clk
rst_n
#W
spi_cs_n
spi_sck
spi_mosi
#E
gpu_ready
vga_hs
vga_vs
#N
vga_rgb\[2\]
vga_rgb\[1\]
vga_rgb\[0\]A board for the chip: parts, power and every connection
This chip is not fabricated. This step is what a small test PCB for the packaged die would need, so the pin plan is complete from the macro pin to the monitor. Part numbers are examples of common parts — any part with the same function and ratings works. Check every datasheet before ordering.
Power tree
The SKY130 pad ring needs three supplies: VCCD 1.8 V for the core and the macro, VDDIO 3.3 V for the pad drivers, VDDA 3.3 V for the analog/clamp domain. Two LDOs from USB 5 V cover it:
Why there is a buffer between the chip and the VGA connector
A sky130_fd_io__gpiov2 pad is specified for 4 mA source/sink (and ≤ 33 MHz output toggle — we toggle at most at 25.175 MHz / 16). A VGA colour input is 75 Ω to ground: 3.3 V through 270 Ω + 75 Ω draws 9.6 mA, more than twice the rating. So the six output pads drive a 74LVC244A (3.3 V octal buffer, ±24 mA), and the buffer drives the resistors. The pads then only see a CMOS input (µA). HSYNC/VSYNC go through the same buffer with 47 Ω series resistors against ringing on the cable.
Bill of materials
| Ref | Part (example) | Qty | Spec | Connects to |
|---|---|---|---|---|
| U1 | gpu_chip (this design, packaged) | 1 | SKY130, 18 bond pads | — |
| U2 | 3.3 V LDO, e.g. AMS1117-3.3 (SOT-223) | 1 | 5 V in, ≥ 300 mA; 10 µF in, 22 µF out (per datasheet) | VDDIO, VDDA, oscillator, supervisor, buffer, host |
| U3 | 1.8 V LDO, e.g. AP2112K-1.8 (SOT-23-5) | 1 | fed from 3V3, EN tied to VIN; 1 µF in/out | VCCD |
| X1 | 25.175 MHz oscillator, 3.3 V CMOS output | 1 | any 3.3 V CMOS oscillator at this frequency (a programmable MEMS oscillator can be ordered at 25.175 MHz) | pad_clk |
| U4 | reset supervisor, e.g. MAX811-type | 1 | 3.3 V rail, ≈ 3.08 V threshold option, active-low push-pull RESET#, ≥ 140 ms timeout, manual-reset input | pad_rst_n and pad_power_good |
| SW1 | push-button | 1 | to the supervisor MR# input | manual reset |
| U5 | 74LVC244A octal buffer | 1 | VCC = 3.3 V, both OE# to GND, 2 spare inputs to GND | pads → VGA |
| R1–R3 | 270 Ω, 1 % | 3 | R, G, B DAC (into the monitor's 75 Ω) | buffer → DE-15 pins 1, 2, 3 |
| R4, R5 | 47 Ω | 2 | series, HSYNC / VSYNC | buffer → DE-15 pins 13, 14 |
| C | 100 nF X7R (0603) | 8 | one at each supply pad (VCCD, VDDIO, VDDA), U2, U3, X1, U4, U5 | decoupling |
| C | 10 µF | 2 | bulk on the 3V3 and 1V8 rails | decoupling |
| J1 | DE-15 female (HD15, 3 rows) | 1 | VGA | monitor |
| J2 | 1×5 pin header | 1 | CS, SCK, MOSI, READY, GND — 3.3 V host only (a 5 V Uno needs the dividers from Step 29) | host MCU |
| J3 | USB-C / micro-USB receptacle | 1 | 5 V in | U2 |
Every connection on the board
| Chip pad (net) | Pad cell | Dir | Board net | Goes to |
|---|---|---|---|---|
| pad_clk | u_clk | in | CLK25 | X1 output |
| pad_rst_n | u_rst_n | in | RESET_N | U4 RESET# (low = reset) |
| pad_power_good | u_power_good | in | RESET_N | same net: HIGH once 3V3 (and so 1V8) is up → enables all pad drivers |
| pad_cs_n | u_cs_n | in | SPI_CS_N | J2-1 (host CS) |
| pad_sck | u_sck | in | SPI_SCK | J2-2 (host SCK, ≤ 3 MHz) |
| pad_mosi | u_mosi | in | SPI_MOSI | J2-3 (host MOSI) |
| pad_ready | u_ready | out | GPU_READY | J2-4 (host GPIO input) |
| pad_rgb[2] | u_r | out | R_TTL | U5 → 270 Ω → J1 pin 1 |
| pad_rgb[1] | u_g | out | G_TTL | U5 → 270 Ω → J1 pin 2 |
| pad_rgb[0] | u_b | out | B_TTL | U5 → 270 Ω → J1 pin 3 |
| pad_hs | u_hs | out | HSYNC | U5 → 47 Ω → J1 pin 13 |
| pad_vs | u_vs | out | VSYNC | U5 → 47 Ω → J1 pin 14 |
| VCCD / VSSD | u_vccd / u_vssd | pwr | 1V8 / GND | U3 out / plane |
| VDDIO / VSSIO | u_vddio / u_vssio | pwr | 3V3 / GND | U2 out / plane |
| VDDA / VSSA | u_vdda / u_vssa | pwr | 3V3 / GND | U2 out / plane |
| — | — | — | GND | J1 pins 5, 6, 7, 8, 10 · J2-5 |
Set #define TARGET_FPGA 0 and use the ESP32/Pico pin numbers from Step 29. The chip pins behave exactly like the PYNQ-Z2 header pins: 3.3 V, SPI mode 0, READY high = accept.
Pins-only testbench (works on the netlist too)
tb_gpu peeks at dut.u_fb.mem, which no longer exists after synthesis flattens the design. tb_pins uses only the 11 pins: it finds the frame from VSYNC/HSYNC like a monitor and writes the captured frame to a file.
▸ Show sim/tb_pins.v · 87 lines
`timescale 1ns / 1ps
// =============================================================
// Pins-only testbench for gpu_asic (works on RTL AND on the
// gate-level netlist from LibreLane: no internal signals used).
//
// +demo=<file.cmd> commands to send (from gen_demo.py)
// +out=<file.hex> captured 640x480 frame (one pixel per line)
//
// The frame is located like a monitor does it: from the sync pulses.
// VSYNC rises at the end of line 491, HSYNC falls at x = 656.
// -> 33rd HSYNC fall after VSYNC rises = line 524
// -> 144 clocks later x = 0 of line 0 comes out.
// =============================================================
module tb_pins;
reg clk = 1'b0;
always #19.861 clk = ~clk; // 25.175 MHz
reg rst_n = 1'b0;
reg cs_n = 1'b1, sck = 1'b0, mosi = 1'b0;
wire ready, hs, vs;
wire [2:0] rgb;
gpu_asic dut (
.clk(clk), .rst_n(rst_n),
.spi_cs_n(cs_n), .spi_sck(sck), .spi_mosi(mosi),
.gpu_ready(ready), .vga_hs(hs), .vga_vs(vs), .vga_rgb(rgb)
);
task send(input [79:0] w);
integer i;
begin
wait (ready === 1'b1);
#100 cs_n = 1'b0;
#250;
for (i = 79; i >= 0; i = i - 1) begin
mosi = w[i];
#250 sck = 1'b1;
#250 sck = 1'b0;
end
#250 cs_n = 1'b1;
#500;
end
endtask
reg [8*128-1:0] demo_file, out_file;
reg [79:0] w;
integer fd, r, x, y, n;
initial begin
if (!$value$plusargs("demo=%s", demo_file)) $fatal(1, "need +demo=");
if (!$value$plusargs("out=%s", out_file)) out_file = "build/pins_frame.hex";
#1000 rst_n = 1'b1;
fd = $fopen(demo_file, "r");
n = 0;
while (!$feof(fd)) begin
r = $fscanf(fd, "%h\n", w);
if (r == 1) begin send(w); n = n + 1; end
end
$fclose(fd);
wait (ready === 1'b1);
$display("sent %0d commands", n);
// ---- find the start of the next frame from the sync pins ----
@(posedge vs);
repeat (33) @(negedge hs);
repeat (144) @(posedge clk);
#1;
fd = $fopen(out_file, "w");
for (y = 0; y < 480; y = y + 1)
for (x = 0; x < 800; x = x + 1) begin
if (x < 640) $fwrite(fd, "%h\n", rgb);
else if (rgb !== 3'b000) $fatal(1, "RGB not black in blanking (x=%0d y=%0d)", x, y);
if (x == 700 && hs !== 1'b0) $fatal(1, "HSYNC not low at x=700 (y=%0d)", y);
if (x == 100 && hs !== 1'b1) $fatal(1, "HSYNC low at x=100 (y=%0d)", y);
@(posedge clk); #1;
end
$fclose(fd);
$display("PASS: frame captured from the pins -> %0s", out_file);
$finish;
end
initial begin #100_000_000; $fatal(1, "timeout"); end
endmodulecd ~/asic_projects/raster_gpu
python3 scripts/gen_demo.py asic pattern build/demo/asic_pattern.cmd
RTL="rtl/spi_cmd_rx.v rtl/vga_controller.v rtl/frame_buffer.v rtl/line_renderer.v rtl/rect_filler.v rtl/circle_renderer.v rtl/gpu_core.v"
iverilog -g2012 -s tb_pins -o build/tb_pins $RTL asic/src/gpu_asic.v sim/tb_pins.v
vvp -n build/tb_pins +demo=build/demo/asic_pattern.cmd +out=build/rtl_pattern.hexThe frame from tb_pins is byte-identical to the tb_gpu capture, on RTL and on the netlist mapped to SKY130 cells. You repeat the netlist run with LibreLane's own netlist in the gate-level step.
Harden gpu_asic with LibreLane
Same tool as for counter8. The result is a hard macro (LEF + GDS + netlist) that chip_top instantiates in Part 6.
config.json, line by line
{
"DESIGN_NAME": "gpu_asic",
"VERILOG_FILES": [
"dir::src/spi_cmd_rx.v",
"dir::src/vga_controller.v",
"dir::src/frame_buffer.v",
"dir::src/line_renderer.v",
"dir::src/rect_filler.v",
"dir::src/circle_renderer.v",
"dir::src/gpu_core.v",
"dir::src/gpu_asic.v"
],
"CLOCK_PORT": "clk",
"CLOCK_PERIOD": 39.72,
"PDK": "sky130A",
"STD_CELL_LIBRARY": "sky130_fd_sc_hd",
"PNR_SDC_FILE": "dir::gpu.sdc",
"SIGNOFF_SDC_FILE": "dir::gpu.sdc",
"FP_SIZING": "absolute",
"DIE_AREA": [0, 0, 720, 720],
"CORE_AREA": [15, 15, 705, 705],
"PL_TARGET_DENSITY_PCT": 45,
"IO_PIN_ORDER_CFG": "dir::pin_order.cfg",
"PDN_MULTILAYER": false,
"PDN_CORE_RING": false,
"RT_MAX_LAYER": "met4",
"PDN_VWIDTH": 3.1,
"PDN_VPITCH": 60,
"PDN_VOFFSET": 20
}| Key | Value | Why |
|---|---|---|
| CLOCK_PERIOD | 39.72 | 25.175 MHz pixel clock |
| DIE_AREA / CORE_AREA | 720×720, 15 µm margin | 0.168 mm² of cells → ~35 % of a 690×690 core; the read mux needs routing room |
| PL_TARGET_DENSITY_PCT | 45 | spread the cells instead of packing them |
| IO_PIN_ORDER_CFG | pin_order.cfg | pins face their pads (old name FP_PIN_ORDER_CFG) |
| PDN_MULTILAYER | false | macro mode: power straps on met4 only, so chip-level met5 straps can cross the macro |
| PDN_CORE_RING | false | LibreLane refuses a core ring when PDN_MULTILAYER is false; the chip owns the ring |
| RT_MAX_LAYER | met4 | keep signal routing off met5 (chip PDN layer) |
| PDN_VWIDTH / PITCH / OFFSET | 3.1 / 60 / 20 | denser met4 straps = more VPWR/VGND pin area for the chip to land on |
Your counter8.lef has VPWR/VGND on met4 and met5 (ring + straps from config_ring.json). Chip-level met5 straps cannot cross that. With PDN_MULTILAYER: false the macro exposes met4 straps only — LibreLane's own macro recipe (its spm-user_project_wrapper example uses exactly this plus RT_MAX_LAYER: met4).
Timing constraints — where the CDC lands
# =============================================================
# gpu.sdc : timing constraints for the gpu_asic macro
# =============================================================
# 25.175 MHz VGA pixel clock (39.72 ns)
create_clock -name clk -period 39.72 [get_ports clk]
set_clock_uncertainty 0.5 [get_clocks clk]
set_clock_transition 0.15 [get_clocks clk]
# Realistic edges at the macro pins (pads sit ~200 um away)
set_input_transition 0.5 [get_ports {rst_n spi_cs_n spi_sck spi_mosi}]
set_load 0.05 [all_outputs]
# ---- CDC: asynchronous inputs ----
# spi_* and rst_n are NOT synchronous to clk. They only enter the first
# flop of a 2-FF synchronizer, so the path pin -> first flop has no
# meaningful setup/hold requirement. Everything after the first flop
# (meta -> sync -> logic) is still fully timed.
set_false_path -from [get_ports {rst_n spi_cs_n spi_sck spi_mosi}]
# ---- outputs ----
# All outputs come straight from flip-flops. Budget 10 ns for the pad +
# board, the rest of the 39.7 ns period is for the clock-to-Q path.
set_output_delay -clock clk -max 10.0 [get_ports {gpu_ready vga_hs vga_vs vga_rgb*}]
set_output_delay -clock clk -min 0.0 [get_ports {gpu_ready vga_hs vga_vs vga_rgb*}]Run the flow
Do
- Start the LibreLane devshell (your AppImage).
- Run:
cd ~/asic_projects/raster_gpu/asic
librelane config.json --run-tag gpu_v1- The terminal prints each step (Verilator.Lint, Yosys.Synthesis, … Netgen.LVS). Expect roughly 10–30 minutes on your i7-1185G7.
- At the end a summary lists DRC, LVS, antenna, setup/hold. Anything red is a real problem: read
runs/gpu_v1/warning.loganderror.log.
Stop after any step and look: librelane config.json --run-tag fp --to OpenROAD.Floorplan. After a change to RTL, SDC or config always start a new tag.
Inspect every stage in the GUI
librelane --last-run --flow OpenInOpenROAD config.json
librelane --last-run --flow OpenInKLayout config.jsonOpenROAD GUI orientation
- F fits the view; mouse wheel zooms; middle-drag pans.
- Display Control (left): tick/untick layers, instances, nets, and the Heat Maps section (placement density, routing congestion).
- Inspector (right): click any object to see name, master, bbox, connected nets.
- Windows›Timing Report: worst paths, click one to highlight it on the layout.
- Tcl console (bottom): every command from this page can be typed here.
| Stage | Where | Good | If not |
|---|---|---|---|
| Synthesis | runs/gpu_v1/*-yosys-synthesis/ | ~12k cells, 0 latches, top = gpu_asic | testbenches in VERILOG_FILES? |
| Pins | GUI: zoom to the edges | clk/rst_n S, SPI W, ready/hs/vs E, rgb N | pin_order.cfg regex must match |
| PDN | Display Control → only met4; Nets VPWR/VGND | vertical met4 straps every 60 µm, no met5 | PDN_MULTILAYER false? |
| Placement | Heat Maps → Placement Density | even, no red spot | bigger DIE_AREA or lower density |
| CTS | Windows → Clock Tree Viewer | ~4,000 sinks, small skew | normal: framebuffer flops dominate |
| Routing | Heat Maps → Routing Congestion | no red | more area, new tag |
| GDS | KLayout: Display → Full Hierarchy | cells + met1–met4 only | — |
| DRC / LVS / antenna | flow summary + step folders | 0 / clean / 0 | open the step log and marker DB |
The KLayout.Render step writes a PNG to runs/gpu_v1/final/render/; open it with explorer.exe runs/gpu_v1/final/render.
CDC and timing review
You wrote "CDS issues" — in this flow that is CDC, clock domain crossing. The GPU has exactly one clock, so the review is short and concrete:
| Crossing | Handled by | How to check |
|---|---|---|
| spi_cs_n, spi_sck, spi_mosi → clk | synchronizer shift register each; logic uses only stage [1] / [2] | false path from the ports; [0]→[1] still timed |
| rst_n → clk | async assert, 2-flop synchronous release (reset_s) | false path from the port; reset_s[1] → logic timed |
| 80-bit command word | never crosses: built inside the clk domain | nothing to check |
| SCK edge vs MOSI | same 2-stage latency; MOSI stable ≥ 6 clocks around the edge at 2 MHz | host rule SCK ≤ clk/8 |
In the OpenROAD GUI → Tcl console
# worst setup / hold
report_checks -path_delay max -group_path_count 5
report_checks -path_delay min -group_path_count 5
# anything left without a constraint?
report_checks -unconstrained -group_path_count 5
# the synchronizer chain must still be timed (stage [0] -> [1])
report_checks -through [get_nets *sck_s*] -path_delay max
report_clock_skewExpected
- Setup slack large and positive (period 39.7 ns).
- Hold slack ≥ 0 at every corner — LibreLane repairs hold; check each corner in the
*-openroad-stapostpnrfolder. - Worst setup path: VGA counters → address multiply → framebuffer read mux. Fine.
- If a
*_s[0]net appears unconstrained, the false path is too wide — it must start only at the ports.
Gate-level simulation of LibreLane's netlist
The netlist LibreLane placed and routed is runs/gpu_v1/final/nl/gpu_asic.nl.v. Simulate it with the PDK cell models and compare against the RTL frame from the pins testbench:
cd ~/asic_projects/raster_gpu
HD=$SKY130_PDK/libs.ref/sky130_fd_sc_hd/verilog
iverilog -g2012 -DFUNCTIONAL -DUNIT_DELAY=#1 -s tb_pins -o build/tb_pins_gl \
$HD/primitives.v $HD/sky130_fd_sc_hd.v \
asic/runs/gpu_v1/final/nl/gpu_asic.nl.v sim/tb_pins.v
vvp -n build/tb_pins_gl +demo=build/demo/asic_pattern.cmd +out=build/gl_pattern.hex
cmp build/gl_pattern.hex build/rtl_pattern.hex && echo "GATE LEVEL == RTL"~12k cells × 1.2 M clocks ≈ 10–15 minutes in Icarus. A compile error naming a cell means a wrong PDK path; a timeout means READY never rose — check reset.
Collect the macro for the chip
cd ~/asic_projects/raster_gpu
mkdir -p chip/macros chip/results chip/reports
cp asic/runs/gpu_v1/final/lef/gpu_asic.lef chip/macros/
cp asic/runs/gpu_v1/final/gds/gpu_asic.gds chip/macros/
cp asic/runs/gpu_v1/final/pnl/gpu_asic.pnl.v chip/macros/
grep -E "SIZE|PIN (VPWR|VGND)" -A3 chip/macros/gpu_asic.lef | head -20Expected
SIZE 720.000 BY 720.000 and VPWR/VGND on met4 only. If the size differs, adjust the macro origin in the floorplan step so it stays centred.
The full chip: pads in Verilog, geometry in OpenROAD
Your counter8_fullchip recipe, scaled to the GPU, with the two problems from your report fixed.
chip_top.v — 11 GPIOs, power-good, supplies, macro
Verilog describes connectivity, Tcl describes geometry. This is your counter8 chip_top.v with the counter replaced by the GPU: same INPUT_PAD/OUTPUT_PAD macros, same tie_lo[10:0], same power-good GPIO, same six clamped supply pads. The port names were checked against the pad module definitions in your report.
`default_nettype none
// =============================================================
// chip_top : SKY130 padframe around the hardened gpu_asic macro
//
// Same structure as counter8_fullchip/rtl/chip_top.v:
// - 11 signal GPIOs (5 in, 6 out) -> tie_lo[10:0]
// - 1 power-good GPIO (drives ENABLE_H / ENABLE_VDDIO of the others)
// - 6 clamped supply pads (VCCD VSSD VDDIO VSSIO VDDA VSSA)
// - 1 conb tie cell for the 1.8 V pad controls
// - the hardened GPU macro u_core
//
// Verilog only describes CONNECTIVITY. Where every cell sits on the
// die is decided later in tcl/01_floorplan.tcl.
// =============================================================
// Shared power/analog connections for SKY130 I/O cells
`define IO_BUSES \
.VCCD(VCCD), \
.VSSD(VSSD), \
.VDDIO(VDDIO), \
.VSSIO(VSSIO), \
.VDDA(VDDA), \
.VSSA(VSSA), \
.VCCHIB(VCCD), \
.VSWITCH(VDDIO), \
.VDDIO_Q(VDDIO), \
.VSSIO_Q(VSSIO), \
.AMUXBUS_A(amux_a), \
.AMUXBUS_B(amux_b)
// Controls common to ordinary signal GPIOs
`define GPIO_COMMON(I) \
`IO_BUSES, \
.ENABLE_H(por_h), \
.ENABLE_VDDIO(por_lv), \
.ENABLE_VDDA_H(tie_lo[I]), \
.ENABLE_VSWITCH_H(tie_lo[I]), \
.ENABLE_INP_H(tie_lo[I]), \
.TIE_LO_ESD(tie_lo[I]), \
.TIE_HI_ESD(), \
.HLD_H_N(cfg_hi), \
.HLD_OVR(cfg_lo), \
.SLOW(cfg_lo), \
.VTRIP_SEL(cfg_lo), \
.IB_MODE_SEL(cfg_lo), \
.ANALOG_EN(cfg_lo), \
.ANALOG_SEL(cfg_lo), \
.ANALOG_POL(cfg_lo), \
.IN_H(), \
.PAD_A_ESD_0_H(), \
.PAD_A_ESD_1_H(), \
.PAD_A_NOESD_H()
// DM = 001 : input only (output driver off)
`define INPUT_PAD(INST, PADWIRE, SIGNAL, I) \
sky130_ef_io__gpiov2_pad_wrapped INST ( \
.PAD(PADWIRE), \
.IN(SIGNAL), \
.OUT(cfg_lo), \
.DM({cfg_lo, cfg_lo, cfg_hi}), \
.OE_N(cfg_hi), \
.INP_DIS(cfg_lo), \
`GPIO_COMMON(I) \
);
// DM = 110 : strong push-pull output, input buffer disabled
`define OUTPUT_PAD(INST, PADWIRE, SIGNAL, I) \
sky130_ef_io__gpiov2_pad_wrapped INST ( \
.PAD(PADWIRE), \
.IN(), \
.OUT(SIGNAL), \
.DM({cfg_hi, cfg_hi, cfg_lo}), \
.OE_N(cfg_lo), \
.INP_DIS(cfg_hi), \
`GPIO_COMMON(I) \
);
module chip_top (
// clock / reset / power good
inout wire pad_clk,
inout wire pad_rst_n,
inout wire pad_power_good,
// SPI from the host MCU
inout wire pad_cs_n,
inout wire pad_sck,
inout wire pad_mosi,
inout wire pad_ready,
// VGA
inout wire pad_hs,
inout wire pad_vs,
inout wire [2:0] pad_rgb, // {R, G, B}
// supplies
inout wire pad_vccd,
inout wire pad_vssd,
inout wire pad_vddio,
inout wire pad_vssio,
inout wire pad_vdda,
inout wire pad_vssa
);
// Supply nets
wire VCCD;
wire VSSD;
wire VDDIO;
wire VSSIO;
wire VDDA;
wire VSSA;
// Unused analog buses
wire amux_a;
wire amux_b;
// Core signals (core side of the pads)
wire clk;
wire rst_n;
wire cs_n;
wire sck;
wire mosi;
wire ready;
wire hs;
wire vs;
wire [2:0] rgb;
// Low-voltage constants and GPIO startup signals
wire cfg_hi;
wire cfg_lo;
wire por_h;
wire por_lv;
wire por_tie_hi;
wire por_tie_lo;
wire [10:0] tie_lo;
// =============================================
// Constant driver for 1.8 V GPIO controls
// =============================================
sky130_fd_sc_hd__conb_1 u_cfg_tie (
.HI(cfg_hi),
.LO(cfg_lo),
.VPWR(VCCD),
.VGND(VSSD),
.VPB(VCCD),
.VNB(VSSD)
);
// =============================================
// Hardened GPU macro
// =============================================
gpu_asic u_core (
.clk(clk),
.rst_n(rst_n),
.spi_cs_n(cs_n),
.spi_sck(sck),
.spi_mosi(mosi),
.gpu_ready(ready),
.vga_hs(hs),
.vga_vs(vs),
.vga_rgb(rgb),
.VPWR(VCCD),
.VGND(VSSD)
);
// =============================================
// Power-good input GPIO
// =============================================
// External power_good must stay low until
// the external supplies are stable.
//
// ENABLE_INP_H uses this GPIO's own ESD tie.
// IN_H and IN provide separate voltage-domain
// versions of the power-good signal.
sky130_ef_io__gpiov2_pad_wrapped u_power_good (
.PAD(pad_power_good),
.IN(por_lv),
.IN_H(por_h),
.OUT(cfg_lo),
.DM({cfg_lo, cfg_lo, cfg_hi}),
.OE_N(cfg_hi),
.INP_DIS(cfg_lo),
.ENABLE_H(por_tie_lo),
.ENABLE_INP_H(por_tie_hi),
.ENABLE_VDDIO(cfg_hi),
.ENABLE_VDDA_H(por_tie_lo),
.ENABLE_VSWITCH_H(por_tie_lo),
.TIE_HI_ESD(por_tie_hi),
.TIE_LO_ESD(por_tie_lo),
.HLD_H_N(cfg_hi),
.HLD_OVR(cfg_lo),
.SLOW(cfg_lo),
.VTRIP_SEL(cfg_lo),
.IB_MODE_SEL(cfg_lo),
.ANALOG_EN(cfg_lo),
.ANALOG_SEL(cfg_lo),
.ANALOG_POL(cfg_lo),
.PAD_A_ESD_0_H(),
.PAD_A_ESD_1_H(),
.PAD_A_NOESD_H(),
`IO_BUSES
);
// =============================================
// Five input GPIOs
// =============================================
`INPUT_PAD(u_clk, pad_clk, clk, 0)
`INPUT_PAD(u_rst_n, pad_rst_n, rst_n, 1)
`INPUT_PAD(u_cs_n, pad_cs_n, cs_n, 2)
`INPUT_PAD(u_sck, pad_sck, sck, 3)
`INPUT_PAD(u_mosi, pad_mosi, mosi, 4)
// =============================================
// Six output GPIOs
// =============================================
`OUTPUT_PAD(u_ready, pad_ready, ready, 5)
`OUTPUT_PAD(u_hs, pad_hs, hs, 6)
`OUTPUT_PAD(u_vs, pad_vs, vs, 7)
`OUTPUT_PAD(u_r, pad_rgb[2], rgb[2], 8)
`OUTPUT_PAD(u_g, pad_rgb[1], rgb[1], 9)
`OUTPUT_PAD(u_b, pad_rgb[0], rgb[0], 10)
// =============================================
// Six supply pads
// =============================================
sky130_ef_io__vccd_lvc_clamped_pad u_vccd (
.VCCD_PAD(pad_vccd),
`IO_BUSES
);
sky130_ef_io__vssd_lvc_clamped_pad u_vssd (
.VSSD_PAD(pad_vssd),
`IO_BUSES
);
sky130_ef_io__vddio_hvc_clamped_pad u_vddio (
.VDDIO_PAD(pad_vddio),
`IO_BUSES
);
sky130_ef_io__vssio_hvc_clamped_pad u_vssio (
.VSSIO_PAD(pad_vssio),
`IO_BUSES
);
sky130_ef_io__vdda_hvc_clamped_pad u_vdda (
.VDDA_PAD(pad_vdda),
`IO_BUSES
);
sky130_ef_io__vssa_hvc_clamped_pad u_vssa (
.VSSA_PAD(pad_vssa),
`IO_BUSES
);
endmodule
`undef OUTPUT_PAD
`undef INPUT_PAD
`undef GPIO_COMMON
`undef IO_BUSES
`default_nettype wireCheck the wiring in simulation first
With stand-in pad models (sim/pad_models_sim.v); run_sims.sh already ran this as test 4/6:
RTL="rtl/spi_cmd_rx.v rtl/vga_controller.v rtl/frame_buffer.v rtl/line_renderer.v rtl/rect_filler.v rtl/circle_renderer.v rtl/gpu_core.v"
iverilog -g2012 -DUSE_POWER_PINS -s tb_chip -o build/tb_chip $RTL asic/src/gpu_asic.v \
chip/rtl/chip_top.v sim/pad_models_sim.v sim/tb_chip.v
vvp -n build/tb_chip▸ Show sim/tb_chip.v · 73 lines
`timescale 1ns / 1ps
// =============================================================
// Chip-level connectivity test: chip_top.v + pad stand-ins + GPU RTL
// - outputs must stay Z while power_good is low
// - SPI in through the pads, VGA out through the pads
// Run with -DUSE_POWER_PINS so gpu_asic has VPWR/VGND ports.
// =============================================================
module tb_chip;
reg clk = 1'b0;
always #19.861 clk = ~clk; // 25.175 MHz oscillator
reg power_good = 1'b0, rst_n = 1'b0;
reg cs_n = 1'b1, sck = 1'b0, mosi = 1'b0;
wire ready, hs, vs;
wire [2:0] rgb;
wire vccd, vssd, vddio, vssio, vdda, vssa;
// inout pads need nets: drive them from the regs
wire w_clk = clk, w_rst_n = rst_n, w_pg = power_good;
wire w_cs_n = cs_n, w_sck = sck, w_mosi = mosi;
chip_top dut (
.pad_clk(w_clk), .pad_rst_n(w_rst_n), .pad_power_good(w_pg),
.pad_cs_n(w_cs_n), .pad_sck(w_sck), .pad_mosi(w_mosi), .pad_ready(ready),
.pad_hs(hs), .pad_vs(vs), .pad_rgb(rgb),
.pad_vccd(vccd), .pad_vssd(vssd), .pad_vddio(vddio),
.pad_vssio(vssio), .pad_vdda(vdda), .pad_vssa(vssa)
);
task send(input [79:0] w);
integer i;
begin
wait (ready === 1'b1);
cs_n = 0; #250;
for (i = 79; i >= 0; i = i - 1) begin
mosi = w[i]; #250 sck = 1; #250 sck = 0;
end
#250 cs_n = 1; #500;
end
endtask
integer x, y, errors = 0;
reg [2:0] expect_pix;
initial begin
#2000;
if (ready !== 1'bz || hs !== 1'bz) $fatal(1, "outputs driven while power_good is low");
$display("[1] pads tri-stated while power_good = 0");
power_good = 1'b1;
#1000 rst_n = 1'b1;
send({8'h01, 64'd0, 8'h1C}); // CLEAR green
send({8'h03, 16'd4, 16'd3, 16'd10, 16'd6, 8'hE0}); // RECT red
send({8'h02, 16'd0, 16'd29, 16'd39, 16'd0, 8'hFF}); // LINE white
wait (ready === 1'b1);
$display("[2] three commands accepted through the SPI pads");
// compare one whole frame on the RGB pads against the core memory
wait (dut.u_core.u_gpu.u_vga.h_count == 0 && dut.u_core.u_gpu.u_vga.v_count == 0);
@(posedge clk); @(posedge clk); #1; // 2-clock video pipeline
for (y = 0; y < 480; y = y + 1)
for (x = 0; x < 800; x = x + 1) begin
expect_pix = (x < 640) ? dut.u_core.u_gpu.u_fb.mem[(y >> 4) * 40 + (x >> 4)] : 3'b000;
if (rgb !== expect_pix) errors = errors + 1;
@(posedge clk); #1;
end
if (errors) $fatal(1, "%0d pixel errors on the RGB pads", errors);
$display("[3] full frame on pad_rgb matches the framebuffer");
$display("PASS: chip_top wiring (11 GPIO + power-good + supplies + macro)");
$finish;
end
initial begin #40_000_000; $fatal(1, "timeout"); end
endmodule▸ Show sim/pad_models_sim.v · 47 lines
`timescale 1ns / 1ps
// =============================================================
// SIMULATION-ONLY stand-ins for the SKY130 pad cells and the
// conb tie cell. They only model what the chip_top wiring relies on:
// - input path : IN = PAD (when INP_DIS = 0)
// - output path: PAD = OUT (when OE_N = 0 and ENABLE_H = 1)
// - TIE_HI_ESD = 1, TIE_LO_ESD = 0
// This lets us check the chip_top.v connectivity with Icarus.
// The real views come from the PDK (LEF/GDS/CDL).
// =============================================================
module sky130_ef_io__gpiov2_pad_wrapped (
output IN, output IN_H, inout PAD_A_NOESD_H, inout PAD_A_ESD_0_H, inout PAD_A_ESD_1_H,
inout PAD, input [2:0] DM, input HLD_H_N, input INP_DIS, input IB_MODE_SEL,
input ENABLE_H, input ENABLE_VDDA_H, input ENABLE_INP_H, input OE_N,
output TIE_HI_ESD, output TIE_LO_ESD, input SLOW, input VTRIP_SEL, input HLD_OVR,
input ANALOG_EN, input ANALOG_SEL, input ENABLE_VDDIO, input ENABLE_VSWITCH_H,
input ANALOG_POL, input OUT, inout AMUXBUS_A, inout AMUXBUS_B,
inout VSSA, inout VDDA, inout VSWITCH, inout VDDIO_Q, inout VCCHIB, inout VDDIO,
inout VCCD, inout VSSIO, inout VSSD, inout VSSIO_Q
);
assign TIE_HI_ESD = 1'b1;
assign TIE_LO_ESD = 1'b0;
wire inp_ok = (INP_DIS === 1'b0) && ((ENABLE_H === 1'b1) || (ENABLE_INP_H === 1'b1));
assign IN = inp_ok ? PAD : 1'b0;
assign IN_H = inp_ok ? PAD : 1'b0;
assign PAD = (OE_N === 1'b0 && ENABLE_H === 1'b1 && DM === 3'b110) ? OUT : 1'bz;
endmodule
module sky130_fd_sc_hd__conb_1 (output HI, output LO, inout VPWR, inout VGND, inout VPB, inout VNB);
assign HI = 1'b1;
assign LO = 1'b0;
endmodule
`define SUPPLY_PAD(NAME, P) \
module NAME (inout AMUXBUS_A, inout AMUXBUS_B, inout VSSA, inout VDDA, inout VSWITCH, \
inout VDDIO_Q, inout VCCHIB, inout VDDIO, inout VCCD, inout VSSIO, inout VSSD, \
inout VSSIO_Q, inout P); \
endmodule
`SUPPLY_PAD(sky130_ef_io__vccd_lvc_clamped_pad, VCCD_PAD)
`SUPPLY_PAD(sky130_ef_io__vssd_lvc_clamped_pad, VSSD_PAD)
`SUPPLY_PAD(sky130_ef_io__vddio_hvc_clamped_pad, VDDIO_PAD)
`SUPPLY_PAD(sky130_ef_io__vssio_hvc_clamped_pad, VSSIO_PAD)
`SUPPLY_PAD(sky130_ef_io__vdda_hvc_clamped_pad, VDDA_PAD)
`SUPPLY_PAD(sky130_ef_io__vssa_hvc_clamped_pad, VSSA_PAD)Expand the Verilog macros for OpenROAD
OpenROAD reads a plain structural netlist, not `define macros. Icarus expands them — this is how your chip_top_expanded.v was made:
cd ~/asic_projects/raster_gpu/chip
iverilog -E -o results/chip_top_expanded.v rtl/chip_top.v
grep -c "sky130_ef_io__gpiov2_pad_wrapped" results/chip_top_expanded.v # expect 1201_floorplan.tcl — die, macro, taps, padframe
What the script does
- Reads tech LEF, cell LEF, both I/O LEFs,
gpu_asic.lef, liberty; reads the expanded netlist and linkschip_top. - Creates the 1600×1600 µm die and the 350…1250 core.
- Places
u_coreat (440, 440) — centred — as FIRM. - New:
tapcell … -halo_width_x 10 -halo_width_y 10adds well taps / end caps and cuts the standard-cell rows around the macro. In counter8 the rows ran under the macro; everyObstructed - CORE_GRID - met1 -> met4entry in your02_failed_vias.rptsits at x ≈ 849–898 µm, inside the counter's 700–900 µm footprint. - Builds the I/O rows and corners, places the 18 pads, fills the gaps with bus slices, abuts the rings, creates the bond terminals.
- Places the conb tie cell south of the macro and legalizes it.
# =========================================================
# 01_floorplan.tcl : die, macro, taps, padframe
# Run from the chip/ folder:
# openroad -gui tcl/01_floorplan.tcl
# =========================================================
# =========================================
# SKY130 libraries
# =========================================
set PDK $::env(SKY130_PDK)
set HD "$PDK/libs.ref/sky130_fd_sc_hd"
set IO "$PDK/libs.ref/sky130_fd_io"
file mkdir results
file mkdir reports
read_lef "$HD/techlef/sky130_fd_sc_hd__nom.tlef"
read_lef "$HD/lef/sky130_fd_sc_hd.lef"
read_lef "$IO/lef/sky130_fd_io.lef"
read_lef "$IO/lef/sky130_ef_io.lef"
read_lef "macros/gpu_asic.lef"
read_liberty \
"$HD/lib/sky130_fd_sc_hd__tt_025C_1v80.lib"
# =========================================
# Load the chip Verilog (macros already expanded)
# =========================================
read_verilog "results/chip_top_expanded.v"
link_design chip_top
# =========================================
# Floorplan
# =========================================
# Die 1600 x 1600 um. Pads + corners use the outer ~210 um,
# the core ring sits between the pads and the core area.
initialize_floorplan \
-die_area {0 0 1600 1600} \
-core_area {350 350 1250 1250} \
-site unithd
make_tracks
# =========================================
# Place the hardened GPU (720 x 720 um)
# =========================================
# origin = lower-left corner. 440 + 720 = 1160 -> centred in the core.
place_inst \
-name u_core \
-origin {440 440} \
-orientation R0 \
-status FIRM
# =========================================
# Well taps + end caps
# =========================================
# -halo_* also CUTS the standard-cell rows 10 um around the macro.
# (In counter8_fullchip the rows ran under the macro, which caused
# all the "Obstructed met1 -> met4" failed vias in 02_failed_vias.rpt)
tapcell \
-distance 13 \
-tapcell_master sky130_fd_sc_hd__tapvpwrvgnd_1 \
-endcap_master sky130_fd_sc_hd__decap_3 \
-halo_width_x 10 \
-halo_width_y 10
# =========================================
# I/O placement sites
# =========================================
make_fake_io_site \
-name IO_SITE \
-width 1 \
-height 200
make_fake_io_site \
-name IO_CORNER_SITE \
-width 200 \
-height 204
make_io_sites \
-horizontal_site IO_SITE \
-vertical_site IO_SITE \
-corner_site IO_CORNER_SITE \
-offset 0 \
-rotation_horizontal R180 \
-rotation_vertical R180 \
-rotation_corner R180
# =========================================
# Corner cells
# =========================================
place_corners sky130_ef_io__corner_pad
# =========================================
# Pads (order: N/S left -> right, E/W bottom -> top)
#
# NORTH: R G B
# WEST (SPI) EAST (status + sync)
# VSSIO VSSA
# MOSI VS
# SCK HS
# CS_N READY
# VDDIO VDDA
# SOUTH: VCCD CLK RST_N PGOOD VSSD
#
# Each pad sits on the side where its macro pin is (pin_order.cfg),
# so the top-level wires stay short.
# =========================================
place_pads -row IO_SOUTH -mode uniform {u_vccd u_clk u_rst_n u_power_good u_vssd}
place_pads -row IO_WEST -mode uniform {u_vddio u_cs_n u_sck u_mosi u_vssio}
place_pads -row IO_EAST -mode uniform {u_vdda u_ready u_hs u_vs u_vssa}
place_pads -row IO_NORTH -mode uniform {u_r u_g u_b}
# ---- OPTIONAL: exact positions by hand instead of "uniform" ----
# Comment out the four place_pads lines above and use place_pad.
# -location is the offset (um) along the row from the die's lower-left
# corner. Check the result: click a pad in the GUI, the Inspector
# shows its bounding box.
#
# place_pad -row IO_SOUTH -location 300 u_vccd
# place_pad -row IO_SOUTH -location 500 u_clk
# place_pad -row IO_SOUTH -location 700 u_rst_n
# place_pad -row IO_SOUTH -location 900 u_power_good
# place_pad -row IO_SOUTH -location 1100 u_vssd
# ... same for IO_WEST / IO_EAST / IO_NORTH
# =========================================
# Fill gaps between I/O cells
# =========================================
set Fillers {
sky130_ef_io__com_bus_slice_20um
sky130_ef_io__com_bus_slice_10um
sky130_ef_io__com_bus_slice_5um
sky130_ef_io__com_bus_slice_1um
}
foreach Side {NORTH SOUTH EAST WEST} {
place_io_fill \
-row "IO_$Side" \
{*}$Fillers
}
# =========================================
# Connect adjacent padframe terminals (ring buses)
# =========================================
connect_by_abutment
# =========================================
# External pad terminals (the bond openings)
# =========================================
place_io_terminals u_*/PAD
place_io_terminals u_vccd/VCCD_PAD
place_io_terminals u_vssd/VSSD_PAD
place_io_terminals u_vddio/VDDIO_PAD
place_io_terminals u_vssio/VSSIO_PAD
place_io_terminals u_vdda/VDDA_PAD
place_io_terminals u_vssa/VSSA_PAD
# =========================================
# Configuration tie cell (south strip, between core edge and macro)
# =========================================
place_inst \
-name u_cfg_tie \
-origin {790 380} \
-orientation R0 \
-status PLACED
# Standard-cell legalization (moves the tie cell onto a legal site)
detailed_placement
check_placement -verbose
# =========================================
# Check important instances
# =========================================
set Block [ord::get_db_block]
foreach Name {
u_core
u_cfg_tie
u_clk
u_rst_n
u_power_good
u_cs_n
u_sck
u_mosi
u_ready
u_hs
u_vs
u_r
u_g
u_b
u_vccd
u_vssd
u_vddio
u_vssio
u_vdda
u_vssa
} {
if {[$Block findInst $Name] eq "NULL"} {
error "Missing instance: $Name"
}
}
# =========================================
# Save floorplan
# =========================================
write_db "results/01_floorplan.odb"
write_def "results/01_floorplan.def"
write_verilog \
-include_pwr_gnd \
"results/01_linked.v"
puts "Floorplan and padframe placement completed."cd ~/asic_projects/raster_gpu/chip
openroad -gui tcl/01_floorplan.tclCheck in the GUI
- Console ends with
Floorplan and padframe placement completed.;check_placementreports no errors. - F: four corners, 18 pads, macro in the middle — like the diagram.
- Click
u_clk: Inspector shows mastersky130_ef_io__gpiov2_pad_wrappedon the south edge; its bond opening faces outwards. - Display Control → Rows: rows stop 10 µm before the macro.
- Want exact pad positions? Use the commented
place_pad -row … -location …block, rerun, and confirm each bbox in the Inspector.
02_power.tcl — supply nets, ring, straps, macro hookup
Your counter8 power script with one change in the macro grid: the macro now exposes met4 only, so every chip-level met5 strap crossing it drops a met4-met5 via — exactly LibreLane's macro hookup (define_pdn_grid -macro … -halo + add_pdn_connect met4 met5).
# =========================================================
# 02_power.tcl : power nets, core ring, straps, macro hookup
# Run from the chip/ folder:
# openroad -gui tcl/02_power.tcl
# =========================================================
# =========================================
# Load completed floorplan
# =========================================
read_db "results/01_floorplan.odb"
set PDK $::env(SKY130_PDK)
set HD "$PDK/libs.ref/sky130_fd_sc_hd"
read_liberty \
"$HD/lib/sky130_fd_sc_hd__tt_025C_1v80.lib"
set Block [ord::get_db_block]
# =========================================
# Mark the supply networks
# =========================================
foreach {Name Type} {
VCCD POWER
VSSD GROUND
VDDIO POWER
VSSIO GROUND
VDDA POWER
VSSA GROUND
} {
set Net [$Block findNet $Name]
if {$Net eq "NULL"} {
error "Missing supply net: $Name"
}
$Net setSpecial
$Net setSigType $Type
}
# =========================================
# Register power-pin matching rules
# =========================================
# VPWR/VGND also covers the gpu_asic macro and the tap cells.
add_global_connection \
-net VCCD \
-pin_pattern {^(VPWR|VPB|VCCD)$} \
-power
add_global_connection \
-net VSSD \
-pin_pattern {^(VGND|VNB|VSSD)$} \
-ground
add_global_connection \
-net VDDIO \
-pin_pattern {^VDDIO$} \
-power
add_global_connection \
-net VSSIO \
-pin_pattern {^VSSIO$} \
-ground
add_global_connection \
-net VDDA \
-pin_pattern {^VDDA$} \
-power
add_global_connection \
-net VSSA \
-pin_pattern {^VSSA$} \
-ground
global_connect -verbose
# =========================================
# Digital-core voltage domain
# =========================================
set_voltage_domain \
-name CORE \
-power VCCD \
-ground VSSD
# =========================================
# Define the core PDN grid
# =========================================
define_pdn_grid \
-name CORE_GRID \
-voltage_domains {CORE}
# =========================================
# Core power ring (met4 vertical / met5 horizontal)
# -connect_to_pads joins the ring to the VCCD/VSSD pad pins
# =========================================
add_pdn_ring \
-grid CORE_GRID \
-layers {met4 met5} \
-widths {4 4} \
-spacings {2 2} \
-core_offsets 10 \
-connect_to_pads
# =========================================
# Standard-cell power rails (met1, on every row)
# =========================================
add_pdn_stripe \
-grid CORE_GRID \
-layer met1 \
-width 0.48 \
-followpins \
-extend_to_core_ring
# =========================================
# Upper metal power straps
# =========================================
# met5 horizontal straps run OVER the macro (the macro only uses
# met1-met4), that is how the macro gets its power.
add_pdn_stripe \
-grid CORE_GRID \
-layer met4 \
-width 1.6 \
-pitch 48 \
-offset 20 \
-extend_to_core_ring
add_pdn_stripe \
-grid CORE_GRID \
-layer met5 \
-width 1.6 \
-pitch 48 \
-offset 20 \
-extend_to_core_ring
# =========================================
# PDN vias
# =========================================
add_pdn_connect \
-grid CORE_GRID \
-layers {met1 met4}
add_pdn_connect \
-grid CORE_GRID \
-layers {met4 met5}
# =========================================
# Hard macro power grid
# =========================================
# The macro's VPWR/VGND pins are vertical met4 straps.
# Every top-level met5 strap that crosses them gets a met4-met5 via.
# -halo keeps the top-level met4 straps / rails 10 um away from it.
define_pdn_grid \
-macro \
-name GPU_GRID \
-instances {u_core} \
-starts_with POWER \
-halo {10 10}
add_pdn_connect \
-grid GPU_GRID \
-layers {met4 met5}
# =========================================
# Check and generate PDN
# =========================================
pdngen -check_only
pdngen \
-failed_via_report reports/02_failed_vias.rpt
# =========================================
# Save
# =========================================
write_db results/02_power.odb
write_def results/02_power.def
puts "Core power network generated."openroad -gui tcl/02_power.tclCheck in the GUI
- Console:
Core power network generated.reports/02_failed_vias.rptshould be (nearly) empty; nothing inside the macro outline. - Display Control → Nets: only VCCD. Follow pad → ring → met5 straps → over the macro; zoom at the macro edge: met4-met5 vias on its VPWR straps.
- Repeat for VSSD.
- Optional:
check_power_grid -net VCCD. A "no terminals" complaint is expected (the external pin ispad_vccd, joined inside the pad);help check_power_gridshows whether your build has-dont_require_terminals.
03_route.tcl — route the signals
Remaining signal nets: 11 pad ↔ macro, the power-good fan-out and the conb tie fan-out to every pad control pin.
# =========================================================
# 03_route.tcl : signal routing (pads <-> macro, tie cell)
# Run from the chip/ folder:
# openroad -gui tcl/03_route.tcl
# =========================================================
# =========================================
# Load powered layout
# =========================================
read_db "results/02_power.odb"
set PDK $::env(SKY130_PDK)
read_liberty \
"$PDK/libs.ref/sky130_fd_sc_hd/lib/sky130_fd_sc_hd__tt_025C_1v80.lib"
# =========================================
# Find legal access points for pins
# =========================================
pin_access
# =========================================
# Global routing
# =========================================
global_route \
-guide_file results/03_route.guide \
-congestion_iterations 100 \
-verbose
# =========================================
# Detailed routing
# =========================================
detailed_route \
-output_drc reports/03_route_drc.rpt \
-output_maze reports/03_maze.log
# =========================================
# Checks
# =========================================
check_antennas -report_file reports/03_antenna.rpt
# =========================================
# Save routed database
# =========================================
write_db results/03_routed.odb
write_def results/03_routed.def
write_verilog \
-include_pwr_gnd \
results/03_routed.v
puts "Detailed routing stage completed."openroad -gui tcl/03_route.tclCheck
reports/03_route_drc.rptmust be empty (as for counter8).reports/03_antenna.rpt: long nets likecfg_lomay violate; if so addrepair_antennasafterglobal_routeand rerun.- GUI: show only met2/met3 and follow
clkfromu_clkto the macro's south edge.
04_streamout.tcl — merge into chip_top.gds
Your proven Magic script: real GDS of the cells, the I/O library and the GPU macro, annotated with LEF pins, plus the routed DEF → full-chip GDS.
# =========================================================
# 04_streamout.tcl : merge everything into chip_top.gds (Magic)
# Run from the chip/ folder:
# magic -dnull -noconsole \
# -rcfile $SKY130_PDK/libs.tech/magic/sky130A.magicrc \
# tcl/04_streamout.tcl | tee reports/04_streamout.log
# =========================================================
set PDK $::env(SKY130_PDK)
set HD "$PDK/libs.ref/sky130_fd_sc_hd"
set IO "$PDK/libs.ref/sky130_fd_io"
set TechLEF "$HD/techlef/sky130_fd_sc_hd__nom.tlef"
# Technology information, including via definitions
lef read $TechLEF
# Import the actual layout geometry
gds readonly true
gds rescale false
gds read "$HD/gds/sky130_fd_sc_hd.gds"
set BaseIOGDS "$IO/gds/sky130_fd_io.gds"
if {[file exists $BaseIOGDS]} {
gds read $BaseIOGDS
}
gds read "$IO/gds/sky130_ef_io.gds"
# Load any separately installed GPIO GDS files
foreach File [glob -nocomplain "$IO/gds/*gpiov2*.gds"] {
gds read $File
}
# The hardened GPU
gds read "macros/gpu_asic.gds"
# Annotate actual GDS cells with LEF pin information
lef read "$HD/lef/sky130_fd_sc_hd.lef" -annotate
lef read "$IO/lef/sky130_fd_io.lef" -annotate
lef read "$IO/lef/sky130_ef_io.lef" -annotate
lef read "macros/gpu_asic.lef" -annotate
# Import placed cells and routed wires
def read "results/03_routed.def"
load chip_top
select top cell
# Produce candidate chip layout
gds write "results/chip_top.gds"
puts "GDS write command finished"
quit -nopromptmagic -dnull -noconsole \
-rcfile $SKY130_PDK/libs.tech/magic/sky130A.magicrc \
tcl/04_streamout.tcl | tee reports/04_streamout.log
klayout -nn $SKY130_PDK/libs.tech/klayout/tech/sky130A.lyt \
-l $SKY130_PDK/libs.tech/klayout/tech/sky130A.lyp results/chip_top.gdsYour counter8 log had 15 "problems" (Boundary is not closed in sky130_fd_io__overlay_vddio_lvc, "placed on top of itself" in I/O sub-cells). They come from the PDK I/O GDS; Magic handles them. Worry only if a message names gpu_asic or chip_top.
DRC — KLayout batch, then the Marker Browser
cd ~/asic_projects/raster_gpu/chip
DRC=$SKY130_PDK/libs.tech/klayout/drc/sky130A_mr.drc
klayout -b -zz -r $DRC -rd input=results/chip_top.gds -rd topcell=chip_top \
-rd report=reports/drc_beol.lyrdb -rd beol=true -rd thr=8
klayout -b -zz -r $DRC -rd input=results/chip_top.gds -rd topcell=chip_top \
-rd report=reports/drc_feol.lyrdb -rd feol=true -rd thr=8- Open the GDS in KLayout (previous step).
- Tools›Marker Browser → File›Open →
reports/drc_beol.lyrdb. - Left: rule names with counts. Click a marker to zoom to it.
- Sort by location. Markers inside I/O cells (
sky130_fd_io__…) are known artefacts of the open I/O library under this deck. Markers on your wiring — between pads and macro, ring, straps, vias at the macro edge — are real and must be fixed in the Tcl. - The macro alone was already DRC-checked (Magic + KLayout) inside LibreLane.
The -b -zz -r … -rd input= -rd topcell= -rd report= form is how LibreLane 3.0.17 itself calls KLayout DRC.
LVS of the top level
The macro was LVS-checked inside LibreLane. At chip level what matters is the wiring between pads, tie cell and macro: Magic extracts the top level with every cell as a LEF abstract (black box) and Netgen compares it to 03_routed.v — the same readnet/lvs recipe LibreLane uses internally.
# =========================================================
# 06_extract.tcl : top-level connectivity extraction (Magic)
# Cells are loaded as LEF ABSTRACTS, so pads / std cells / the macro
# become black boxes and only the TOP-LEVEL wiring is extracted.
# (The macro itself was already LVS-checked inside LibreLane.)
#
# magic -dnull -noconsole \
# -rcfile $SKY130_PDK/libs.tech/magic/sky130A.magicrc \
# tcl/06_extract.tcl | tee reports/06_extract.log
# =========================================================
set PDK $::env(SKY130_PDK)
set HD "$PDK/libs.ref/sky130_fd_sc_hd"
set IO "$PDK/libs.ref/sky130_fd_io"
lef read "$HD/techlef/sky130_fd_sc_hd__nom.tlef"
lef read "$HD/lef/sky130_fd_sc_hd.lef"
lef read "$IO/lef/sky130_fd_io.lef"
lef read "$IO/lef/sky130_ef_io.lef"
lef read "macros/gpu_asic.lef"
def read "results/03_routed.def"
# give the standard cells their real port order (same as LibreLane does)
readspice "$HD/spice/sky130_fd_sc_hd.spice"
load chip_top
select top cell
extract do local
extract all
ext2spice lvs
ext2spice -o results/chip_top_extracted.spice
puts "Extraction finished"
quit -noprompt# =========================================================
# 06_lvs.tcl : compare extracted top level vs 03_routed.v (Netgen)
# Same recipe LibreLane uses internally (steps/netgen.py)
# netgen -batch source tcl/06_lvs.tcl
# =========================================================
set PDK $::env(SKY130_PDK)
# layout side
set circuit1 [readnet spice results/chip_top_extracted.spice]
# schematic side: std-cell SPICE + the powered top-level netlist
set circuit2 [readnet verilog /dev/null]
readnet spice $PDK/libs.ref/sky130_fd_sc_hd/spice/sky130_fd_sc_hd.spice $circuit2
readnet verilog results/03_routed.v $circuit2
# pads + gpu_asic have no transistor netlist on either side -> black boxes
lvs "$circuit1 chip_top" "$circuit2 chip_top" \
$PDK/libs.tech/netgen/sky130A_setup.tcl \
reports/06_lvs.log \
-blackbox
puts "LVS finished, see reports/06_lvs.log"magic -dnull -noconsole -rcfile $SKY130_PDK/libs.tech/magic/sky130A.magicrc \
tcl/06_extract.tcl | tee reports/06_extract.log
netgen -batch source tcl/06_lvs.tcl
tail -30 reports/06_lvs.logIO_BUSES ties VDDIO_Q to VDDIO and VSSIO_Q to VSSIO. In the abutted padframe these are separate ring buses. If Netgen reports them merged/split, give them their own nets (wire VDDIO_Q, VSSIO_Q;), mark them POWER/GROUND in 02_power.tcl and rerun from the expand step.
Signoff checklist
| Item | Status after this tutorial |
|---|---|
| RTL function | ✔ simulated (3 configs), gate-level matches |
| Macro DRC / LVS / antenna / timing | ✔ LibreLane summary |
| Chip routing DRC (router) | ✔ 03_route_drc.rpt empty |
| Chip GDS DRC (KLayout) | ◐ review markers; I/O-cell artefacts expected |
| Chip LVS (top-level connectivity) | ◐ LVS step |
| Pin plan consistency (RTL ↔ Tcl ↔ board) | ✔ check_pins.py (Step 27) |
| Board-level I/O limits | ✔ 4 mA pads buffered by a 74LVC244A (Step 34) |
| Seal ring, metal fill / density | ✘ not done (the PDK has a Magic seal-ring generator; shuttles add fill) |
| Chip-level STA through the pads | ✘ macro is signed off; pad delays (≈2–5 ns) fit easily in 40 ns |
| ESD / supply pad count / package | ✘ one pad per supply is fine for learning; a tapeout needs a bond-diagram review |
Next step: a bigger framebuffer with SRAM
After v1 works. Swap one file (frame_buffer.v); gpu_core and everything else stay the same.
Choose the macro and the banking
Your PDK ships OpenRAM macros in libs.ref/sky130_sram_macros:
ls $SKY130_PDK/libs.ref/sky130_sram_macros/lef/
grep -E "SIZE|PIN" $SKY130_PDK/libs.ref/sky130_sram_macros/lef/sky130_sram_1kbyte_1rw1r_32x256_8.lef | head -40The design uses sky130_sram_1kbyte_1rw1r_32x256_8: 256 × 32 bit with a byte write mask, port 0 read/write, port 1 read-only — one port for drawing, one for VGA. One byte per pixel (RGB332) → 1,024 pixels per macro, so 80 × 60 = 4,800 pixels → 5 macros.
| Macro fact (from its LEF / Verilog) | Value |
|---|---|
| Size | 479.78 × 397.5 µm |
| Power pins | vccd1 / vssd1 on met3 + met4 |
| Ports | clk0 csb0 web0 wmask0[3:0] addr0[7:0] din0 dout0 · clk1 csb1 addr1[7:0] dout1 |
| Timing model | inputs latched on the rising edge, data out after the falling edge → 1-clock latency |
frame_buffer.v, SRAM version (drop-in)
Same module name, ports and one-clock read latency as rtl/frame_buffer.v. Bank and byte lane are registered so they line up with the SRAM data.
`timescale 1ns / 1ps
// =============================================================
// frame_buffer (SRAM version) - drop-in replacement for rtl/frame_buffer.v
//
// Same ports and same 1-clock read latency, but the storage is a row of
// OpenRAM macros sky130_sram_1kbyte_1rw1r_32x256_8
// port 0 (RW) : draw engines write here (byte write mask)
// port 1 (R) : VGA scan-out reads here (every clock)
//
// One macro = 256 words x 32 bit = 1024 pixels of 8 bit.
// pixel address a : bank = a / 1024, word = a[9:2], byte lane = a[1:0]
//
// 80 x 60 x 8 bit = 4800 pixels -> 5 macros
// =============================================================
module frame_buffer #(
parameter PIX_BITS = 8,
parameter DEPTH = 4800,
parameter ADDR_BITS = 13
)(
input wire clk,
// Write port
input wire write_en,
input wire [ADDR_BITS-1:0] addr_write,
input wire [PIX_BITS-1:0] write_data,
// Read port
input wire [ADDR_BITS-1:0] addr_read,
output reg [PIX_BITS-1:0] read_data
);
localparam BANKS = (DEPTH + 1023) / 1024;
localparam BANK_BITS = (ADDR_BITS > 10) ? ADDR_BITS - 10 : 1;
// which bank / byte the VGA asked for one clock ago
reg [BANK_BITS-1:0] rd_bank_d;
reg [1:0] rd_lane_d;
always @(posedge clk) begin
rd_bank_d <= addr_read[ADDR_BITS-1:10];
rd_lane_d <= addr_read[1:0];
end
wire [7:0] wr_byte = write_data; // PIX_BITS = 8 in this build
wire [3:0] wr_mask = 4'b0001 << addr_write[1:0];
wire [31:0] rd_word [0:BANKS-1];
genvar i;
generate
for (i = 0; i < BANKS; i = i + 1) begin : g_bank
wire sel_w = write_en && (addr_write[ADDR_BITS-1:10] == i);
// vccd1 / vssd1 are hooked up by LibreLane (PDN_MACRO_CONNECTIONS),
// dout0 (read data of the write port) is not needed.
/* verilator lint_off PINMISSING */
/* verilator lint_off PINCONNECTEMPTY */
sky130_sram_1kbyte_1rw1r_32x256_8 u_sram (
// port 0 : write
.clk0 (clk),
.csb0 (~sel_w), // active low chip select
.web0 (1'b0), // 0 = write
.wmask0(wr_mask),
.addr0 (addr_write[9:2]),
.din0 ({4{wr_byte}}),
.dout0 (),
// port 1 : read (always enabled)
.clk1 (clk),
.csb1 (1'b0),
.addr1 (addr_read[9:2]),
.dout1 (rd_word[i])
);
/* verilator lint_on PINCONNECTEMPTY */
/* verilator lint_on PINMISSING */
end
endgenerate
// pick the byte (combinational after the macro's own output register)
wire [31:0] sel_word = rd_word[rd_bank_d];
always @(*) begin
case (rd_lane_d)
2'd0: read_data = sel_word[ 7: 0];
2'd1: read_data = sel_word[15: 8];
2'd2: read_data = sel_word[23:16];
default: read_data = sel_word[31:24];
endcase
end
endmodule`timescale 1ns / 1ps
// =============================================================
// gpu_asic (SRAM version) : 80 x 60, 8-bit RGB332, 5 OpenRAM macros
// 5 inputs + 11 outputs = 16 signal GPIOs
// =============================================================
module gpu_asic (
`ifdef USE_POWER_PINS
inout wire VPWR,
inout wire VGND,
`endif
input wire clk,
input wire rst_n,
input wire spi_cs_n,
input wire spi_sck,
input wire spi_mosi,
output wire gpu_ready,
output wire vga_hs,
output wire vga_vs,
output wire [7:0] vga_rgb // RRRGGGBB
);
gpu_core #(
.FB_W(80),
.FB_H(60),
.SCALE_SHIFT(3), // 8 x 8 screen pixels per FB pixel
.PIX_BITS(8),
.DOUBLE_BUF(0)
) u_gpu (
.clk(clk),
.rst_n(rst_n),
.spi_cs_n(spi_cs_n),
.spi_sck(spi_sck),
.spi_mosi(spi_mosi),
.gpu_ready(gpu_ready),
.vga_hs(vga_hs),
.vga_vs(vga_vs),
.vga_pix(vga_rgb),
/* verilator lint_off PINCONNECTEMPTY */
.dbg_cmd_toggle() // debug LED output, not needed on the chip
/* verilator lint_on PINCONNECTEMPTY */
);
endmoduleSimulate with the real PDK model
cd ~/asic_projects/raster_gpu
# the PDK model prints every read unless VERBOSE is 0
sed 's/parameter VERBOSE = 1/parameter VERBOSE = 0/' \
$SKY130_PDK/libs.ref/sky130_sram_macros/verilog/sky130_sram_1kbyte_1rw1r_32x256_8.v > build/sram_model.v
SRAM_RTL="rtl/spi_cmd_rx.v rtl/vga_controller.v rtl/line_renderer.v rtl/rect_filler.v rtl/circle_renderer.v rtl/gpu_core.v asic_sram/src/frame_buffer.v"
iverilog -g2012 -DSRAM_CFG -s tb_gpu -o build/tb_sram $SRAM_RTL build/sram_model.v sim/tb_gpu.v
vvp -n build/tb_sram +frames=build/sram | grep -E "^\[|PASS|FATAL"All 8 groups pass (circles included) and so do the 36-frame cube and the 40-frame orbit. The model prints about 136 WARNING: Writing and reading … simultaneously! lines: the VGA happened to read a word in the same clock it was written. On silicon that pixel can be wrong for one frame (16 ms) and is then redrawn — invisible. sim/sram_model_sim.v is a quiet stand-in if you do not have the PDK at hand.
Harden the SRAM version with LibreLane
The macros go into MACROS (format checked against the LibreLane 3.0.17 source). Two values must come from your synthesized netlist because Yosys decides the flattened instance names:
- Synthesis only:
cd asic_sram && librelane config.json --run-tag syn --to Yosys.Synthesis - Find the names:
grep -o "[^ ]*u_sram[^ ]*" runs/syn/*-yosys-synthesis/gpu_asic.nl.v | sort -u - Put the five names into
instancesand one regex matching all five intoPDN_MACRO_CONNECTIONS(formatregex VDD_NET GND_NET macro_vdd_pin macro_gnd_pin), then run the full flow with a new tag.
{
"DESIGN_NAME": "gpu_asic",
"VERILOG_FILES": [
"dir::src/spi_cmd_rx.v",
"dir::src/vga_controller.v",
"dir::src/frame_buffer.v",
"dir::src/line_renderer.v",
"dir::src/rect_filler.v",
"dir::src/circle_renderer.v",
"dir::src/gpu_core.v",
"dir::src/gpu_asic.v"
],
"CLOCK_PORT": "clk",
"CLOCK_PERIOD": 39.72,
"PDK": "sky130A",
"STD_CELL_LIBRARY": "sky130_fd_sc_hd",
"PNR_SDC_FILE": "dir::gpu.sdc",
"SIGNOFF_SDC_FILE": "dir::gpu.sdc",
"FP_SIZING": "absolute",
"DIE_AREA": [0, 0, 1700, 1150],
"CORE_AREA": [20, 20, 1680, 1130],
"PL_TARGET_DENSITY_PCT": 40,
"PDN_MULTILAYER": true,
"PDN_CORE_RING": true,
"PDN_CORE_RING_VWIDTH": 1.6,
"PDN_CORE_RING_HWIDTH": 1.6,
"PDN_CORE_RING_VSPACING": 1.7,
"PDN_CORE_RING_HSPACING": 1.7,
"PDN_CORE_RING_VOFFSET": 6,
"PDN_CORE_RING_HOFFSET": 6,
"PDN_EXTEND_TO": "core_ring",
"MACROS": {
"sky130_sram_1kbyte_1rw1r_32x256_8": {
"gds": ["pdk_dir::libs.ref/sky130_sram_macros/gds/sky130_sram_1kbyte_1rw1r_32x256_8.gds"],
"lef": ["pdk_dir::libs.ref/sky130_sram_macros/lef/sky130_sram_1kbyte_1rw1r_32x256_8.lef"],
"nl": ["pdk_dir::libs.ref/sky130_sram_macros/verilog/sky130_sram_1kbyte_1rw1r_32x256_8.v"],
"lib": {
"*": ["pdk_dir::libs.ref/sky130_sram_macros/lib/sky130_sram_1kbyte_1rw1r_32x256_8_TT_1p8V_25C.lib"]
},
"instances": {
"REPLACE_WITH_NAME_OF_BANK0": {"location": [60, 60], "orientation": "N"},
"REPLACE_WITH_NAME_OF_BANK1": {"location": [620, 60], "orientation": "N"},
"REPLACE_WITH_NAME_OF_BANK2": {"location": [1180, 60], "orientation": "N"},
"REPLACE_WITH_NAME_OF_BANK3": {"location": [60, 620], "orientation": "N"},
"REPLACE_WITH_NAME_OF_BANK4": {"location": [620, 620], "orientation": "N"}
}
}
},
"PDN_MACRO_CONNECTIONS": [
"REPLACE_WITH_REGEX_FOR_ALL_BANKS VPWR VGND vccd1 vssd1"
]
}The SRAM power pins sit on met3/met4, so the block needs met5 straps over them: PDN_MULTILAYER is true here, with a core ring like your counter8 config_ring.json. At chip level this block then behaves like your counter8 macro (met4 + met5 power pins) — connect it with a macro grid as in counter8 and check in the GUI that ring and straps really meet. Expect a few iterations. Five macros + logic need a ≈1.7 × 1.15 mm block → ≈2.6 × 2.0 mm chip, and 16 GPIO pads (5 in, 3 status/sync, 8 colour).
Appendix
Troubleshooting by stage
| Stage | Symptom | Fix |
|---|---|---|
| Icarus | syntax error at before | SystemVerilog keyword under -g2012 — rename it |
| Icarus | testbench hangs | READY watchdog ends it after 3 M clocks; READY stuck = reset/init problem |
| Vivado | clk_wiz_0 not found | IP name exactly clk_wiz_0, then Generate Output Products |
| Vivado | ~64 BRAM instead of ~38 | DEPTH became a power of two — keep frame_buffer.v as is |
| Vivado | board shows the previous bring-up step | two gpu_core.v or two selftest.mem in Sources — remove the old step’s files |
| LibreLane | IO placement "unmatched" | a pin_order.cfg regex matches no port (escape brackets: vga_rgb\[2\]) |
| LibreLane | congestion / slow detailed routing | bigger DIE_AREA, lower PL_TARGET_DENSITY_PCT, new tag |
| LibreLane | hold violations at the ff corner | normally auto-repaired; rerun from scratch after any SDC change |
| OpenROAD 01 | Missing instance: … | stale chip_top_expanded.v → expand step |
| OpenROAD 01 | tapcell rejects -halo options | older build: cut_rows -halo_width_x 10 -halo_width_y 10 + plain tapcell |
| OpenROAD 02 | failed vias inside the macro | macro LEF has met5 power → harden with PDN_MULTILAYER false |
| OpenROAD 03 | unrouted pad nets | pad orientation — keep R180 rotations from counter8 |
| Magic 04 | GPU missing in the GDS | macros/gpu_asic.gds not copied → collect step |
| KLayout DRC | thousands of markers in I/O cells | known I/O-library artefacts — review your own wiring |
| Netgen | pin mismatch on pads | compare pin lists; VDDIO_Q/VSSIO_Q → LVS step |
Command cheat sheet
# ---------- simulation (WSL, devshell) ----------
cd ~/asic_projects/raster_gpu
bash run_sims.sh
python3 scripts/check_pins.py
python3 scripts/check_circle.py
python3 scripts/gen_selftest.py # after editing a board test
cp fpga/selftest.mem /mnt/c/fpga/raster_gpu/fpga/
gtkwave sim/wave.gtkw
# ---------- FPGA bring-up (Vivado, Windows) ----------
# step 1: rtl/vga_controller.v + bringup/step1_vga/* top = vga_test_top, vga_test.xdc
# step 2: + spi_cmd_rx, frame_buffer, rect_filler, bringup/step2_rect/{gpu_core.v,selftest.mem},
# fpga/fpga_top.v, spi_test_host.v, pynq_gpu.xdc top = fpga_top (disable vga_test.xdc)
# step 3: + rtl/line_renderer.v, core + ROM -> bringup/step3_line/*
# step 4: + rtl/circle_renderer.v, core + ROM -> rtl/gpu_core.v, fpga/selftest.mem
# SW0 up: test 1 runs by itself; SW1 down BTN1-3 = new tests, SW1 up = previous step's
# ---------- macro (LibreLane) ----------
cd ~/asic_projects/raster_gpu/asic
librelane config.json --run-tag gpu_v1
librelane --last-run --flow OpenInOpenROAD config.json
librelane --last-run --flow OpenInKLayout config.json
# ---------- chip ----------
cd ~/asic_projects/raster_gpu/chip
iverilog -E -o results/chip_top_expanded.v rtl/chip_top.v
openroad -gui tcl/01_floorplan.tcl
openroad -gui tcl/02_power.tcl
openroad -gui tcl/03_route.tcl
magic -dnull -noconsole -rcfile $SKY130_PDK/libs.tech/magic/sky130A.magicrc tcl/04_streamout.tcl
klayout -b -zz -r $SKY130_PDK/libs.tech/klayout/drc/sky130A_mr.drc \
-rd input=results/chip_top.gds -rd topcell=chip_top -rd report=reports/drc_beol.lyrdb -rd beol=true
magic -dnull -noconsole -rcfile $SKY130_PDK/libs.tech/magic/sky130A.magicrc tcl/06_extract.tcl
netgen -batch source tcl/06_lvs.tclGlossary
| Term | Meaning here |
|---|---|
| CDC | clock domain crossing — a signal moving between unrelated clocks (here: SPI and reset pins → 25 MHz) |
| STA / SDC | static timing analysis / the constraints file it reads (gpu.sdc) |
| LEF / DEF / GDS | abstract cell view (size, pins, blockages) / placed + routed design / final mask geometry |
| PDN | power distribution network: rings, straps, rails, vias |
| CTS | clock tree synthesis |
| DRC / LVS | design-rule check / layout-versus-schematic connectivity check |
| POR / power-good | signal that says the supplies are stable; enables the pad drivers |
| Hard macro | a pre-placed-and-routed block (gpu_asic) used as one cell by the chip |
| RGB332 / RGB111 | 8-bit colour 3-3-2 / 3-bit colour 1-1-1 |
| vblank | the 45 non-visible lines between frames |
| Bresenham | line algorithm with an integer error term: adds and compares only, one pixel per step |
| Midpoint circle | circle algorithm: walks one octant, decides each step by the sign of f at the midpoint between two candidate pixels |
| Octant | one eighth of the circle (45°); the other seven are mirror images |
| Span | a horizontal run of pixels on one row (how filled circles are drawn) |
| AR0 … AR13 | the PYNQ-Z2 names of its Arduino-connector sockets (an Uno prints 0 … 13) |
| Loopback | feeding a circuit's own output back into its input to test the path without the real partner |
| Clipping | dropping (or not walking) the part of a shape that is outside the screen |
All remaining files
▸ Show scripts/check_circle.py · 75 lines
#!/usr/bin/env python3
"""
check_circle.py - checks the circle algorithm of rtl/circle_renderer.v
(independent of the RTL and of the testbench model).
python3 scripts/check_circle.py [max_r] (default 400)
For every radius 0..max_r:
1. every outline pixel is within half a pixel of the true circle
( |x^2 + y^2 - r^2| <= r )
2. the outline has no gaps (every pixel has an 8-neighbour, r >= 1)
3. the filled disc writes no pixel twice
4. the filled disc is exactly "each row filled between the leftmost and
the rightmost outline pixel" (so outline and fill always match)
Then prints the clock counts used in the guide.
"""
import math, sys
def steps(r):
"""octant 0 of the midpoint circle: yields (x, y, d, last) per step"""
x, y, d = r, 0, 1 - r
while True:
yn = y + 1
xn = x if d < 0 else x - 1
dn = d + 2 * yn + 1 if d < 0 else d + 2 * (yn - xn) + 1
last = xn < yn
yield x, y, d, last
if last:
return
x, y, d = xn, yn, dn
def outline(r):
pts = []
for x, y, d, last in steps(r):
pts += [(x, y), (y, x), (-y, x), (-x, y), (-x, -y), (-y, -x), (y, -x), (x, -y)]
return pts
def spans(r):
"""the spans circle_renderer.v walks in filled mode: (row, half_width)"""
out = []
for x, y, d, last in steps(r):
out.append((y, x)) # s = 0
if y != 0:
out.append((-y, x)) # s = 1
if (d >= 0 or last) and x != y:
out += [(x, y), (-x, y)] # s = 2, 3
return out
max_r = int(sys.argv[1]) if len(sys.argv) > 1 else 400
bad = 0
for r in range(max_r + 1):
out = set(outline(r))
fill = [(i, row) for row, h in spans(r) for i in range(-h, h + 1)]
if any(abs(px * px + py * py - r * r) > r for px, py in out):
bad += 1; print('r =', r, ': outline pixel too far from the circle')
if r >= 1 and any(not any((px + a, py + b) in out for a in (-1, 0, 1) for b in (-1, 0, 1) if a or b)
for px, py in out):
bad += 1; print('r =', r, ': gap in the outline')
if len(fill) != len(set(fill)):
bad += 1; print('r =', r, ': filled disc writes a pixel twice')
hull = set()
for row in {py for _, py in out}:
xs = [px for px, py in out if py == row]
hull |= {(i, row) for i in range(min(xs), max(xs) + 1)}
if set(fill) != hull:
bad += 1; print('r =', r, ': filled disc does not match the outline')
print(f'radii 0..{max_r}:', 'ALL CHECKS PASSED' if not bad else f'{bad} PROBLEM(S)')
print()
print(' r steps outline clocks filled pixels (pi r^2) filled clocks @25 MHz')
for r in (3, 10, 50, 100, 200):
n = sum(1 for _ in steps(r))
fp = sum(2 * h + 1 for _, h in spans(r))
print(f'{r:4d} {n:6d} {8*n:15d} {fp:14d} {math.pi*r*r:9.0f} {fp+4*n:14d} {(fp+4*n)/25e3:8.2f} ms')
sys.exit(1 if bad else 0)▸ Show scripts/check_vga_test.py · 45 lines
#!/usr/bin/env python3
"""
check_vga_test.py - checks the bring-up step 1 test pictures (bringup/step1_vga/vga_pattern.v)
pixel by pixel against an independent model, and writes PNGs.
python3 scripts/check_vga_test.py [build/vga_test]
The .hex files come from sim/tb_vga_test.v (run_sims.sh stage 7).
"""
import os, sys
D = sys.argv[1] if len(sys.argv) > 1 else 'build/vga_test'
BARS = [0xFFF, 0xFF0, 0x0FF, 0x0F0, 0xF0F, 0xF00, 0x00F, 0x000]
def model(sel, x, y, invert=False):
cx, cy, ix, iy = x // 40, y // 40, x % 40, y % 40
if sel == 0:
c = 0xF00 if x in (0, 639) or y in (0, 479) else (0x000 if (cx ^ cy) & 1 else 0xFFF)
elif sel == 1:
c = BARS[cx // 2] if y < 320 else cx * 0x111
elif sel == 2:
c = [cx << 8, cx << 4, cx, cx * 0x111][min(y // 120, 3)]
else:
c = 0xFFF if ix == 0 or iy == 0 or x == 639 or y == 479 or x == 320 or y == 240 else 0x000
return c ^ 0xFFF if invert else c
cases = [(0, 0, False, 'checkerboard'), (1, 1, False, 'colour bars + grey ramp'), (2, 2, False, 'DAC ramps'),
(3, 3, False, 'grid'), (4, 0, True, 'inverted checkerboard')]
bad = 0
for n, sel, inv, name in cases:
px = [int(l, 16) for l in open(f'{D}/pattern_{n}.hex').read().split()]
if len(px) != 640 * 480:
print(f'pattern {n}: {len(px)} pixels'); bad += 1; continue
wrong = sum(1 for i, p in enumerate(px) if p != model(sel, i % 640, i // 640, inv))
print(f'pattern {n} ({name:24s}): {"OK" if not wrong else str(wrong) + " pixels differ"}')
bad += wrong != 0
try:
from PIL import Image
im = Image.new('RGB', (640, 480))
im.putdata([(((p >> 8) & 15) * 17, ((p >> 4) & 15) * 17, (p & 15) * 17) for p in px])
im.save(f'{D}/pattern_{n}.png')
except ImportError:
pass
print('RESULT:', 'ALL 5 PICTURES MATCH THE MODEL' if not bad else f'{bad} PROBLEM(S)')
sys.exit(1 if bad else 0)▸ Show sim/tb_vga_test.v · 72 lines
`timescale 1ns / 1ps
// =============================================================
// tb_vga_test : bring-up step 1 bitstream (vga_test_top) in simulation
//
// Captures one full 640x480 frame from the VGA pins for every
// picture: checkerboard (after reset), colour bars (BTN2),
// DAC ramps (BTN3), grid (SW1), inverted checkerboard (BTN1 + SW0).
// Each pixel is written as 3 hex digits RGB444 to
// build/vga_test/pattern_<n>.hex; scripts/check_vga_test.py compares
// every pixel with an independent model and makes the PNGs.
// =============================================================
module tb_vga_test;
reg sysclk = 1'b0, btn0 = 1'b1;
reg [2:0] btn = 3'b000;
reg [1:0] sw = 2'b00;
wire hs, vs; wire [3:0] r, g, b, led;
vga_test_top dut (.sysclk(sysclk), .reset(btn0), .btn(btn), .sw(sw),
.vga_hs(hs), .vga_vs(vs), .vga_r(r), .vga_g(g), .vga_b(b), .led(led));
always #20 sysclk = !sysclk; // 25 MHz through the clk_wiz stand-in
// capture: pins carry the pixel of the counters seen 2 clocks earlier
integer hd1 = 0, vd1 = 0, hd2 = 0, vd2 = 0, st = 0, fd = 0, hs_low = 0, n_hs = 0;
always @(negedge sysclk) begin
if (st == 1 && hd2 == 0 && vd2 == 0) st = 2;
if (st == 2) begin
if (hd2 < 640 && vd2 < 480) $fwrite(fd, "%h%h%h\n", r, g, b);
if (vd2 == 100 && hd2 >= 640 && hs === 1'b0) hs_low = hs_low + 1; // HSYNC width
if (hd2 == 799 && vd2 == 524) st = 3;
end
hd2 = hd1; vd2 = vd1;
hd1 = dut.u_vga.h_count; vd1 = dut.u_vga.v_count;
end
task capture(input [8*48-1:0] fname);
begin
fd = $fopen(fname, "w"); st = 1;
wait (st == 3); st = 0; $fclose(fd);
end
endtask
task press(input integer k);
begin
@(negedge sysclk) btn[k] = 1'b1;
repeat (10) @(negedge sysclk);
btn[k] = 1'b0;
end
endtask
initial begin
repeat (50) @(negedge sysclk);
btn0 = 1'b0;
wait (dut.top_reset === 1'b0); // clock locked, reset released
repeat (5) @(negedge sysclk);
capture("build/vga_test/pattern_0.hex"); // checkerboard right after reset
if (hs_low != 96) $fatal(1, "HSYNC low for %0d clocks, expected 96", hs_low);
$display("[1] checkerboard after reset, HSYNC pulse = %0d clocks", hs_low);
press(1); capture("build/vga_test/pattern_1.hex");
$display("[2] BTN2: colour bars + grey ramp");
press(2); capture("build/vga_test/pattern_2.hex");
$display("[3] BTN3: DAC ramps");
sw[1] = 1'b1; repeat (10) @(negedge sysclk);
capture("build/vga_test/pattern_3.hex");
$display("[4] SW1: 1-pixel grid");
sw[1] = 1'b0; sw[0] = 1'b1; press(0);
capture("build/vga_test/pattern_4.hex");
$display("[5] BTN1 + SW0: inverted checkerboard");
$display("PASS: step 1 (VGA controller + adapter) frames captured");
$finish;
end
endmodule▸ Show sim/tb_selftest.v · 134 lines
`timescale 1ns / 1ps
// =============================================================
// tb_selftest : the PYNQ-Z2 top level with its on-board SPI test host
//
// Runs fpga_top (real file, Clocking Wizard replaced by sim/clk_wiz_sim.v)
// as it is built in bring-up step 2, 3 or 4 (iverilog -DSTEP=n, compiled
// with that step's gpu_core.v and engine files, -DROM="<its selftest.mem>"):
// the power-up test (test 1 runs by itself with SW0 = 1),
// tests 1..6 by "pressing" BTN1..BTN3 with SW1 down and up
// (step 2: tests 4..6 are empty - checked that they send nothing),
// then test 2 again with SW0 = 0 and the SPI header wired back into the
// Arduino header pins (the loopback test).
// After each test one VGA frame is captured to build/selftest/board_<n>.hex.
// run_sims.sh compares them with frames that tb_gpu.v verified against its
// golden model for the same commands.
// =============================================================
`ifndef STEP
`define STEP 4
`endif
`ifndef ROM
`define ROM "fpga/selftest.mem"
`endif
module tb_selftest;
reg sysclk = 1'b0;
reg btn0 = 1'b1; // reset held
reg [2:0] btn = 3'b000;
reg [1:0] sw = 2'b01; // SW0 = 1: internal test host
reg loopback = 1'b0; // jumper wires SPI header -> AR10/11/13
wire t_cs, t_sck, t_mosi, ready, hs, vs;
wire [3:0] r, g, b, led;
// what the Arduino header sees: the loopback wires, or nothing (pulls)
wire ar10 = loopback ? t_cs : 1'b1;
wire ar13 = loopback ? t_sck : 1'b0;
wire ar11 = loopback ? t_mosi : 1'b0;
fpga_top #(.DEBOUNCE_BITS(4), .ROM_FILE(`ROM)) dut (
.sysclk(sysclk), .reset(btn0), .btn(btn), .sw(sw),
.spi_cs_n(ar10), .spi_sck(ar13), .spi_mosi(ar11), .gpu_ready(ready),
.test_cs_n(t_cs), .test_sck(t_sck), .test_mosi(t_mosi),
.vga_hs(hs), .vga_vs(vs), .vga_r(r), .vga_g(g), .vga_b(b), .led(led)
);
always #20 sysclk = !sysclk; // 25 MHz (the stand-in passes it through)
// ---------------- frame capture (same alignment as tb_gpu.v) ----------------
integer hd1 = 0, vd1 = 0, hd2 = 0, vd2 = 0, cap_state = 0, cap_fd = 0;
always @(negedge sysclk) begin
if (cap_state == 1 && hd2 == 0 && vd2 == 0) cap_state = 2;
if (cap_state == 2) begin
if (hd2 < 640 && vd2 < 480) $fwrite(cap_fd, "%h\n", dut.pix);
if (hd2 == 799 && vd2 == 524) cap_state = 3;
end
hd2 = hd1; vd2 = vd1;
hd1 = dut.u_gpu.u_vga.h_count; vd1 = dut.u_gpu.u_vga.v_count;
end
task capture(input [8*64-1:0] fname);
begin
cap_fd = $fopen(fname, "w");
cap_state = 1;
wait (cap_state == 3);
cap_state = 0;
$fclose(cap_fd);
end
endtask
// press a button long enough for the debouncer, then wait for the test
task run_test(input integer n);
integer k;
begin
k = (n - 1) % 3;
sw[1] = (n > 3);
@(negedge sysclk) btn[k] = 1'b1;
wait (dut.test_busy === 1'b1);
repeat (100) @(negedge sysclk);
btn[k] = 1'b0;
wait (dut.test_busy === 1'b0);
wait (ready === 1'b1); // last command (the SWAP) done
end
endtask
reg [8*64-1:0] fname;
integer n, cmds0;
initial begin
repeat (50) @(negedge sysclk);
btn0 = 1'b0; // release BTN0
wait (ready === 1'b1);
$display("[1] step %0d: reset released, power-up clear done, READY = 1", `STEP);
// power-up picture: test 1 starts by itself because SW0 = 1
wait (dut.test_busy === 1'b1);
wait (dut.test_busy === 1'b0);
wait (ready === 1'b1);
capture("build/selftest/auto.hex");
$display("[2] power-up: test 1 ran by itself, %0d commands", n_cmds);
for (n = 1; n <= 6; n = n + 1) begin
cmds0 = n_cmds;
if (`STEP == 2 && n > 3) begin
// step 2 has no earlier step: tests 4..6 are empty
run_test(n);
repeat (2000) @(negedge sysclk);
if (n_cmds != cmds0) $fatal(1, "empty test %0d sent %0d commands", n, n_cmds - cmds0);
$display("[3] test %0d: empty, sends nothing (as it should in step 2)", n);
end
else begin
run_test(n);
$sformat(fname, "build/selftest/board_%0d.hex", n);
capture(fname);
$display("[3] test %0d: %0d commands over SPI, frame -> %0s", n, n_cmds - cmds0, fname);
end
end
// loopback: GPU listens to the Arduino header, test host drives the SPI header
sw[0] = 1'b0; loopback = 1'b1;
cmds0 = n_cmds;
run_test(2);
capture("build/selftest/board_2_loop.hex");
$display("[4] loopback (SPI header -> AR10/AR11/AR13, SW0 = 0): test 2, %0d commands", n_cmds - cmds0);
$display("PASS: bring-up step %0d: power-up test + 6 tests + loopback", `STEP);
$finish;
end
// count completed SPI frames seen by the GPU
integer n_cmds = 0;
always @(posedge sysclk) if (dut.u_gpu.cmd_valid) n_cmds = n_cmds + 1;
initial begin
#2_000_000_000; // 2 s simulated: something is stuck
$fatal(1, "timeout (test_busy %b, ready %b)", dut.test_busy, ready);
end
endmodule▸ Show scripts/hex2png.py · 22 lines
#!/usr/bin/env python3
"""Turn a captured VGA frame (.hex, 640x480 lines) into a PNG.
python3 scripts/hex2png.py <fpga|asic|sram> build/fpga_test.hex out.png
needs: pip install pillow --break-system-packages
"""
import sys
from PIL import Image
kind, src, dst = sys.argv[1], sys.argv[2], sys.argv[3]
vals = [int(l, 16) for l in open(src) if l.strip()]
img = Image.new('RGB', (640, 480))
px = []
for v in vals:
if kind in ('fpga', 'sram'): # RGB332 -> RGB444 -> 8 bit
r4 = ((v >> 5) << 1) | (v >> 7)
g4 = (((v >> 2) & 7) << 1) | ((v >> 4) & 1)
b4 = ((v & 3) << 2) | (v & 3)
px.append((r4 * 17, g4 * 17, b4 * 17))
else: # RGB111
px.append((255 * ((v >> 2) & 1), 255 * ((v >> 1) & 1), 255 * (v & 1)))
img.putdata(px)
img.save(dst)
print('wrote', dst)▸ Show sim/sram_model_sim.v · 22 lines
`timescale 1ns / 1ps
// SIMULATION-ONLY behavioural stand-in for the OpenRAM macro, written to
// match the PDK model's timing: inputs captured on posedge, data out on the
// following negedge (so it is valid at the next posedge = 1 clk latency).
// For real work use $SKY130_PDK/libs.ref/sky130_sram_macros/verilog/*.v
module sky130_sram_1kbyte_1rw1r_32x256_8 (
input clk0, input csb0, input web0, input [3:0] wmask0, input [7:0] addr0,
input [31:0] din0, output reg [31:0] dout0,
input clk1, input csb1, input [7:0] addr1, output reg [31:0] dout1
);
reg [31:0] mem [0:255];
reg csb0_r, web0_r, csb1_r; reg [3:0] wm_r; reg [7:0] a0_r, a1_r; reg [31:0] d0_r;
always @(posedge clk0) begin csb0_r <= csb0; web0_r <= web0; wm_r <= wmask0; a0_r <= addr0; d0_r <= din0; end
always @(posedge clk1) begin csb1_r <= csb1; a1_r <= addr1; end
always @(negedge clk0) if (!csb0_r && !web0_r) begin
if (wm_r[0]) mem[a0_r][ 7: 0] <= d0_r[ 7: 0];
if (wm_r[1]) mem[a0_r][15: 8] <= d0_r[15: 8];
if (wm_r[2]) mem[a0_r][23:16] <= d0_r[23:16];
if (wm_r[3]) mem[a0_r][31:24] <= d0_r[31:24];
end
always @(negedge clk1) if (!csb1_r) dout1 <= mem[a1_r];
endmodule