PYNQ-Z2 → SKY130 · open-source RTL-to-GDS · tutorial

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.

3
builds from one RTL
8 × 3
self-checking test groups
0
Verilator -Wall warnings
12,176
SKY130 cells (v1)
38 / 140
PYNQ-Z2 BRAMs
11 + 1
GPIO pads + power-good

Every code block below is the file in the zip, byte for byte, and every simulation picture was produced from those files.

00

The plan

Read this once: what you build, how the Arduino talks to the GPU, what is already verified, and where each tool runs.

01

What we are building

read

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.

Host MCUArduino Unoor ESP32gpu_core.vone 25 MHz clock · same RTL on PYNQ-Z2 and SKY130spi_cmd_rx2-FF sync80-bit shiftregisterdecodeRECT clipcolour latchacceptline_rendererBresenhamrect_fillerRECT + CLEARcircle_renderermidpoint · fillinit sweepclear after resetpixel writerpick engineclip to screeny · W + x+ back bufferframe_bufferFPGA: BRAMASIC: flopsv2: SRAMvga_ctrl640x480countersscalingswap logicat vblankVGA DACPMOD adapteror resistorsMonitor640x480 @ 60CS · SCK · MOSIwrrdfront / back buffer selectgpu_ready — flow control back to the hostengines: only "plot (x, y)"
diagramEverything inside the dashed box runs on one 25 MHz clock. The only clock-domain crossings are the SPI pins and the reset pin.
Build 1 · FPGA (PYNQ-Z2)Build 2 · ASIC v1Build 3 · ASIC v2 (Part 7)
Framebuffer320 × 240, double buffered40 × 30, single80 × 60, single
Pixel format8 bit RGB332 (256 colours)3 bit RGB111 (8 colours)8 bit RGB332
StorageBlock RAM (38 × RAMB36)3,600 standard-cell flip-flops5 × OpenRAM SRAM macros
Screen scaling2 × 216 × 168 × 8
Pixel clock25.000 MHz (MMCM)25.175 MHz oscillator25.175 MHz oscillator
CommandsCLEAR · LINE · RECT · CIRCLE (outline / filled) · SWAPsamesame
Signal pins4 SPI + 14 VGA + 4 LED11 GPIO + power-good16 GPIO + power-good
Verified hereRTL sim, Yosys xc7 estimateRTL + gate-level sim, synthesisRTL 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 %:

ASIC v1 cell area by module (Yosys + sky130_fd_sc_hd tt): 170,275 µm² (flattened: 168,414 µm², 12,176 cells)141.9k µm² · 83%frame_buffer: 3,600 flops + read mux · 141,929 µm² (83.4 %)circle_renderer · 10,762 µm² (6.3 %)line_renderer · 6,790 µm² (4.0 %)spi_cmd_rx · 5,398 µm² (3.2 %)gpu_core glue (clip, address, init) · 2,754 µm² (1.6 %)vga_controller + rect_filler · 2,642 µm² (1.6 %)Each pixel bit ≈ 30 µm² of flop + its share of the read mux.All the drawing logic together is ~17 % of the macro.One 1 KB OpenRAM macro (8,192 bits) is 479.78 × 397.5 µm,~23 µm² per bit including its periphery → Part 7.
diagramMeasured: Yosys synthesis of gpu_asic (each module kept separate) against sky130_fd_sc_hd__tt_025C_1v80.lib.
02

The pin protocol: SPI + READY

read

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.
byte 0opcode02byte 1A[15:8]00byte 2A[7:0]02byte 3B[15:8]00byte 4B[7:0]01byte 5C[15:8]00byte 6C[7:0]09byte 7D[15:8]00byte 8D[7:0]04byte 9colourE0A = int16 : x0 · x · cxB = int16 : y0 · y · cyC = int16 : x1 · w · rD = int16 : y1 · h · fillRRRGGGBBOpcodes: 01 CLEAR · 02 LINE · 03 RECT · 04 SWAP · 05 CIRCLE. Example above: 02 0002 0001 0009 0004 E0 = LINE (2,1) → (9,4), red.CS low for the whole frame · SPI mode 0 · MSB first · exactly 80 rising SCK edges · CS high → the GPU executes it.
diagramThe 10-byte command frame with a real example (the LINE used in the waveform pictures).
waitREADY = 1 ?CS lowsend 10 bytesop A B C D colourCS highGPU executesREADY low while busyrepeat for every command · CLEAR ≈ 3 ms on the FPGA, a line a few µs, SWAP up to one frame (16.7 ms)
diagramWhat the host does for every command (gpuSend() in the sketch).

Command set

OpcodeNameABCDWhat the GPU doesGPU busy time
0x01CLEAR––––fills the whole (back) buffer with the colourW·H clocks · 3.07 ms FPGA, 48 µs ASIC
0x02LINEx0y0x1y1Bresenham, both end points drawn, off-screen pixels skippedmax(|dx|,|dy|) + 1 clocks
0x03RECTxywhfilled rectangle, clipped (negative x/y allowed)visible w·h clocks
0x04SWAP––––FPGA: flip buffers at the next vblank · ASIC: wait for vblank≤ 16.7 ms
0x05CIRCLEcxcyrfillmidpoint circle; D bit 0: 0 = outline, 1 = filled disc; clippedoutline ≈ 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 sketchRGB332bits RRRGGGBBFPGA (RGB444 out)ASIC v1 (RGB111 out)
WHITE0xFF11111111FFF111
YELLOW0xFC11111100FF0110
CYAN0x1F000111110FF011
GREEN0x1C000111000F0010
MAGENTA0xE311100011F0F101
RED0xE011100000F00100
BLUE0x030000001100F001
ORANGE0xF011110000F90110
GREY0x921001001099A111
BLACK0x0000000000000000
!
Host timing rules
  • 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.
03

What is already verified

readverified

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.

CheckToolResult
Self-checking testbench, FPGA parameters — 8 groups (incl. 15 circles) vs a golden modelIcarus Verilog 12PASS
Same testbench, ASIC v1 parametersIcarus Verilog 12PASS
Same testbench, SRAM framebuffer with the real OpenRAM model (VLSIDA sky130_sram_macros)IcarusPASS
Full 800 × 525 VGA frame from the pins, pixel + HSYNC + VSYNC, every configIcarusPASS
Demos, every frame checked, 3 configs: pattern, starburst, circles, cube (36 frames), orbit (40 frames)IcarusPASS
Bring-up step 1 (VGA controller + adapter): real vga_test_top, 5 pictures from the VGA pins vs an independent pixel model, HSYNC widthIcarus + scripts/check_vga_test.py5 × 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 outputIcarus (sim/tb_selftest.v)identical to golden-model frames
Refactored RTL vs the previous version: 111 cube + starburst frames from the VGA pins, 3 buildscmpbyte-identical
Circle algorithm, radii 0…400: on the circle, no gaps, no overdraw, fill = outline rowsscripts/check_circle.pyALL CHECKS PASSED
chip_top.v wiring: pads Hi-Z before power-good, SPI in / VGA out through padsIcarus + pad stand-insPASS
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 coreVerilator 5.0200 warnings
Synthesis to sky130_fd_sc_hd (tt corner)Yosys 0.7012,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 RTLYosys + Icarusidentical 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_xilinx38 RAMB36 · ~930 LUT · 468 FF · 2 DSP48
LibreLane config keys, Classic step names, PDN macro rules, Netgen recipe, KLayout DRC argumentsLibreLane 3.0.17 sourcechecked
Arduino sketch (both TARGET values)g++ with an Arduino API stubcompiles, no warnings
Every pin across XDC, sketch, pin_order.cfg, chip_top.v and the floorplan; divider / DAC electrical limitsscripts/check_pins.pyALL CONNECTIONS CONSISTENT
!
Not run here — check on your machine

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.

04

Where each tool runs

read
TaskToolRuns inHow you start it
RTL simulationIcarus Verilog 13 + vvpWSL, inside the LibreLane devshellbash run_sims.sh
WaveformsGTKWaveWSL (WSLg window)gtkwave sim/wave.gtkw
FPGA build + programmingVivadoWindowsStart menu
Arduino sketchArduino IDE 2WindowsStart menu
Macro hardeningLibreLane 3.0.17 (Yosys, OpenROAD, Magic, KLayout, Netgen)WSL devshelllibrelane config.json …
Chip padframe / PDN / routeOpenROAD (GUI)WSL devshellopenroad -gui tcl/01_floorplan.tcl
GDS merge, extractionMagicWSL devshellmagic -dnull -noconsole …
DRC / layout viewingKLayoutWSL devshellklayout …
LVSNetgenWSL devshellnetgen -batch source …
★
Your environment

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.

05

Unpack the project

WSL

Do

  1. Click Download the project at the top. It lands in C:\Users\Sam\Downloads.
  2. Open Ubuntu and paste:
terminalBashWSL
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 && ls

Expected

project layoutText
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 command
i
One source of truth

rtl/ 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/.

01

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.

06

How the RTL is organised (read this first)

readverified

One interface for every drawing engine

Every engine — line, rectangle, circle — has the same shape:

PortMeaning
start + argumentsone-clock pulse from gpu_core; the arguments are valid in that clock and are copied inside
busyhigh 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.

line_rendererplot · x, y (12-bit signed)rect_fillerplot · x, y (unsigned, on screen)circle_rendererplot · px, py (15-bit signed)selectthe engine whoseplot = 1plot_x/yclip0 ≤ x < W0 ≤ y < Hdraw_weaddressback_base+ y · W + xinit sweepuntil init_doneframe_bufferwrite portdraw_colorlatched on acceptThe engines know nothing about the screen size, the colour or the memory layout: they only walk their shape.Clipping, colour and addressing are written once, here — and one multiply-by-constant is shared by all three engines.
diagramThe shared pixel writer in gpu_core.v. Before this version the line engine had its own clipper and each engine computed its own addresses.

Coding rules used in every file

RuleWhy
One clock (25 MHz) for everything; SPI pins and rst_n are synchronizedno 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 starta 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 bug I hit while cleaning up — worth remembering

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)

ModuleBeforeAfterChange
spi_cmd_rx5,789 µm²5,398 µm²−7 % (no reset on the shift register)
line_renderer8,448 µm²6,790 µm²−20 % (no SETUP state, no own clipper/multiplier)
rect_filler2,355 µm²1,297 µm²−45 % (walks x/y, no address arithmetic)
gpu_core glue2,246 µm²2,754 µm²+23 % (now holds the shared clipper + address)
vga_controller1,346 µm²1,345 µm²same
logic without framebuffer20,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.

07

spi_cmd_rx.v — SPI receiver and CDC

readverified

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.

spi_sck pinasynchronoussck_s[0]DQsck_s[1]DQsck_s[2]DQsck_riseone-clock pulseclk 25 MHzFF1 may go metastable → it gets a whole clock period (40 ns) to settle before FF2 samples it.Only [1] and [2] feed logic. CS uses the same 3-flop chain, MOSI the first two, so all keep the same latency.
diagramOne SPI pin through its synchronizer shift register. sck_s[0] may go metastable; sck_s[1] is clean; sck_s[2] is one clock older for edge detection.

Step by step

  1. 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.
  2. 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.
  3. MOSI goes through the same two first stages, so mosi_s[1] is exactly the bit that was on the wire when SCK rose.
  4. cs_fall clears bit_count. Each sck_rise with CS low shifts one bit in and counts it (the counter stops at 81, so a long frame stays invalid).
  5. cs_rise with bit_count == 80 copies the shift register to cmd_word and pulses cmd_valid for one clock. Any other count: the frame is ignored.
  6. After reset bit_count starts 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.
PortDirWidthMeaning
clk, resetin125 MHz clock, synchronous reset
spi_cs_n / spi_sck / spi_mosiin1raw SPI pins (asynchronous)
bus_idleout1CS high for two clocks (part of READY)
cmd_validout1one-clock pulse: a complete frame arrived
cmd_wordout80the frame, byte 0 (opcode) in bits 79:72
rtl/spi_cmd_rx.vVerilogDownload
`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

endmodule
Oversampling SCK: the pin shifts through sck_s[0] → [1] → [2]; rise = [1] & ~[2] 54000 ns 54100 ns 54200 ns 54300 ns 54400 ns 54500 ns 54600 ns 54700 ns clk 25 MHz spi_sck (pin) sck_s[2:0] 111 110 100 000 001 011 111 110 100 000 sck_rise spi_mosi (pin) mosi_s[1:0] 00 bit_count 10 11
simulationOne SCK edge in the simulator: the pin rises, the 1 walks through sck_s (001 → 011 → 111), sck_rise is high for exactly one clock, and bit_count counts the bit.
One 80-bit SPI frame: LINE (2,1)→(9,4) colour E0 50 us 60 us 70 us 80 us 90 us cmd_valid spi_cs_n spi_sck spi_mosi bit_count 81 80 cmd_valid cmd_word x gpu_ready
simulationA whole LINE frame: 80 SCK pulses, bit_count reaches 80, CS rises, cmd_valid pulses and the line starts. READY is low during the frame and while the line draws.
i
Speed limit, explained

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.

08

vga_controller.v — VGA timing and scaling

readverified

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.

Horizontalvisible640 clksync96 clkfront 16 · back 48800Verticalvisible480 linesfront 10 · sync 2 · back 3352525.175 MHz / 800 = 31.47 kHz line rate · / 525 = 59.94 Hz frame rate · both syncs are active-LOWvblank_start pulses when the vertical counter enters line 480 (start of front porch) → buffer swaps happen here
diagram640×480 @ 60 Hz timing. Counter values, not microseconds.

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_valid keeps RGB black until the power-up clear is done.

The two-stage pipeline

ClockWhat happensSignals
tcounters give the screen position → framebuffer addressh_count, v_count, fb_addr
t + 1the framebuffer returns the pixel; visible/sync are delayed by one flop to stay alignedfb_data, visible_d, h_sync_d
t + 2everything is registered on the output pins togetherpixel, 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.

PortDirWidthMeaning
clk, resetin1pixel clock = system clock
frame_validin1force black until the power-up clear is done
fb_addroutADDR_BITSpixel index into one buffer
fb_datainPIX_BITSpixel, one clock after fb_addr
vblank_startout1pulse at line 480, column 0
hsync, vsync, pixelout1 / 1 / PIX_BITSregistered, 2 clocks after the counters
rtl/vga_controller.vVerilogDownload
`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

endmodule
Screen line ~100 (FB row 6): green rectangle at FB x=3..6, blue circle row at x=28..34 3195 us 3200 us 3205 us 3210 us 3215 us 3220 us 3225 us HSYNC HSYNC h_count counting… visible fb_x 0 1 2 3 4 5 6 7 8 9 vga_rgb 000 010 000 001 000 vga_hs
simulationASIC config, screen line ~100 = FB row 6: the green rectangle (FB x = 3…6) and one row of the filled blue circle (FB x = 28…34), each FB pixel 16 clocks wide; HSYNC low for 96 clocks.
09

frame_buffer.v — one write port, one read port

read

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 initial block. Silicon powers up with random contents; gpu_core clears 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.
rtl/frame_buffer.vVerilogDownload
`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

endmodule
i
Read during write

If 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.

★
This file is the swap point for Part 7

The SRAM version keeps the module name, ports and one-clock read latency, so nothing else changes.

10

line_renderer.v — Bresenham lines, explained

readverified

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:

QuantityValueMeaning
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 −1direction of travel in x and y
e(u, v)v · dx + u · dyline equation: 0 exactly on the line (u, v = steps taken in x, y)
erre of the diagonal neighbourstarts 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 dy to err for an x-step and dx for a y-step: err is again the error of the new diagonal neighbour.
Bresenham, all octants (the reference model in tb_gpu.v is exactly this)Text
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 y

Worked 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:

Clockplot (x, y)erre2 = 2·erre2 ≥ dy → xe2 ≤ dx → ynext err
1(2,1)48yesno4 -3 = 1
2(3,1)12yesyes1 +4 = 5
3(4,2)510yesno5 -3 = 2
4(5,2)24yesyes2 +4 = 6
5(6,3)612yesno6 -3 = 3
6(7,3)36yesyes3 +4 = 7
7(8,4)714yesno7 -3 = 4
8(9,4)4———end point → busy = 0
012345678910110123451422433844855126612771688169LINE (2,1) → (9,4)dx = 7, dy = −3err₀ = dx + dy = 4every clock:e2 = 2·erre2 ≥ dy → x += 1, err += dye2 ≤ dx → y += 1, err += dx8 pixels → 8 clockssmall number = fb address (y·40 + x)
diagramThe 8 pixels the simulation wrote, numbered in draw order, with their framebuffer addresses (y · 40 + x on the ASIC).

From algorithm to hardware

AlgorithmRTLHardware
dx, dy, err, sx, sy at the startadx_in, ady_in computed straight from the inputs; loaded on start2 subtractors + 2 negators, no extra clock
plot(x, y)plot = busy; x, y are registersevery busy clock is a pixel
the end testat_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 decisionsstep_x = (e2 >= dy_w), step_y = (e2 <= dx_w)2 comparators
err updateerr + add_x + add_yone 3-input adder
IDLEbusy = 0, plot = 0DRAW (busy)plot (x, y) this clockstartx,y ← x0,y0 · dx, dy, err, sx, sy from the inputs!at_end: step x and/or y,update errat_end — the last pixel was plotted in this same clock
diagramOnly two states. The arguments are copied on start; the end point is detected in the clock that plots it, so a single-point line writes exactly once.

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_core drops 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.
PortDirWidthMeaning
startin1one-clock pulse, x0…y1 valid
x0, y0, x1, y1inCW signedend points
busyout1walking the line
plot, x, yout1, CW signedpixel (x, y) this clock
rtl/line_renderer.vVerilogDownload
`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

endmodule
Bresenham line (2,1) → (9,4): one pixel per clock, 8 pixels in 8 clocks 89300 ns 89400 ns 89500 ns 89600 ns 89700 ns 89800 ns clk start busy = plot x x 2 3 4 5 6 7 8 9 y x 1 2 3 4 err x 4 1 5 2 6 3 7 4 step_x step_y fb_waddr x 42 43 84 85 126 127 168 169 x fb_we
simulationThe same line in the simulator: start, 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.
11

rect_filler.v — rectangles and CLEAR

readverified

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

  1. On start: x ← x0, y ← y0, remember x0 (start of every row), x1 and y1.
  2. Every busy clock plots (x, y). If x ≠ x1: x ← x + 1.
  3. Else, if y ≠ y1: next row — x ← x0, y ← y + 1.
  4. Else (x1, y1) was the last pixel: busy ← 0.
Clockxyaddress y·40 + xnext
136243x+1
246244x+1
356245x+1
466246row end → x = 3, y = 7
537283x+1
……
867286done
i
Where did the address arithmetic go?

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².

rtl/rect_filler.vVerilogDownload
`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

endmodule
Rectangle x=3 y=6 w=4 h=2: x walks 3..6, then the next row; address = y*40 + x 140600 ns 140700 ns 140800 ns 140900 ns 141000 ns 141100 ns clk start busy = plot x x 3 4 5 6 3 4 5 6 y x 6 7 fb_waddr x 243 244 245 246 283 284 285 286 fb_we
simulationRECT x=3 y=6 w=4 h=2: x walks 3…6 on row 6, then 3…6 on row 7 — eight clocks for eight pixels; the pixel writer turns them into addresses 243…246 and 283…286.
12

circle_renderer.v — midpoint circles, outline and filled

readverified

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.

+x+y (screen: down)k=0 (+x,+y)k=1 (+y,+x)k=2 (−y,+x)k=3 (−x,+y)k=4 (−x,−y)k=5 (−y,−x)k=6 (+y,−x)k=7 (+x,−y)walkedOnly octant 0 is computed:from (r, 0) to the 45° diagonal, where x = y.Every point (x, y) found there gives 8 pixelsby swapping x/y and flipping signs:px = cx + ox, py = cy + oyIn hardware: one 3-bit counter k andone case statement → ox, oy.koxoy0+x+y1+y+x2−y+x3−x+ykoxoy4−x−y5−y−x6+y−x7+x−y
diagramThe 8-way symmetry. The engine computes the amber point; the case statement on k produces the seven mirrored copies.

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):

x−2x−1xx+1y+2y+1yy−1PcurrentAd < 0Bd ≥ 0true circleMOctant 0, drawn with y going UP. P = (x, y) was just drawn.The next pixel is one row up: A = (x, y+1) or B = (x−1, y+1).Test the MIDPOINT between them, M = (x − ½, y + 1):d = f(M) = (x − ½)² + (y + 1)² − r²d < 0 → M is inside → the circle passes outside M → Ad ≥ 0 → M is outside → the circle passes inside M → BNext d from the old d (no squares in hardware):A: d += 2·y′ + 1B: d += 2·(y′ − x′) + 1(y′, x′ = the NEW y and x)
diagramOne decision. d is f evaluated at the midpoint M; its sign picks the pixel.

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):

ChoiceNew midpointd′ − dUpdate in the RTL
A: x stays (d < 0)(x − ½, y′ + 1)(y′+1)² − y′² = 2·y′ + 1d + 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).

midpoint circle, octant 0 (circle_renderer.v and the testbench model do exactly this)Text
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)dd < 0 ?next (x′, y′)d′last?
1(7,0)-6yes(7,1)-6 + 2·1 + 1 = -3no
2(7,1)-3yes(7,2)-3 + 2·2 + 1 = 2no
3(7,2)2no(6,3)2 + 2·(3−6) + 1 = -3no
4(6,3)-3yes(6,4)-3 + 2·4 + 1 = 6no
5(6,4)6no(5,5)6 + 2·(5−5) + 1 = 7no
6(5,5)7no(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 sRowFrom … toDrawn when
0cy + ycx − x … cx + xevery step
1cy − ycx − x … cx + xevery step except y = 0 (that row is span 0)
2cy + xcx − y … cx + yonly 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)
3cy − xcx − y … cx + ysame as span 2
OUTLINE r = 7 · 6 steps × 8 clocks123456FILLED r = 7 · each row onceoctant 0, step numberthe 7 mirrored copiesrows cy ± y (every step)rows cy ± x (last step of each x)Both pictures were produced by the same Python model the testbench uses; the red square is the centre.
diagramr = 7. Left: the outline, octant 0 numbered by step. Right: the filled disc, coloured by which kind of span drew each row.
✓
Checked for every radius from 0 to 400

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.

IDLEbusy = 0S_POINTSplot point k, k += 1S_SPAN_SETpick span s, clip itS_SPAN_RUNplot run_x, run_x += 1start, fill = 0start, fill = 1k = 7: step (x, y, d)k = 7 & lastspan visiblerun_x = run_end: s += 1span hidden: s += 1run_x < run_end: run_x += 1s = 3 & lastA "step" moves (x, y, d) to the next point of octant 0: after the 8th point (outline) or after the 4th span (filled).The engine is busy until the step with x′ < y′ ("last"). Only S_POINTS and S_SPAN_RUN plot a pixel.
diagramThree states while busy. The outline uses S_POINTS only; the filled disc alternates S_SPAN_SET (choose + clip span s) and S_SPAN_RUN (one pixel per clock).

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

gpu_demo.inoArduino C++
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 RGB332

How long it takes

python3 scripts/check_circle.pyText
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 ms

Steps ≈ 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².

PortDirWidthMeaning
start, fillin1one-clock pulse; fill = D bit 0
cx_in, cy_ininCW signedcentre (sign-extended by gpu_core)
r_ininRWradius, unsigned
busyout1drawing
plot, px, pyout1, CW signedpixel this clock
rtl/circle_renderer.vVerilogDownload
`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

endmodule
CIRCLE outline, centre (20,15), r = 3: 3 steps x 8 points = 24 clocks 192000 ns 192200 ns 192400 ns 192600 ns 192800 ns 193000 ns clk busy k x 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 x x 3 2 1 y x 0 1 2 3 d x -2 1 2 7 px x 23 20 17 20 23 21 19 17 19 21 23 22 18 22 21 py x 15 18 15 12 15 16 18 16 14 12 14 17 13 18 plot
simulationOutline, centre (20,15), r = 3. k counts 0…7 for each step; (x, y, d) go (3,0,−2) → (3,1,1) → (2,2,2); px/py are the eight mirrored points; plot is high all 24 clocks.
CIRCLE filled, centre (31,6), r = 3: 7 rows, 37 pixels, 49 clocks 243500 ns 244000 ns 244500 ns 245000 ns clk busy state RUN SET RUN RUN RUN RUN RUN RUN SET s (span) 0 1 2 3 0 1 2 3 0 1 2 3 0 x 1 3 2 1 y 3 0 1 2 3 run_row x 6 7 5 9 3 8 4 run_x x 34 34 34 32 32 33 33 plot
simulationFilled, centre (31,6), r = 3. SET clocks choose and clip a span, RUN clocks plot it: rows 6, 7, 5, 9, 3, 8, 4 — every row once, 37 pixels in 49 clocks.
13

gpu_core.v — decode, pixel writer, reset, double buffering

readverified

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:

  1. Reset synchronizer — a 2-bit shift register: rst_n low sets it at once (asynchronously), release happens on a clock edge two clocks later. Everything else uses the clean synchronous reset.
  2. Power-up clear — init_addr walks the whole memory writing 0, one word per clock. RGB is forced black and READY is low until init_done.
  3. 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.
  4. 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 into draw_color.
  5. 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.
  6. Engines — one start pulse each; the circle gets its centre sign-extended to 15 bits and fill = D[0].
  7. 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.
  8. SWAP / double buffering — drawing always targets the back buffer. SWAP sets swap_pending; at vblank_start the buffers flip. With DOUBLE_BUF = 0 SWAP only waits for vblank (used by the ASIC sketch to start drawing during blanking).
  9. Framebuffer + VGA — the init sweep owns the write port until done; the VGA reads the front buffer.
Host MCUArduino Unoor ESP32gpu_core.vone 25 MHz clock · same RTL on PYNQ-Z2 and SKY130spi_cmd_rx2-FF sync80-bit shiftregisterdecodeRECT clipcolour latchacceptline_rendererBresenhamrect_fillerRECT + CLEARcircle_renderermidpoint · fillinit sweepclear after resetpixel writerpick engineclip to screeny · W + x+ back bufferframe_bufferFPGA: BRAMASIC: flopsv2: SRAMvga_ctrl640x480countersscalingswap logicat vblankVGA DACPMOD adapteror resistorsMonitor640x480 @ 60CS · SCK · MOSIwrrdfront / back buffer selectgpu_ready — flow control back to the hostengines: only "plot (x, y)"
diagramThe whole core. Only one engine is busy at a time — the testbench checks that on every clock.
VGA showsGPU drawshost sendsbuffer 0buffer 0buffer 1vblankvblankCLEAR buf 112 LINEsSWAP pending → READY low (waits)CLEAR buf 0SWAPThe monitor never sees a half-drawn frame: drawing always targets the hidden buffer, and the flip happens only at vblank.
diagramDouble buffering on the FPGA: the host draws into the hidden buffer and SWAP flips at vblank.

How one command travels through the core

ClockWhat happensSignal to watch
hostCS rises after 80 SCK edgesspi_cs_n
+2CS has passed the synchronizeru_spi.cs_s[1]
+3rising edge seen, 80 bits → cmd_valid = 1 for one clock; READY dropscmd_valid, gpu_ready
+3accept = cmd_valid & idle → one engine gets start; the colour is latchedaccept, u_*.start
+4 …engine busy, one pixel per clock: plot → clip → address → writeplot, fb_we, fb_waddr
endbusy = 0 → READY = 1 → the host may send the next commandgpu_ready
ParameterFPGAASIC v1ASIC v2Effect
FB_W × FB_H320 × 24040 × 3080 × 60framebuffer size
SCALE_SHIFT143screen px per FB px = 2^shift
PIX_BITS838RGB332 or RGB111
DOUBLE_BUF100second buffer + flip at vblank
COORD_BITS121212signed coordinate range ±2047
i
On the FPGA you build this core in three steps

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.

rtl/gpu_core.vVerilogDownload
`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)
    );

endmodule
Reset release → power-up clear of all 1200 pixels → READY 10 us 20 us 30 us 40 us 50 us rst_n released init_done rst_n (pin) reset (sync) init_addr counting… 1199 fb_we init_done gpu_ready
simulationASIC config: reset released → 1,200 clear writes (48 µs) → init_done → READY. The FPGA needs 153,600 clocks (6.1 ms).
02

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.

14

The self-checking testbench

WSLdevshellverified

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.

GroupWhat 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
sim/tb_gpu.vVerilogDownload
`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

endmodule

Do

  1. Start the LibreLane devshell the same way you did for counter8.
  2. Run:
terminalBashWSL · devshell
cd ~/asic_projects/raster_gpu
bash run_sims.sh
▸ Show run_sims.sh · 80 lines
run_sims.shBashDownload
#!/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)

expected output (real run) · about 5 minutesText
=== 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 PASSED

If it fails

MessageMeaning
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 Ma 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 oncea start pulse reached an engine while another was busy — check idle / accept
buffer swap outside vblankSWAP logic broken
syntax error near beforebefore is a SystemVerilog keyword under -g2012
★
Turn a captured frame into a PNG

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.

15

Read the waveforms in GTKWave

WSLGUI

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.

terminalBashWSL
cd ~/asic_projects/raster_gpu
gtkwave sim/wave.gtkw          # if missing: sudo apt install gtkwave
  1. 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.
  2. Click the Zoom Fit toolbar button (magnifier with a box) to see the whole run.
  3. 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 with u_circ.busy for the two circles.
  4. Right-click a bus → Data Format›Decimal to switch between hex and decimal.
  5. Drag the primary marker (left click in the wave area) onto a sck_rise pulse and read the values in the signal column.
  6. Compare with the pictures in Part 1 — they were drawn from this same VCD.
▸ Show sim/tb_wave.v · 68 lines
sim/tb_wave.vVerilogDownload
`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
sim/wave.gtkwTextDownload
[*] 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]
16

Render the demos in simulation

WSLverified

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:

terminalBashWSL · devshell
# 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
scripts/gen_demo.pyPythonDownload
#!/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()
03

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.

17

Pinout: which connector does what (and why the Arduino header)

readverified

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:

ConnectorReachable from the fabric (PL)?Free pinsVerdict
PMOD A (JA)yesonly pins JA-1 (Y18) and JA-7 (U18)2 pins — not enough
PMOD B (JB)yesnonefull
Raspberry Pi headeryesmany — but the PYNQ-Z2 shares 8 RPi pins with PMOD Aclashes 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–AR13yes — every AR socket is a PL I/O pin14 digital + GNDchosen for the Arduino
SPI header (2×3)yes — AR_SS, AR_SCK, AR_MOSI, AR_MISO are PL pins4used 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 labelConnector · pinFPGA pinUsed forUno position
AR8 · AR9J3 · 1, 2V17 · V18—8 · ~9
AR10J3 · 3T16spi_cs_n (in)~10 (SS)
AR11J3 · 4R17spi_mosi (in)~11 (MOSI)
AR12J3 · 5P18gpu_ready (out)12 (MISO)
AR13J3 · 6N17spi_sck (in)13 (SCK)
GNDJ3 · 7—groundGND
A · AR_SDA · AR_SCLJ3 · 8, 9, 10Y13 · P16 · P15—AREF · SDA · SCL
AR0 … AR7J4 · 1 … 8T14 U12 U13 V13 V15 T15 R16 U17—0 … 7
AR_SS · AR_SCK · AR_MOSISPI header · 5, 3, 4F16 · H15 · T12test 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)MinMax
Board powered — recommended−0.2 V3.4 V
Board powered — absolute−0.4 V3.75 V
Board unpowered — absolute−0.4 V0.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.

PYNQ-Z2connection map — not a physical drawingZynq XC7Z020 · programmable logicfpga_top → gpu_coreevery pin below is a plain PL pin(LVCMOS33, 3.3 V)Arduino headerAR10 CS_N · T16AR11 MOSI · R17AR12 READY · P18AR13 SCK · N17SPIPMOD A (JA)HSYNC · VSYNC · B[3:0]JA1 / JA7 freePMOD B (JB)R[3:0] · G[3:0]all 8 usedyour video adapter→ VGA monitorLD0–LD3statusBTN0–3 · SW0–1reset · tests125 MHzH16SPI header (2×3)test host out · loopbackRPi headershares PMOD A pins → avoidArduino → Arduino header (AR10–AR13) · video adapter → PMOD A + B · on-board test host → SPI header · no ARM PS involved
diagramWhere everything goes on the PYNQ-Z2. The Arduino is a separate board on jumper wires; nothing passes through the ARM side.

The Arduino connector pins used

PYNQ-Z2 connector J3 (pin 1 = AR8 … pin 10 = SCL), labels as in the PYNQ-Z2 reference manualAR8AR9AR10spi_cs_nT16AR11spi_mosiR17AR12gpu_readyP18AR13spi_sckN17GNDGNDASDASCLGND sits right next to AR13, so all five wires go to one 5-socket group (AR10 … GND). "A" (Y13) is where an Uno has AREF.Every AR socket has a 200 Ω series resistor on the board. AR0–AR7, power and A0–A5 stay empty. 3.3 V logic only.
diagramPYNQ-Z2 connector J3, pins 1 … 10. Four signals and GND sit next to each other.

Your video adapter (unchanged)

PMOD A (JA) — sync + blue1—Y18 (1_P2HSYNCY19 (1_N3B2Y16 (2_P4B0Y17 (2_N5GND63V37—U18 (3_P8VSYNCU19 (3_N9B3W18 (4_P10B1W19 (4_N11GND123V3PMOD B (JB) — red + green1G2W14 (1_P2G0Y14 (1_N3R2T11 (2_P4R0T10 (2_N5GND63V37G3V16 (3_P8G1W16 (3_N9R3V12 (4_P10R1W13 (4_N11GND123V3Physical pin numbers (1–6 one row, 7–12 the other; pin 1 is marked on the board). 5/11 = GND, 6/12 = 3.3 V (up to 1 A).Small grey text = the signal name in the PYNQ-Z2 manual: pin 2 is called JA1_N, so "JA2" alone is ambiguous — this guide says JA-2 for pin 2.
diagramPMOD A and B exactly as in your old pynq.xdc, checked against the PYNQ-Z2 manual (tables 13 and 14). Full pin tables: Step 18.

Complete FPGA pin map

fpga_top portFPGA pinBoard connector · labelConnects to
sysclkH16on-board 125 MHz—
resetD19BTN0—
btn[2:0]L19 L20 D20BTN3 BTN2 BTN1start test 1/2/3 (or 4/5/6)
sw[1:0]M19 M20SW1 SW0test bank · SPI source
spi_cs_nT16J3 · AR10Uno pin ~10 (via divider)
spi_mosiR17J3 · AR11Uno pin ~11 (via divider)
gpu_readyP18J3 · AR12Uno pin 8 (direct)
spi_sckN17J3 · AR13Uno pin 13 (via divider)
——J3 · GNDUno GND
test_cs_n / test_sck / test_mosiF16 / H15 / T12SPI header · AR_SS / AR_SCK / AR_MOSIloopback wires to AR10 / AR13 / AR11
vga_hs / vga_vsY19 / U19PMOD A pin 2 / pin 8adapter HSYNC / VSYNC
vga_b[3:0]W18 Y16 W19 Y17PMOD A pins 9 3 10 4adapter blue DAC
vga_r[3:0]V12 T11 W13 T10PMOD B pins 9 3 10 4adapter red DAC
vga_g[3:0]V16 W14 W16 Y14PMOD B pins 7 1 8 2adapter green DAC
led[3:0]M14 N16 P14 R14LD3 … LD0—
✓
Verified

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.

18

Connection reference: every connector, pin by pin

hardwareread

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)

PartSettingWhy
JP1 boot-mode jumperJTAGthe PL is loaded from Vivado; with SD the PYNQ image would load its own bitstream
J9 power jumper (next to SW1)USBpower from the micro-USB port (REG = from the DC jack, 7–15 V, 12 V recommended)
micro-USB (PROG / UART)to the PCpower + JTAG programming
Arduino shield (joystick)removedits buttons sit on AR2–AR8 and it may drive pins
SW0 / SW1both down (OFF)start in "Arduino" mode with test bank 1–3; change when a step says so

1 · Which wires exist in which mode

ModeSW0Wires on the PYNQ-Z2Who sends SPIStep
Step 1 · VGA test—only the video adapter on PMOD A + Bnobody (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 + Bbuilt-in test host, inside the FPGAStep 23
B · loopbackdown (OFF)adapter + 3 jumpers SPI header → J3 (AR_SCK→AR13, AR_MOSI→AR11, AR_SS→AR10)test host, through the real pinsStep 26
C · Arduinodown (OFF)adapter + 5 wires to J3 (AR10, AR11, AR12, AR13, GND) via the breadboardthe UnoStep 29
!
Never mix B and C

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

PinManual nameFPGA pinfpga_top portAdapter functionWhat a meter / scope sees
1JA1_PY18—unused (pull-down by default)0 V
2JA1_NY19vga_hsHSYNCidle 3.3 V, 96-clock low pulse every line (31.25 kHz); DC meter ≈ 2.9 V
3JA2_PY16vga_b[2]blue bit 20 V on black; toggles with the picture
4JA2_NY17vga_b[0]blue bit 0 (LSB)0 V on black; toggles with the picture
5GND——adapter ground (both rows)0 V
63V3——not needed by a resistor DAC3.3 V
7JA3_PU18—unused (pull-down by default)0 V
8JA3_NU19vga_vsVSYNCidle 3.3 V, 2-line low pulse every frame (59.5 Hz); DC meter ≈ 3.3 V
9JA4_PW18vga_b[3]blue bit 3 (MSB)0 V on black; toggles with the picture
10JA4_NW19vga_b[1]blue bit 10 V on black; toggles with the picture
11GND——adapter ground (both rows)0 V
123V3——not needed by a resistor DAC3.3 V

3 · PMOD B (JB) — your video adapter: red + green

PinManual nameFPGA pinfpga_top portAdapter functionWhat a meter / scope sees
1JB1_PW14vga_g[2]green bit 20 V on black; toggles with the picture
2JB1_NY14vga_g[0]green bit 0 (LSB)0 V on black; toggles with the picture
3JB2_PT11vga_r[2]red bit 2 (weight 4)0 V on black; toggles with the picture
4JB2_NT10vga_r[0]red bit 0 (LSB, weight 1)0 V on black; toggles with the picture
5GND——adapter ground (both rows)0 V
63V3——not needed by a resistor DAC3.3 V
7JB3_PV16vga_g[3]green bit 3 (MSB)0 V on black; toggles with the picture
8JB3_NW16vga_g[1]green bit 10 V on black; toggles with the picture
9JB4_PV12vga_r[3]red bit 3 (MSB, weight 8)0 V on black; toggles with the picture
10JB4_NW13vga_r[1]red bit 1 (weight 2)0 V on black; toggles with the picture
11GND——adapter ground (both rows)0 V
123V3——not needed by a resistor DAC3.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

PinLabelFPGA pinfpga_top portDirConnects toIdle level
1AR8V17——leave empty—
2AR9V18——leave empty—
3AR10T16spi_cs_ninUno ~10 via divider · or loopback wire from AR_SS3.0 V idle (Uno) · 3.3 V (pull-up, nothing plugged)
4AR11R17spi_mosiinUno ~11 via divider · or loopback wire from AR_MOSI0 V idle
5AR12P18gpu_readyoutUno pin 8, direct wire3.3 V when ready
6AR13N17spi_sckinUno 13 via divider · or loopback wire from AR_SCK0 V idle (mode 0)
7GND———breadboard − rail (Uno GND)0 V
8AY13——leave empty—
9AR_SDAP16——leave empty—
10AR_SCLP15——leave empty—

5 · SPI header (2×3) — test host output, loopback only

PinLabelFPGA pinfpga_top portDirConnects to
1AR_MISOW15——leave empty
23V3——powernever connect (3.3 V supply)
3AR_SCKH15test_sckoutwire → AR13 (loopback only)
4AR_MOSIT12test_mosioutwire → AR11 (loopback only)
5AR_SSF16test_cs_noutwire → AR10 (loopback only)
6GND———not needed (same board)

6 · Connectors that stay empty

ConnectorPinsWhy empty
Arduino J4AR0 … 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_RSTnever connect the Uno's 5 V or 3.3 V here — the boards share only GND
Arduino J1 (analog)A0 … A5XADC inputs
Raspberry Pi header—shares 8 pins with PMOD A (your video)

7 · Buttons, switches and LEDs

PartFPGA pinPortFunction
BTN0D19resethold = everything in reset (the screen goes black, then the power-up clear runs)
BTN1 / BTN2 / BTN3D20 / L20 / L19btn[0..2]run test 1 / 2 / 3 (with SW1 up: 4 / 5 / 6) · step 1: checkerboard / colour bars / DAC ramps
SW0M20sw[0]up: GPU listens to the test host, test 1 runs by itself after reset · down: Arduino connector · step 1: invert
SW1M19sw[1]test bank: down = the step’s new tests 1–3, up = tests 4–6 (the previous step’s) · step 1: grid
LD0R14led[0]gpu_ready — on when the GPU accepts a command
LD1P14led[1]clock locked — must always be on
LD2N16led[2]toggles with every accepted command (flickers while drawing)
LD3M14led[3]heartbeat ≈ 0.75 Hz; steady on while a test runs

8 · The Uno side

Uno pin (printed)Arduino nameIn the sketchModeGoes to
13D13 / SCKhardware SPI (SPI.h)outputbreadboard col 2 → 2.2 kΩ → col 6 → PYNQ AR13
~11D11 / MOSIhardware SPIoutputcol 9 → 2.2 kΩ → col 13 → PYNQ AR11
~10D10 / SSPIN_CS = 10outputcol 16 → 2.2 kΩ → col 20 → PYNQ AR10
12D12 / MISO(taken by SPI.h)inputnothing — keep free
8D8PIN_READY = 8inputPYNQ AR12, direct wire
GNDGND——breadboard − rail
5V, 3.3V, VIN———nothing

9 · Check before you power anything

#Check (boards unpowered, meter in continuity / Ω)Expected
1Uno GND ↔ PYNQ J3 pin 7 (GND)beep
2Uno pin 13 ↔ PYNQ AR13≈ 2.2 kΩ (the series resistor)
3Uno ~11 ↔ AR11 and Uno ~10 ↔ AR10≈ 2.2 kΩ each
4AR13, AR11, AR10 ↔ GND≈ 3.3 kΩ each (or a little less)
5Uno pin 8 ↔ AR12beep (direct wire)
6AR12 ↔ any other AR pin, any AR pin ↔ 5V / 3V3open — no beep
7nothing on J7, J4, J1, the RPi header or the SPI headerlook
#Check (PYNQ powered and programmed, Arduino running the sketch, meter in DC V)Expected
8AR10 (CS) while idle≈ 3.0 V
9AR13 (SCK), AR11 (MOSI) while idle≈ 0 V
10AR12 (READY)≈ 3.3 V (LD0 on)
11PMOD 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.

19

Vivado: create the project (empty — the bring-up fills it)

WindowsGUI

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.

StepWhat you add (in this order)Top · constraintsTest ROMOn the monitor
1 · VGA controllerrtl/vga_controller.v + bringup/step1_vga/vga_pattern.v, vga_test_top.vvga_test_top · vga_test.xdc—checkerboard, colour bars, DAC ramps, grid
2 · SPI + framebuffer + RECTrtl/spi_cmd_rx.v, frame_buffer.v, rect_filler.v, bringup/step2_rect/gpu_core.v + fpga/fpga_top.v, spi_test_host.vfpga_top · pynq_gpu.xdcbringup/step2_rect/selftest.mem“HI”, colour bars, blocks off the edges
3 · + LINErtl/line_renderer.v; the core becomes bringup/step3_line/gpu_core.vsamebringup/step3_line/selftest.memstarburst, string art, a house
4 · + CIRCLErtl/circle_renderer.v; the core becomes rtl/gpu_core.v (the final one)samefpga/selftest.memtarget, 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

  1. 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/
  2. Vivado → Quick Start›Create Project → Next. Name raster_gpu_pynq, location C:\fpga, tick Create project subdirectory → Next.
  3. Project type RTL Project, tick Do not specify sources at this time → Next.
  4. Default Part: type xc7z020clg400-1 in Search, select the row → Next → Finish. No board file is needed.
i
One rule for every Add Sources in this guide

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.

20

Vivado: Clocking Wizard (125 → 25 MHz)

WindowsGUI

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

  1. Flow Navigator›PROJECT MANAGER›IP Catalog → search Clocking Wizard → double-click.
  2. Top of the dialog: Component Name = clk_wiz_0 (both top levels instantiate it by this name).
  3. Tab Clocking Options: Primitive MMCM. Input Clock Information → Primary: Input Frequency 125.000 MHz, Source Single ended clock capable pin.
  4. Tab Output Clocks: clk_out1 Requested 25.000 MHz (Actual shows 25.000). Only clk_out1 ticked.
  5. Same tab, bottom: keep reset and locked ticked, Reset Type Active High.
  6. Tabs Port Renaming / MMCM Settings: leave defaults. Summary shows VCO 1000 MHz, divide 40.
  7. OK → Generate (out-of-context is fine). Wait for clk_wiz_0_synth_1 in the Design Runs tab.

Expected

Sources › IP Sources lists clk_wiz_0. Nothing uses it yet; the step-1 top level does.

i
Why 25.000 and not 25.175 MHz

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.

21

Vivado: the build → program loop (you repeat it in every step)

WindowsGUIhardware

Do

  1. Flow Navigator›PROGRAM AND DEBUG›Generate Bitstream → Yes (runs synthesis + implementation) → OK. A few minutes.
  2. The first time, choose View Reports and check the numbers below. Later: just continue.
  3. Set the PYNQ-Z2 boot jumper JP1 to JTAG (so the PYNQ Linux image does not reload the PL), connect micro-USB, power on.
  4. Open Hardware Manager›Open Target›Auto Connect → Program Device → the .bit is pre-filled → Program. The Hardware Manager stays connected; next time only Program Device.
  5. Your adapter on PMOD A + B, the monitor connected.

Expected

ReportStep 1Steps 2–4If not
Timing Summary → WNSpositive, 0 failing endpointspositive, 0 failing endpointsclock constraint missing → the create_clock line of the XDC
Utilization → Block RAM0~34–38 tiles of 140 (the double framebuffer)~64 → DEPTH became a power of two (do not edit frame_buffer.v)
Utilization → LUT / FFa few hundredstep 4: ≈ 1,000–1,300 LUT, ≈ 550 FF, 0–2 DSP (of 53,200 / 106,400 / 220)—
Methodologyno unconstrained clocksno 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).

22

Bring-up step 1: the VGA controller, on your adapter

GUIhardware

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.

FileRole
rtl/vga_controller.vthe 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.vtest pictures from x = address[9:0], y = address[18:10]; registered output
bringup/step1_vga/vga_test_top.vClocking Wizard, reset, buttons/switches, LEDs; RGB444 straight to the adapter (all 4096 colours, every DAC bit)
bringup/step1_vga/vga_test.xdcthe 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
bringup/step1_vga/vga_pattern.vVerilogDownload
`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
bringup/step1_vga/vga_test_top.vVerilogDownload
`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]};

endmodule

Do

  1. Add Sources → design sources → rtl\vga_controller.v, bringup\step1_vga\vga_pattern.v, bringup\step1_vga\vga_test_top.v (Copy sources: unticked).
  2. Add Sources → constraints → bringup\step1_vga\vga_test.xdc.
  3. Sources: vga_test_top is shown in bold as the top, with u_clk : clk_wiz_0 and u_vga : vga_controller below it.
  4. Build and program (Step 21). Nothing else plugged in.

The tests

The checkerboard appears straight away. Then go through the buttons and switches:

ControlPictureWhat it proves
(after programming) · BTN1checkerboard, 40 × 40-pixel squares, 1-pixel red frame on the outermost pixelsHSYNC/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)
BTN28 colour bars + 16-step grey rampeach colour reaches the right DAC: white yellow cyan green magenta red blue black, left to right
BTN3DAC ramps: red, green, blue, grey, 16 steps eachevery 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 up1-pixel grid every 40 pixels + centre crosssharpness: thin, even lines; the cross exactly in the centre
SW0 upevery picture invertedeach pixel and DAC bit both ways (a stuck bit shows in one of the two)
BTN0back to the checkerboard (reset)reset path
LEDMeaning in step 1
LD1clock locked — on
LD3heartbeat ≈ 0.75 Hz
LD0, LD2picture number in binary (00 checkerboard … 11 grid)

If a picture is wrong

SymptomCauseFix
Monitor: no signalHSYNC/VSYNC not arrivingLD1 on? PMOD A the right way round (pin 1 to pin 1)? HSYNC = JA-2, VSYNC = JA-8 (Step 18)
Picture rolls or tearssync wiring on the adapterHSYNC and VSYNC swapped, or not on VGA pins 13 / 14
Bars in the wrong ordertwo colour channels swappede.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 stepsbits of one channel swapped or openbit table in Step 18; the step tells you the bit (step 8 wrong = bit 3, step 1 = bit 0)
Everything too dark / too brightDAC resistor valuesyour adapter’s resistors, not the RTL
✓
Verified in simulation

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.

23

Bring-up step 2: SPI receiver + framebuffer + RECT, over real SPI

GUIhardware

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

FileWhat it is
rtl/spi_cmd_rx.vSPI receiver with synchronizers, 80-bit framing (Step 7)
rtl/frame_buffer.v1 write + 1 read port, block RAM (Step 9)
rtl/rect_filler.vthe rectangle engine (Step 11)
bringup/step2_rect/gpu_core.vthe first core: decode, power-up clear, RECT, SWAP + double buffering, VGA
fpga/fpga_top.v, fpga/spi_test_host.vboard shell + on-board SPI master (below)
bringup/step2_rect/selftest.memthe step-2 tests (made by scripts/gen_selftest.py)
fpga/pynq_gpu.xdcconstraints 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
bringup/step2_rect/gpu_core.vVerilogDownload
`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)
    );

endmodule

fpga_top.v — the board shell

BTN1 · BTN2 · BTN3which test (1–3)SW1 up: tests 4–6debouncesample every 5.2 msspi_test_hostROM: selftest.memwait READY → CS low80 bits @ 2.08 MHz→ CS high → nextstartSW0 muxup: test hostdown: Arduinoheader pinsSPIgpu_coresame SPI receiver,same engines→ VGA → monitorgpu_ready (also on AR12 for an Arduino)AR10 · AR11 · AR13Arduino header inSPI header 2×3AR_SS · AR_SCK · AR_MOSI outloopback: 3 jumper wiresSW0 up: the GPU listens to the test host (no wires at all). SW0 down + 3 jumper wires: the same frames leave the FPGA on the SPI headerand come back in through the Arduino header pins — testing the real pins, pull-ups and XDC, still without an Arduino.
diagramInside fpga_top: two possible SPI sources for the same GPU, chosen with SW0.
  • 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 in fpga_top uses 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_ready rises 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 is F on 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
fpga/fpga_top.vVerilogDownload
`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];

endmodule

spi_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.

StateWhat it does
S_IDLEwait for start; remember the test number
S_SEEKwalk the ROM, counting all-zero end markers, until test N begins
S_WAITend marker → done; else wait for gpu_ready, then CS low with the first bit on MOSI
S_SHIFT6 clocks SCK low, 6 clocks high, per bit; MOSI changes on the falling edge, the GPU samples on the rising edge
S_GAPCS high after half a bit, then 32 clocks before looking at READY again
▸ Show fpga/spi_test_host.v · 143 lines
fpga/spi_test_host.vVerilogDownload
`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

endmodule

pynq_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:

SignalBoard labelFPGA pinDirNote
spi_cs_nAR10T16ininternal pull-up → idle high
spi_mosiAR11R17inpull-down
spi_sckAR13N17inpull-down → idle low (mode 0)
gpu_readyAR12P18out3.3 V, 8 mA
test_cs_n / test_sck / test_mosiAR_SS / AR_SCK / AR_MOSIF16 / H15 / T12outtest host (loopback)
btn[2:0] · sw[1:0]BTN3–1 · SW1–0L19 L20 D20 · M19 M20inasynchronous, synchronized + debounced
sysclk—H16in125 MHz oscillator
resetBTN0D19inactive high
vga_*PMOD A + Bunchangedoutyour video adapter
▸ Show fpga/pynq_gpu.xdc · 80 lines
fpga/pynq_gpu.xdcTclDownload
## =============================================================================
## 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

  1. 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.
  2. Add Sources → design sources → filter All Files → bringup\step2_rect\selftest.mem.
  3. Add Sources → constraints → fpga\pynq_gpu.xdc. Then right-click vga_test.xdc → Disable File (one XDC per top level).
  4. Sources: right-click fpga_top → Set as Top. Below it: u_clk, u_test : spi_test_host, u_gpu : gpu_core with u_spi, u_rect, u_fb, u_vga. The step-1 files stay in the project unused — to go back to step 1, set vga_test_top as top and swap which XDC is disabled.
  5. 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.

TestCommandsIf it looks right, these workIf not, look at
1 · HICLEAR, 10 RECT, SWAPSPI 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 · coloursCLEAR, 15 RECT, SWAPall 8 palette colours through RGB332 → RGB444, rectangles down to 2 × 2 and 1 × 1colours wrong although step 1 was right: the RGB332 expansion in fpga_top · 1 × 1 missing: the - 1 of the inclusive corner
3 · blocksCLEAR, 12 RECT, SWAPRECT 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 nothingcolour 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.

✓
Verified in simulation

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.

24

Bring-up step 3: add the line engine

GUIhardware

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

  1. Add Sources → design sources → rtl\line_renderer.v.
  2. Swap the core and the tests: in Sources, right-click bringup/step2_rect/gpu_core.v → Remove File from Project, same for the step-2 selftest.mem (the files stay on disk). Then Add Sources → bringup\step3_line\gpu_core.v and bringup\step3_line\selftest.mem.
  3. Read the change below — that is the whole difference between the two cores.
  4. Build and program (Step 21). SW0 up.

What changes in gpu_core.v

gpu_core.v: step 2 → step 3diff+52 / −23 lines
··· 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]};
 
 
ChangeWhy
OP_LINE, is_line, arguments c, dLINE uses all four arguments (x0, y0, x1, y1); RECT only needed A and B signed
line_busy in idleREADY stays low while a line is drawn, so the host waits
u_line instancestarted by accept && is_line, like the rect engine by its opcode
plot_x / plot_y multiplexerone writer, two engines; only one is ever busy, so “line if it plots, else rect” is enough
on_screen and draw_we = plot && on_screenline 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

TestCommandsIf it looks right, these workIf not, look at
1 · starburstCLEAR, 38 LINE, SWAPBresenham 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 artCLEAR, 52 LINE, SWAPmany 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 · houseCLEAR, 7 RECT, 27 LINE, SWAPboth engines in one frame through the shared writer, line clipping: sun rays and road lines start or end hundreds of pixels off screena 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.

✓
Verified in simulation

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.

25

Bring-up step 4: add the circle engine — the complete GPU

GUIhardware

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

  1. Add Sources → design sources → rtl\circle_renderer.v.
  2. Swap the core and the tests: remove bringup/step3_line/gpu_core.v and its selftest.mem from the project; add rtl\gpu_core.v and fpga\selftest.mem. These two are the final files — the same core the ASIC uses.
  3. Build and program (Step 21). SW0 up.

What changes in gpu_core.v

gpu_core.v: step 3 → step 4 (final)diff+42 / −25 lines
··· 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) &&
ChangeWhy
PW = COORD_BITS + 3cx ± r needs 15 signed bits; every coordinate in the writer gets this width
OP_CIRCLE, is_circle, circ_busy in idlesame pattern as LINE in step 3
cx_p, cy_p and u_circcentre sign-extended to 15 bits; fill = D[0], radius = the low 11 bits of C
line_xs / line_ysline coordinates sign-extended from 12 to 15 bits
3-way plot_x / plot_yline, else circle, else rect

The tests

TestCommandsIf it looks right, these workIf not, look at
1 · targetCLEAR, 22 CIRCLE, SWAPoutline and filled circles, discs with no holes and no double rows (rings of alternating colour stay clean), clipping at the bottom edgeholes or stripes in a disc: the span rules (Step 12) · rings not round: the d update
2 · snowmanCLEAR, 18 CIRCLE, 5 RECT, 4 LINE, SWAPall 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 · edgesCLEAR, 6 RECT, 1 LINE, 9 CIRCLE, SWAPevery 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 nothingcolour 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.

✓
Verified in simulation

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).

26

The test host: loopback through the real pins, and your own tests

hardwareGUI

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

ROMStepTests 1–3 (SW1 down)Tests 4–6 (SW1 up)Words
bringup/step2_rect/selftest.mem2HI · colours · blocks— (empty)49 / 256
bringup/step3_line/selftest.mem3starburst · string art · housestep 2 again179 / 256
fpga/selftest.mem4 (final)target · snowman · edgesstep 3 again207 / 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):

PYNQ-Z2 SPI header (2×3), pin numbers as in the reference manual1AR_MISOW15 · unused23V3do not connect3AR_SCKH15 · test_sck4AR_MOSIT12 · test_mosi5AR_SSF16 · test_cs_n6GNDAR10AR11AR12AR13Arduino connector J3AR_MOSI → AR11AR_SS → AR10AR_SCK → AR13Find pin 1 on the board (the corner mark next to the header). With the board on, pin 2 measures 3.3 V and pin 6 is GND.Both ends are 3.3 V FPGA pins (each with its own 200 Ω series resistor), so plain jumper wires are safe — no dividers. Leave AR12 free.
diagramThree jumper wires from the 2×3 SPI header to connector J3. Both ends are 3.3 V FPGA pins.
  1. 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.
  2. Power on, program, SW0 down (the GPU listens to the Arduino connector again).
  3. 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.

scripts/gen_selftest.py (excerpt)Python
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}),
}
  1. Edit or add a function in scripts/gen_selftest.py and put it in STEPS (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.
  2. 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/
  3. Optional but quick: see the result before building — bash run_sims.sh stage 7 keeps the frames in build/selftest/step2, step3, step4/board_N.hex; turn one into a PNG with python3 scripts/hex2png.py fpga build/selftest/step4/board_2.hex snowman.png.
  4. Vivado → Generate Bitstream. It sees the changed .mem and re-runs synthesis. Program, press the button.
▸ Show scripts/gen_selftest.py · 258 lines
scripts/gen_selftest.pyPythonDownload
#!/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()
✓
Verified in simulation

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

SymptomCauseFix
Button does nothing, LD3 keeps blinkingtest host never startedBTN0 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 drawnGPU not listening, so READY never comes backSW0 must be up (or the loopback wires in place with SW0 down)
Loopback: nothing drawn, works with SW0 upa wire on the wrong socketAR_SCK→AR13, AR_MOSI→AR11, AR_SS→AR10; check pin 1 of the SPI header
Pictures of the previous step after swappingthe old selftest.mem or gpu_core.v is still in the projectexactly 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 testVivado still has the old ROMcopied the new .mem to C:\fpga? added with “Copy sources” ticked by mistake?
27

Before the Arduino: cross-check every pin and connection by script

WSLverified

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.

SectionComparesCatches
[A] FPGAfpga_top ports ↔ XDC ↔ PYNQ-Z2 pin list (manual tables 9–19 + base overlay), incl. the manual's PMOD P/N namesunconstrained or doubly constrained bits, a pin used twice, a wrong ;# JA2-style comment
[A2] Step 1vga_test_top ports ↔ vga_test.xdc ↔ pynq_gpu.xdcthe step-1 adapter test using a different pin than the GPU build — then a working checkerboard would prove nothing
[B] Arduinosketch PIN_CS/PIN_READY ↔ the XDC sockets (AR10…AR13) ↔ the test host's SPI-header pinsCS not on AR10/Uno 10, READY on an SPI pin; prints the cable list and the loopback wires
[C] Macrogpu_asic ports ↔ pin_order.cfga macro pin left out or placed twice
[D] Chipevery 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] Layoutplace_pads rows ↔ macro pin sidesa pad missing from the floorplan, or on a different side than its macro pin (long wires across the core)
[F] Electricaldivider, READY level, VGA DACout-of-spec voltages (PYNQ-Z2 limits from its manual) and the pad current limit
[G] Test ROMsthe three selftest.mem (steps 2, 3, 4)wrong size, a test without CLEAR/SWAP, an opcode the step’s core does not have

Do

terminalBashWSL · devshell
cd ~/asic_projects/raster_gpu
python3 scripts/check_pins.py        # exit code 0 = consistent

Expected (real output)

▸ Show check_pins.py · full output · 119 lines
check_pins.py · full outputText

[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
check_pins.py · the lines to look atText
[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 CONSISTENT
✓
It really catches mistakes

Tested 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
scripts/check_pins.pyPythonDownload
#!/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)
28

Parts list for the FPGA setup

hardware

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.

#PartQtyExact specUsed for
1PYNQ-Z2 + micro-USB cable1data-capable cable (not charge-only); power jumper on USB, boot jumper on JTAGruns the GPU bitstream
2Your VGA video adapter112-bit RGB444 resistor DAC on PMOD A + PMOD B (unchanged)turns 4-bit colours into 0–0.7 V
3VGA cable + monitor1must accept 640 × 480 @ 60 Hz (almost all VGA monitors do); an HDMI-only monitor needs an active VGA→HDMI convertershows the picture
4Arduino Uno R3 (or Nano) + USB cable1ATmega328P, 16 MHz, 5 V logic · USB-B for the Uno, mini/micro/USB-C for Nano cloneshost that sends commands
5Resistor 2.2 kΩ3¼ W, 5 % carbon film · bands red red red goldseries arm of each divider
6Resistor 3.3 kΩ3¼ W, 5 % · bands orange orange red goldlower arm (to GND) of each divider
7Breadboard1half size, 400 tie points (any size works)holds the three dividers
8Jumper wires, male–male9 used10–15 cm; buy a pack of 20+. Both the Uno headers and the PYNQ-Z2 sockets are female, so male–male everywhereconnections (counted below)
9Multimeter1DC volts; a Hz range is a bonus (checks HSYNC/VSYNC)checking the dividers before connecting

The 9 jumpers, counted

#FromToSuggested colour
1Uno pin 13breadboard column 2yellow (SCK)
2breadboard column 6PYNQ AR13yellow
3Uno pin ~11breadboard column 9green (MOSI)
4breadboard column 13PYNQ AR11green
5Uno pin ~10breadboard column 16blue (CS)
6breadboard column 20PYNQ AR10blue
7Uno pin 8PYNQ AR12red/orange (READY) — direct, no breadboard
8Uno GNDbreadboard − railblack
9PYNQ GND (J3 pin 7, next to AR13)breadboard − railblack

The three 3.3 kΩ resistors plug straight from their column into the − rail, so they need no wires.

Optional, but useful

PartWhy you might want it
3.3 V board instead of the Uno: ESP32 DevKitC, Raspberry Pi Pico, Arduino Nano 33 IoTno 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 modulealternative to the dividers (not the BSS138 type — too slow above ~1 MHz)
E12 resistor kit1.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 wiresfor the loopback test in Step 26 (SPI header → AR sockets)
29

Wire the Arduino to the PYNQ-Z2

hardware
⚠
Voltage

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):

Arduino Uno R3top header next to the USB jack, 5 V logic (pin labels as printed)SCLSDAAREFGND1312~11~10~98PYNQ-Z2Arduino connector J3, 3.3 V logic (shield removed)SCLSDAAGNDAR13AR12AR11AR10AR9AR8GNDGNDSCK outspi_sck · N17MISO · leave freegpu_ready · P18MOSI outspi_mosi · R17CS outspi_cs_n · T16READY individerdividerdividerREADY, directGNDSame R3 layout on both boards, but different printing: the Uno says 13 / ~11 / ~10 (Arduino code: D13, D11, D10), the PYNQ-Z2 says AR13 / AR11 / AR10.Uno pin 12 is the SPI MISO pin — keep it free, which is why READY (PYNQ AR12) goes to Uno pin 8. Match by label, not position: the boards are rotated.
diagramSame R3 positions, different printing: Uno 13 / ~11 / ~10 ↔ PYNQ AR13 / AR11 / AR10. READY goes from AR12 to Uno pin 8, keeping the Uno MISO pin (12) free.

Schematic

Arduino Uno (5 V)PYNQ-Z2 Arduino header3.3 V I/O only · shield removed13 / SCKAR13 · N17 · spi_sck2.2 kΩ3.3 kΩ → GND5 V → 3.0 V~11 / MOSIAR11 · R17 · spi_mosi2.2 kΩ3.3 kΩ → GND5 V → 3.0 V~10 / CSAR10 · T16 · spi_cs_n2.2 kΩ3.3 kΩ → GND5 V → 3.0 V8 READYAR12 · P18 · gpu_ready3.3 V straight in — the Uno reads it as HIGHGNDGND
diagramThree dividers (2.2 kΩ series, 3.3 kΩ to GND) bring 5 V down to 3.0 V. READY (3.3 V) goes straight into the Uno, which reads it as HIGH.

On the breadboard

− rail = GND (every hole on this line is connected)123456789101112131415161718192021abcde2.2 kΩ3.3 kΩ3.0 VUno pin 13SCK 5 VPYNQ AR13N17 · SCK 3.0 V2.2 kΩ3.3 kΩ3.0 VUno pin ~11MOSI 5 VPYNQ AR11R17 · MOSI 3.0 V2.2 kΩ3.3 kΩ3.0 VUno pin ~10CS_N 5 VPYNQ AR10T16 · CS_N 3.0 VUno GNDPYNQ GNDUno pin 8PYNQ AR12READY: one direct jumper, not through the breadboard (3.3 V into the 5 V Uno is safe)Each numbered column of 5 holes (a–e) is one node. The Arduino wire goes into column 2/9/16, the PYNQ wire leaves from column 6/13/20,and the 3.3 kΩ joins that same column to the GND rail. Bands: 2.2 kΩ = red-red-red-gold · 3.3 kΩ = orange-orange-red-gold.
diagramA half-size breadboard, top view. One divider per signal: Arduino wire in, 2.2 kΩ across, 3.3 kΩ to the GND rail, PYNQ wire out from the same column as the 3.3 kΩ.

Why these values work — the numbers

QuantityValueRequirementOK?
Divider output, Arduino HIGH5 V × 3.3 / (2.2 + 3.3) = 3.00 VVIH ≥ 2.0 V; PYNQ-Z2 header ≤ 3.4 V recommended✔
Board series resistor200 Ω between socket and FPGA pin (reference manual)input current is tiny, so no voltage drop✔
Divider output, Arduino LOW0 VVIL ≤ 0.8 V✔
Current per divider (HIGH)5 V / 5.5 kΩ = 0.9 mAUno pin ≤ 20 mA✔
Edge speedsource 2.2 k ∥ 3.3 k = 1.32 kΩ; with ~10 pF pin + wire: 10–90 % ≈ 29 nsSCK half period at 2 MHz = 250 ns✔ 8× margin
READY HIGH at the Uno≈ 3.3 VATmega328P VIH ≥ 0.6 × 5 V = 3.0 V◐ 0.3 V margin — fine with short wires
READY LOW at the Uno≈ 0 VVIL ≤ 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)ThroughTo (PYNQ-Z2 socket, as printed)FPGA pinSignal
113col 2 → 2.2 kΩ → col 6 (3.3 kΩ to GND)AR13N17SCK
2~11col 9 → 2.2 kΩ → col 13 (3.3 kΩ to GND)AR11R17MOSI
3~10col 16 → 2.2 kΩ → col 20 (3.3 kΩ to GND)AR10T16CS_N
48direct wireAR12P18READY (PYNQ → Arduino)
5GNDbreadboard − railGND (J3 pin 7, next to AR13)—common ground

Do — in this order

  1. Unplug the joystick shield from the PYNQ-Z2. Both boards unpowered.
  2. 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.
  3. Connect the − rail to Arduino GND (jumper 8).
  4. 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.
  5. Connect Uno pins 13, ~11, ~10 to columns 2, 9, 16 (jumpers 1, 3, 5).
  6. 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).
  7. SW0 down on the PYNQ-Z2 (the GPU listens to the Arduino connector; SW0 up = on-board test host).
  8. 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_rx only executes frames of exactly 80 bits. Then setup() 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)ExpectedIf 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 on0 V → bitstream not loaded, BTN0 held, or READY wire on the wrong socket
Continuity Arduino GND ↔ PYNQ GNDbeepno common ground → garbage or nothing
i
Why dividers and not a BSS138 module?

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.

★
ESP32 / Pico instead (3.3 V, no dividers)

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).

30

The Arduino sketch

WindowsGUIhardware

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).

arduino/gpu_demo/gpu_demo.inoArduino C++Download
// =============================================================
// 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

  1. Copy the sketch folder to Windows: cp -r ~/asic_projects/raster_gpu/arduino/gpu_demo /mnt/c/fpga/
  2. Arduino IDE → File›Open → C:\fpga\gpu_demo\gpu_demo.ino.
  3. Check line 23: #define TARGET_FPGA 1 (0 for the ASIC).
  4. Tools›Board›Arduino AVR Boards›Arduino Uno, Tools›Port → your COM port.
  5. Upload (Ctrl+U). Then Tools›Serial Monitor at 115200 baud.

Expected

Serial Monitor · 115200 baudText
=== 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 = 0

How the sketch is organised

SectionWhat it does
pins / protocol / coloursone 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 / Swapone-line wrappers, the "GL" API you draw with; a circle is one 10-byte command whatever its size
beginFrame/endFrameFPGA: SWAP after drawing (double buffer) · ASIC: wait for vblank before drawing
demosidentical 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.

i
Double buffering

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.

31

FPGA bring-up checklist

hardware

Bring-up order (test one thing at a time)

  1. 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.
  2. Sync check (optional, multimeter in Hz mode or scope): PMOD A pin 2 ≈ 31.25 kHz (HSYNC), pin 8 ≈ 59.5 Hz (VSYNC).
  3. Step 2 — SPI + framebuffer + RECT (Step 23): fpga_top + the step-2 core, SW0 up. “HI” appears by itself; BTN2 / BTN3 → colours, blocks.
  4. Step 3 — + LINE (Step 24): starburst, string art, house; SW1 up → the step-2 pictures again.
  5. Step 4 — + CIRCLE (Step 25): target, snowman, edges; SW1 up → the step-3 pictures again. The complete GPU works on the real FPGA.
  6. Loopback (optional): three wires SPI header → AR10/11/13, SW0 down, same pictures → the input pins and XDC are right. Remove the wires.
  7. READY: PYNQ AR12 measures ≈ 3.3 V.
  8. 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.
  9. 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

SymptomLikely causeFix
Monitor: "no signal"bitstream not loaded / LD1 offcheck LD1, re-program, check PMOD orientation
Picture rolls or is shiftedadapter or cablesame 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 heldAR12 must read 3.3 V; check GND; LD0 must be on
READY ok, nothing drawn, LD2 never togglesSW0 up, SPI wires swapped or divider wrongSW0 down; Uno 13→AR13, ~11→AR11, ~10→AR10; ≈3.0 V high at the AR sockets
On-board tests fine, Arduino draws nothingthe problem is outside the FPGAwiring, dividers, GND or the sketch — the GPU itself is proven
Garbage shapes / wrong coloursSPI edges too slow / long wiresset SPI_HZ to 1000000, keep wires < 15 cm
READY timeouts > 0a command was sent while busyonly if you removed gpuWaitReady()
Cube flickersTARGET_FPGA 0 on the FPGAset it to 1
04

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.

32

What changes, and why

read
TopicFPGAASICWhy
FramebufferBRAM 320×240×8 ×2flip-flops 40×30×3no SRAM yet; ≈30 µm² + mux per bit
Initial contentscould use initialcleared by logic after resetsilicon has no init values
ClockMMCM 25.000 MHz25.175 MHz oscillatorno PLL; VGA needs the pixel rate
Resetlocked & ~BTN0pad rst_n from a supervisorsame reset synchronizer inside
SPI2-FF sync2-FF sync + SDC false pathsSTA must not time async pins (CDC step)
Colour out12 pins RGB4443 pins RGB111each pin is an 80 µm GPIO pad
i
Can the clock be lower?

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.

asic/src/gpu_asic.vVerilogDownload
`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 */
    );

endmodule

The `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.

33

Pin plan: 11 GPIOs for a GPU chip

read
#Macro pinPadDirFunctionSide
0clku_clkin25.175 MHz oscillatorS
1rst_nu_rst_ninreset (low = reset)S
2spi_cs_nu_cs_ninSPI chip selectW
3spi_scku_sckinSPI clockW
4spi_mosiu_mosiinSPI dataW
5gpu_readyu_readyoutflow control to the MCUE
6vga_hsu_hsoutHSYNCE
7vga_vsu_vsoutVSYNCE
8–10vga_rgb[2:0]u_r u_g u_boutR, G, B (resistor to the VGA pins)N
——u_power_goodinPOR from a board supervisor → ENABLE_H of all padsS

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":

gpu_chip (SKY130)pad_clkpad_rst_npad_power_goodpad_cs_npad_sckpad_mosipad_readypad_rgb[2] Rpad_rgb[1] Gpad_rgb[0] Bpad_hspad_vs25.175 MHz oscreset supervisorRESET# → rst_n + power_goodESP32 / Pico (3.3 V)CS → cs_nSCK → sckMOSI → mosiGPIO ← ready74LVC244Abuffer · 3.3 V±24 mA outputsVGA DE-15pin 1REDpin 2GREENpin 3BLUEpin 13HSYNCpin 14VSYNCpin 5–8,10GND270 Ω270 Ω270 Ω47 Ω47 ΩA SKY130 GPIO pad is rated 4 mA. 3.3 V into 270 Ω + 75 Ω is 9.6 mA, so the pads drive a 74LVC244A and the buffer drives the monitor.Full scale per colour: 3.3 V × 75 / (270 + 75) ≈ 0.72 V (VGA = 0.7 V). Supplies: VCCD 1.8 V, VDDIO 3.3 V, VDDA 3.3 V (power-tree diagram below).
diagramBoard-level hookup of the ASIC: oscillator, reset supervisor, any 3.3 V MCU, a 74LVC244A buffer and a 3-resistor VGA DAC (one bit per colour). Parts and power: Step 34.

All 18 bond pads

Side (die)OrderPad instanceCellNet / function
South L→R1u_vccdvccd_lvc_clamped_padVCCD 1.8 V core supply
South2u_clkgpiov2_pad_wrapped (in)clock
South3u_rst_ngpiov2 (in)reset, active low
South4u_power_goodgpiov2 (in)POR → ENABLE_H
South5u_vssdvssd_lvc_clamped_padcore ground
West B→T1u_vddiovddio_hvc_clamped_padVDDIO 3.3 V pad supply
West2u_cs_ngpiov2 (in)SPI CS
West3u_sckgpiov2 (in)SPI SCK
West4u_mosigpiov2 (in)SPI MOSI
West5u_vssiovssio_hvc_clamped_padpad ground
East B→T1u_vddavdda_hvc_clamped_padVDDA 3.3 V
East2u_readygpiov2 (out)READY
East3u_hsgpiov2 (out)HSYNC
East4u_vsgpiov2 (out)VSYNC
East5u_vssavssa_hvc_clamped_padanalog ground
North L→R1u_rgpiov2 (out)RED
North2u_ggpiov2 (out)GREEN
North3u_bgpiov2 (out)BLUE

The macro's own pins sit on the side that faces their pads, so the top-level wires stay short:

asic/pin_order.cfgTextDownload
#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\]
34

A board for the chip: parts, power and every connection

read
i
Hypothetical

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:

USB 5 Vor 5 V barrel3.3 V LDOe.g. AMS1117-3.33V3 railVDDIO padu_vddio · pad ringVDDA padu_vdda25.175 MHz osc3.3 V CMOS out → pad_clksupervisorpush-pull, active-low→ pad_rst_n + pad_power_goodVGA buffer74LVC244A VCChost MCU (3.3 V)ESP32 / Pico1.8 V LDOe.g. AP2112K-1.8VCCD padu_vccd · coreGrounds: u_vssd, u_vssio, u_vssa all go to one board ground plane. Decoupling: 100 nF next to every supply pad + 10 µF per rail.The 1.8 V LDO is fed from 3V3, so when the 3.3 V supervisor releases (≈140 ms after 3V3 is good) 1.8 V is long since up.
diagramBoard power tree. All three ground pads go to one ground plane.

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

RefPart (example)QtySpecConnects to
U1gpu_chip (this design, packaged)1SKY130, 18 bond pads—
U23.3 V LDO, e.g. AMS1117-3.3 (SOT-223)15 V in, ≥ 300 mA; 10 µF in, 22 µF out (per datasheet)VDDIO, VDDA, oscillator, supervisor, buffer, host
U31.8 V LDO, e.g. AP2112K-1.8 (SOT-23-5)1fed from 3V3, EN tied to VIN; 1 µF in/outVCCD
X125.175 MHz oscillator, 3.3 V CMOS output1any 3.3 V CMOS oscillator at this frequency (a programmable MEMS oscillator can be ordered at 25.175 MHz)pad_clk
U4reset supervisor, e.g. MAX811-type13.3 V rail, ≈ 3.08 V threshold option, active-low push-pull RESET#, ≥ 140 ms timeout, manual-reset inputpad_rst_n and pad_power_good
SW1push-button1to the supervisor MR# inputmanual reset
U574LVC244A octal buffer1VCC = 3.3 V, both OE# to GND, 2 spare inputs to GNDpads → VGA
R1–R3270 Ω, 1 %3R, G, B DAC (into the monitor's 75 Ω)buffer → DE-15 pins 1, 2, 3
R4, R547 Ω2series, HSYNC / VSYNCbuffer → DE-15 pins 13, 14
C100 nF X7R (0603)8one at each supply pad (VCCD, VDDIO, VDDA), U2, U3, X1, U4, U5decoupling
C10 µF2bulk on the 3V3 and 1V8 railsdecoupling
J1DE-15 female (HD15, 3 rows)1VGAmonitor
J21×5 pin header1CS, SCK, MOSI, READY, GND — 3.3 V host only (a 5 V Uno needs the dividers from Step 29)host MCU
J3USB-C / micro-USB receptacle15 V inU2

Every connection on the board

gpu_chip (SKY130)pad_clkpad_rst_npad_power_goodpad_cs_npad_sckpad_mosipad_readypad_rgb[2] Rpad_rgb[1] Gpad_rgb[0] Bpad_hspad_vs25.175 MHz oscreset supervisorRESET# → rst_n + power_goodESP32 / Pico (3.3 V)CS → cs_nSCK → sckMOSI → mosiGPIO ← ready74LVC244Abuffer · 3.3 V±24 mA outputsVGA DE-15pin 1REDpin 2GREENpin 3BLUEpin 13HSYNCpin 14VSYNCpin 5–8,10GND270 Ω270 Ω270 Ω47 Ω47 ΩA SKY130 GPIO pad is rated 4 mA. 3.3 V into 270 Ω + 75 Ω is 9.6 mA, so the pads drive a 74LVC244A and the buffer drives the monitor.Full scale per colour: 3.3 V × 75 / (270 + 75) ≈ 0.72 V (VGA = 0.7 V). Supplies: VCCD 1.8 V, VDDIO 3.3 V, VDDA 3.3 V (power-tree diagram below).
diagramSignal hookup: oscillator and supervisor on the left, host on its 5-pin header, buffer + 3-resistor DAC to the VGA connector.
Chip pad (net)Pad cellDirBoard netGoes to
pad_clku_clkinCLK25X1 output
pad_rst_nu_rst_ninRESET_NU4 RESET# (low = reset)
pad_power_goodu_power_goodinRESET_Nsame net: HIGH once 3V3 (and so 1V8) is up → enables all pad drivers
pad_cs_nu_cs_ninSPI_CS_NJ2-1 (host CS)
pad_scku_sckinSPI_SCKJ2-2 (host SCK, ≤ 3 MHz)
pad_mosiu_mosiinSPI_MOSIJ2-3 (host MOSI)
pad_readyu_readyoutGPU_READYJ2-4 (host GPIO input)
pad_rgb[2]u_routR_TTLU5 → 270 Ω → J1 pin 1
pad_rgb[1]u_goutG_TTLU5 → 270 Ω → J1 pin 2
pad_rgb[0]u_boutB_TTLU5 → 270 Ω → J1 pin 3
pad_hsu_hsoutHSYNCU5 → 47 Ω → J1 pin 13
pad_vsu_vsoutVSYNCU5 → 47 Ω → J1 pin 14
VCCD / VSSDu_vccd / u_vssdpwr1V8 / GNDU3 out / plane
VDDIO / VSSIOu_vddio / u_vssiopwr3V3 / GNDU2 out / plane
VDDA / VSSAu_vdda / u_vssapwr3V3 / GNDU2 out / plane
———GNDJ1 pins 5, 6, 7, 8, 10 · J2-5
★
Same sketch

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.

35

Pins-only testbench (works on the netlist too)

WSLverified

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
sim/tb_pins.vVerilogDownload
`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
endmodule
terminalBashWSL · devshell
cd ~/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.hex
✓
Verified

The 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.

05

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.

36

config.json, line by line

read
asic/config.jsonJSONDownload
{
    "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
}
KeyValueWhy
CLOCK_PERIOD39.7225.175 MHz pixel clock
DIE_AREA / CORE_AREA720×720, 15 µm margin0.168 mm² of cells → ~35 % of a 690×690 core; the read mux needs routing room
PL_TARGET_DENSITY_PCT45spread the cells instead of packing them
IO_PIN_ORDER_CFGpin_order.cfgpins face their pads (old name FP_PIN_ORDER_CFG)
PDN_MULTILAYERfalsemacro mode: power straps on met4 only, so chip-level met5 straps can cross the macro
PDN_CORE_RINGfalseLibreLane refuses a core ring when PDN_MULTILAYER is false; the chip owns the ring
RT_MAX_LAYERmet4keep signal routing off met5 (chip PDN layer)
PDN_VWIDTH / PITCH / OFFSET3.1 / 60 / 20denser met4 straps = more VPWR/VGND pin area for the chip to land on
met5chip: horizontal straps 1.6 µm / 48 µm pitch + ringvia4met4–met5 vias: chip grid ↔ macro VPWR/VGNDmet4macro: vertical VPWR/VGND straps (its LEF pins) · chip: vertical straps outside the macromet1–3macro-internal rails and signal routing (RT_MAX_LAYER = met4)cellsstandard cells (sky130_fd_sc_hd) inside the macro
diagramWho owns which metal layer once the macro sits inside the chip.
!
Different from your counter8 macro

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

asic/gpu.sdcTclDownload
# =============================================================
# 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*}]
37

Run the flow

WSLdevshell
Lint + synthVerilator.LintYosys.SynthesisSTAPrePNRFloorplanFloorplanTapEndcapGeneratePDNIOPlacementPlace + clockGlobalPlacementDetailedPlacementCTSResizerTimingRouteGlobalRoutingRepairAntennasDetailedRoutingFillInsertionSignoffRCX + STAPostPNRMagic/KLayout DRCNetgen.LVSfinal/ viewsStep names are the real LibreLane 3.0.17 Classic step IDs (shortened). Use them with --to / --from to stop or resume a run.
diagramThe Classic flow your run goes through.

Do

  1. Start the LibreLane devshell (your AppImage).
  2. Run:
terminalBashWSL · devshell
cd ~/asic_projects/raster_gpu/asic
librelane config.json --run-tag gpu_v1
  1. The terminal prints each step (Verilator.Lint, Yosys.Synthesis, … Netgen.LVS). Expect roughly 10–30 minutes on your i7-1185G7.
  2. At the end a summary lists DRC, LVS, antenna, setup/hold. Anything red is a real problem: read runs/gpu_v1/warning.log and error.log.
★
Checkpoint runs

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.

38

Inspect every stage in the GUI

WSLGUI
terminalBashasic/ · devshell
librelane --last-run --flow OpenInOpenROAD config.json
librelane --last-run --flow OpenInKLayout  config.json

OpenROAD 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.
StageWhereGoodIf not
Synthesisruns/gpu_v1/*-yosys-synthesis/~12k cells, 0 latches, top = gpu_asictestbenches in VERILOG_FILES?
PinsGUI: zoom to the edgesclk/rst_n S, SPI W, ready/hs/vs E, rgb Npin_order.cfg regex must match
PDNDisplay Control → only met4; Nets VPWR/VGNDvertical met4 straps every 60 µm, no met5PDN_MULTILAYER false?
PlacementHeat Maps → Placement Densityeven, no red spotbigger DIE_AREA or lower density
CTSWindows → Clock Tree Viewer~4,000 sinks, small skewnormal: framebuffer flops dominate
RoutingHeat Maps → Routing Congestionno redmore area, new tag
GDSKLayout: Display → Full Hierarchycells + met1–met4 only—
DRC / LVS / antennaflow summary + step folders0 / clean / 0open the step log and marker DB
★
A picture without a GUI

The KLayout.Render step writes a PNG to runs/gpu_v1/final/render/; open it with explorer.exe runs/gpu_v1/final/render.

39

CDC and timing review

GUI

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:

CrossingHandled byHow to check
spi_cs_n, spi_sck, spi_mosi → clksynchronizer shift register each; logic uses only stage [1] / [2]false path from the ports; [0]→[1] still timed
rst_n → clkasync assert, 2-flop synchronous release (reset_s)false path from the port; reset_s[1] → logic timed
80-bit command wordnever crosses: built inside the clk domainnothing to check
SCK edge vs MOSIsame 2-stage latency; MOSI stable ≥ 6 clocks around the edge at 2 MHzhost rule SCK ≤ clk/8

In the OpenROAD GUI → Tcl console

OpenROAD Tcl consoleTcl
# 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_skew

Expected

  • Setup slack large and positive (period 39.7 ns).
  • Hold slack ≥ 0 at every corner — LibreLane repairs hold; check each corner in the *-openroad-stapostpnr folder.
  • 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.
40

Gate-level simulation of LibreLane's netlist

WSLdevshell

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:

terminalBashWSL · devshell
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"
i
Slow on purpose

~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.

41

Collect the macro for the chip

WSL
terminalBashWSL · devshell
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 -20

Expected

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.

06

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.

42

chip_top.v — 11 GPIOs, power-good, supplies, macro

readverified

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.

u_power_goodGPIO used as inputfrom board supervisoru_cfg_tiesky130_fd_sc_hd__conb_1each of the 11 signal GPIOsENABLE_H← por_h: IN_H of power-good (3.3 V domain)ENABLE_VDDIO← por_lv: IN of power-good (1.8 V domain)DM, OE_N, INP_DIS← cfg_hi / cfg_lo: input or push-pull outputHLD_H_N, SLOW, …← cfg_hi / cfg_lo: normal speed, no holdENABLE_INP_H, …← tie_lo[i]: the pad's own TIE_LO_ESDpor_hpor_lvcfg_hi / cfg_loBoard rule: keep pad_power_good LOW until VCCD (1.8 V) and VDDIO (3.3 V) are stable.While it is low every output pad stays Hi-Z — checked in tb_chip.v.
diagramHow the pad control pins are driven (unchanged from counter8_fullchip).
chip/rtl/chip_top.vVerilogDownload
`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 wire

Check 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:

terminalBashWSL · devshell
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
sim/tb_chip.vVerilogDownload
`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
sim/pad_models_sim.vVerilogDownload
`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)
43

Expand the Verilog macros for OpenROAD

WSL

OpenROAD reads a plain structural netlist, not `define macros. Icarus expands them — this is how your chip_top_expanded.v was made:

terminalBashWSL · devshell
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 12
44

01_floorplan.tcl — die, macro, taps, padframe

WSLGUI
VCCDCLKRST_NPGOODVSSDVDDIOCS_NSCKMOSIVSSIOVDDAREADYHSVSVSSARGBu_core : gpu_asic720 × 720 µm at (440, 440)met5 straps cross it → met4/met5 viasclk rst_ncs sck mosiready hs vsR G Bu_cfg_tie (conb)core ring (met4 / met5)met5 straps, 48 µm pitchcore area 350 … 1250supply padinput GPIOoutput GPIOcorner cellDie 1600 × 1600 µm (as counter8_fullchip)N/S pads listed left → rightE/W pads listed bottom → topeach pad faces the macro pin it feeds
diagramTarget floorplan, to scale. Pads use place_pads -mode uniform per side, in the listed order.

What the script does

  1. Reads tech LEF, cell LEF, both I/O LEFs, gpu_asic.lef, liberty; reads the expanded netlist and links chip_top.
  2. Creates the 1600×1600 µm die and the 350…1250 core.
  3. Places u_core at (440, 440) — centred — as FIRM.
  4. New: tapcell … -halo_width_x 10 -halo_width_y 10 adds well taps / end caps and cuts the standard-cell rows around the macro. In counter8 the rows ran under the macro; every Obstructed - CORE_GRID - met1 -> met4 entry in your 02_failed_vias.rpt sits at x ≈ 849–898 µm, inside the counter's 700–900 µm footprint.
  5. Builds the I/O rows and corners, places the 18 pads, fills the gaps with bus slices, abuts the rings, creates the bond terminals.
  6. Places the conb tie cell south of the macro and legalizes it.
chip/tcl/01_floorplan.tclTclDownload
# =========================================================
# 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."
terminalBashWSL · devshell
cd ~/asic_projects/raster_gpu/chip
openroad -gui tcl/01_floorplan.tcl

Check in the GUI

  1. Console ends with Floorplan and padframe placement completed.; check_placement reports no errors.
  2. F: four corners, 18 pads, macro in the middle — like the diagram.
  3. Click u_clk: Inspector shows master sky130_ef_io__gpiov2_pad_wrapped on the south edge; its bond opening faces outwards.
  4. Display Control → Rows: rows stop 10 µm before the macro.
  5. Want exact pad positions? Use the commented place_pad -row … -location … block, rerun, and confirm each bbox in the Inspector.
45

02_power.tcl — supply nets, ring, straps, macro hookup

WSLGUI

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).

chip/tcl/02_power.tclTclDownload
# =========================================================
# 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."
terminalBashchip/ · devshell
openroad -gui tcl/02_power.tcl

Check in the GUI

  1. Console: Core power network generated. reports/02_failed_vias.rpt should be (nearly) empty; nothing inside the macro outline.
  2. 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.
  3. Repeat for VSSD.
  4. Optional: check_power_grid -net VCCD. A "no terminals" complaint is expected (the external pin is pad_vccd, joined inside the pad); help check_power_grid shows whether your build has -dont_require_terminals.
46

03_route.tcl — route the signals

WSLGUI

Remaining signal nets: 11 pad ↔ macro, the power-good fan-out and the conb tie fan-out to every pad control pin.

chip/tcl/03_route.tclTclDownload
# =========================================================
# 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."
terminalBashchip/ · devshell
openroad -gui tcl/03_route.tcl

Check

  1. reports/03_route_drc.rpt must be empty (as for counter8).
  2. reports/03_antenna.rpt: long nets like cfg_lo may violate; if so add repair_antennas after global_route and rerun.
  3. GUI: show only met2/met3 and follow clk from u_clk to the macro's south edge.
47

04_streamout.tcl — merge into chip_top.gds

WSLGUI

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.

chip/tcl/04_streamout.tclTclDownload
# =========================================================
# 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 -noprompt
terminalBashchip/ · devshell
magic -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.gds
i
The "errors" in the streamout log

Your 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.

48

DRC — KLayout batch, then the Marker Browser

WSLGUI
terminalBashchip/ · devshell · BEOL = metals/vias, FEOL = devices
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
  1. Open the GDS in KLayout (previous step).
  2. Tools›Marker Browser → File›Open → reports/drc_beol.lyrdb.
  3. Left: rule names with counts. Click a marker to zoom to it.
  4. 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.
  5. The macro alone was already DRC-checked (Magic + KLayout) inside LibreLane.
i
Arguments checked

The -b -zz -r … -rd input= -rd topcell= -rd report= form is how LibreLane 3.0.17 itself calls KLayout DRC.

49

LVS of the top level

WSL

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.

chip/tcl/06_extract.tclTclDownload
# =========================================================
# 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
chip/tcl/06_lvs.tclTclDownload
# =========================================================
# 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"
terminalBashchip/ · devshell
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.log
!
Likely first mismatch: VDDIO_Q / VSSIO_Q

IO_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.

50

Signoff checklist

read
ItemStatus 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
07

Next step: a bigger framebuffer with SRAM

After v1 works. Swap one file (frame_buffer.v); gpu_core and everything else stay the same.

51

Choose the macro and the banking

read

Your PDK ships OpenRAM macros in libs.ref/sky130_sram_macros:

terminalBashWSL
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 -40

The 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
Size479.78 × 397.5 µm
Power pinsvccd1 / vssd1 on met3 + met4
Portsclk0 csb0 web0 wmask0[3:0] addr0[7:0] din0 dout0 · clk1 csb1 addr1[7:0] dout1
Timing modelinputs latched on the rising edge, data out after the falling edge → 1-clock latency
pixel address a (0 … 4799, 13 bits)a[12:10]bank 0..4a[9:2]word 0..255a[1:0]byte lanebank 0sky130_sram_1kbyte_1rw1r_32x256_8479.78 × 397.5 µmbank 1sky130_sram_1kbyte_1rw1r_32x256_8479.78 × 397.5 µmbank 2sky130_sram_1kbyte_1rw1r_32x256_8479.78 × 397.5 µmbank 3sky130_sram_1kbyte_1rw1r_32x256_8479.78 × 397.5 µmbank 4sky130_sram_1kbyte_1rw1r_32x256_8479.78 × 397.5 µmPort 0 (RW): csb0 = !(write_en && bank == i) · wmask0 = 0001 << lane · din0 = {4{pixel}}Port 1 (R): always on · addr1 = a[9:2] · bank + lane registered 1 clock · byte mux picks the pixel
diagramAddress split and the five banks.
52

frame_buffer.v, SRAM version (drop-in)

WSLverified

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.

asic_sram/src/frame_buffer.vVerilogDownload
`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
asic_sram/src/gpu_asic.vVerilogDownload
`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 */
    );

endmodule

Simulate with the real PDK model

terminalBashWSL · devshell
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"
✓
Verified with the real OpenRAM model

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.

The same cube frame: ASIC v1 (40×30×3) · ASIC v2 with SRAM (80×60×8) · FPGA (320×240×8).
The same cube frame: ASIC v1 (40×30×3) · ASIC v2 with SRAM (80×60×8) · FPGA (320×240×8).
53

Harden the SRAM version with LibreLane

WSLdevshell

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:

  1. Synthesis only: cd asic_sram && librelane config.json --run-tag syn --to Yosys.Synthesis
  2. Find the names: grep -o "[^ ]*u_sram[^ ]*" runs/syn/*-yosys-synthesis/gpu_asic.nl.v | sort -u
  3. Put the five names into instances and one regex matching all five into PDN_MACRO_CONNECTIONS (format regex VDD_NET GND_NET macro_vdd_pin macro_gnd_pin), then run the full flow with a new tag.
asic_sram/config.jsonJSONDownload
{
    "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"
    ]
}
!
This block is built differently from v1

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).

A

Appendix

54

Troubleshooting by stage

read
StageSymptomFix
Icarussyntax error at beforeSystemVerilog keyword under -g2012 — rename it
Icarustestbench hangsREADY watchdog ends it after 3 M clocks; READY stuck = reset/init problem
Vivadoclk_wiz_0 not foundIP name exactly clk_wiz_0, then Generate Output Products
Vivado~64 BRAM instead of ~38DEPTH became a power of two — keep frame_buffer.v as is
Vivadoboard shows the previous bring-up steptwo gpu_core.v or two selftest.mem in Sources — remove the old step’s files
LibreLaneIO placement "unmatched"a pin_order.cfg regex matches no port (escape brackets: vga_rgb\[2\])
LibreLanecongestion / slow detailed routingbigger DIE_AREA, lower PL_TARGET_DENSITY_PCT, new tag
LibreLanehold violations at the ff cornernormally auto-repaired; rerun from scratch after any SDC change
OpenROAD 01Missing instance: …stale chip_top_expanded.v → expand step
OpenROAD 01tapcell rejects -halo optionsolder build: cut_rows -halo_width_x 10 -halo_width_y 10 + plain tapcell
OpenROAD 02failed vias inside the macromacro LEF has met5 power → harden with PDN_MULTILAYER false
OpenROAD 03unrouted pad netspad orientation — keep R180 rotations from counter8
Magic 04GPU missing in the GDSmacros/gpu_asic.gds not copied → collect step
KLayout DRCthousands of markers in I/O cellsknown I/O-library artefacts — review your own wiring
Netgenpin mismatch on padscompare pin lists; VDDIO_Q/VSSIO_Q → LVS step
55

Command cheat sheet

WSL
cheat sheetBashall commands in order
# ---------- 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.tcl
56

Glossary

read
TermMeaning here
CDCclock domain crossing — a signal moving between unrelated clocks (here: SPI and reset pins → 25 MHz)
STA / SDCstatic timing analysis / the constraints file it reads (gpu.sdc)
LEF / DEF / GDSabstract cell view (size, pins, blockages) / placed + routed design / final mask geometry
PDNpower distribution network: rings, straps, rails, vias
CTSclock tree synthesis
DRC / LVSdesign-rule check / layout-versus-schematic connectivity check
POR / power-goodsignal that says the supplies are stable; enables the pad drivers
Hard macroa pre-placed-and-routed block (gpu_asic) used as one cell by the chip
RGB332 / RGB1118-bit colour 3-3-2 / 3-bit colour 1-1-1
vblankthe 45 non-visible lines between frames
Bresenhamline algorithm with an integer error term: adds and compares only, one pixel per step
Midpoint circlecircle algorithm: walks one octant, decides each step by the sign of f at the midpoint between two candidate pixels
Octantone eighth of the circle (45°); the other seven are mirror images
Spana horizontal run of pixels on one row (how filled circles are drawn)
AR0 … AR13the PYNQ-Z2 names of its Arduino-connector sockets (an Uno prints 0 … 13)
Loopbackfeeding a circuit's own output back into its input to test the path without the real partner
Clippingdropping (or not walking) the part of a shape that is outside the screen
57

All remaining files

read
▸ Show scripts/check_circle.py · 75 lines
scripts/check_circle.pyPythonDownload
#!/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
scripts/check_vga_test.pyPythonDownload
#!/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
sim/tb_vga_test.vVerilogDownload
`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
sim/tb_selftest.vVerilogDownload
`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
scripts/hex2png.pyPythonDownload
#!/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
sim/sram_model_sim.vVerilogDownload
`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
↑