Ports 35h-37h scroll the graphics layer (wrapping at 320 x 240); bit 1 of 36h hides a border (4 columns, 2 rows) where a program draws the strip coming into view unseen. The video loads its own column/row counters from the scroll registers each line and frame. CLS resets both. Testbench checks scroll, wrap and border. games/raid: an original Zaxxon-style game in C - fly over a fortress that scrolls diagonally, climb over low walls and through doorways in tall ones, shoot turrets, fuel tanks, radar and fighters, destroy the reactor. The world is drawn pixel by pixel from a formula, two columns and a row a frame (about 40% of the Z-80). test-raid.py flies the level with an autopilot and checks the frame budget; tools/boardemu.py is now shared by both games' tests. send-hex.py sets the date before saving. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
577 lines
28 KiB
Markdown
577 lines
28 KiB
Markdown
# Basys 3 VT220 Terminal
|
||
|
||
Turns a Digilent Basys 3 (Artix-7 XC7A35T) into a stand-alone VT220-compatible
|
||
serial terminal with ANSI colour:
|
||
|
||
- **Screen**: VGA port, 1280x1024 @ 60 Hz. 80 columns x 32 rows in a 16x32
|
||
font (the 8x16 CP437 font doubled), or 132 columns x 64 rows in the 8x16 font
|
||
after `ESC[?3h` (DECCOLM). 16 colours, underline, blink, reverse video,
|
||
optional smooth scrolling.
|
||
- **Keyboard**: a USB keyboard in the **USB HID host** port (J2). The board's
|
||
PIC24 presents it to the FPGA as a PS/2 keyboard.
|
||
- **Serial line**: the micro-USB **PROG/UART** port (the FTDI chip), 8N1. Bytes
|
||
received there are drawn on the screen. Keystrokes are sent out there.
|
||
|
||
It also contains a **Z-80 computer running Dartmouth-style BASIC with 320×240
|
||
colour graphics**. Flip SW15 up and the terminal becomes its console (see
|
||
[Z-80 BASIC](#z-80-basic) and the full manual,
|
||
[docs/basic-manual.pdf](docs/basic-manual.pdf)).
|
||
|
||
Plug the micro-USB into a PC and open the serial port (`/dev/ttyUSB1` is usually
|
||
the UART; `ttyUSB0` is JTAG). For example:
|
||
|
||
```bash
|
||
picocom -b 115200 /dev/ttyUSB1
|
||
```
|
||
|
||
## Linux login with colour
|
||
|
||
Install the `basys3` terminfo entry once (as your user, or with `sudo` and no
|
||
`-o` for every user):
|
||
|
||
```bash
|
||
tic -x -o ~/.terminfo terminfo/basys3.ti
|
||
```
|
||
|
||
Run a getty on the port at a fixed speed with that terminal type:
|
||
|
||
```bash
|
||
sudo mkdir -p /etc/systemd/system/serial-getty@ttyUSB1.service.d
|
||
```
|
||
|
||
```bash
|
||
printf '[Service]\nExecStart=\nExecStart=-/usr/sbin/agetty -L 115200 %%I basys3\n' | sudo tee /etc/systemd/system/serial-getty@ttyUSB1.service.d/override.conf
|
||
```
|
||
|
||
```bash
|
||
sudo systemctl daemon-reload && sudo systemctl restart serial-getty@ttyUSB1.service
|
||
```
|
||
|
||
For 132 columns, switch the terminal and tell the PC its size:
|
||
|
||
```bash
|
||
printf '\033[?3h'; export TERM=basys3-w; stty rows 64 cols 132
|
||
```
|
||
|
||
The getty sets `TERM=basys3` for the login session. Programs find the entry in
|
||
`~/.terminfo` once you're logged in. Without the entry, `TERM=vt220` works but
|
||
has no colour.
|
||
|
||
Without the override, Ubuntu's getty keeps whatever speed the port had when it
|
||
appeared, which is usually 9600. Then set SW1:0 to `01` (9600).
|
||
|
||
To start the getty whenever the board is plugged in, add a udev rule (use your
|
||
board's serial number from `udevadm info -q property -n /dev/ttyUSB1`):
|
||
|
||
```bash
|
||
echo 'ACTION=="add", SUBSYSTEM=="tty", ENV{ID_SERIAL_SHORT}=="210183BB7B5B", ENV{ID_USB_INTERFACE_NUM}=="01", TAG+="systemd", ENV{SYSTEMD_WANTS}+="serial-getty@%k.service"' | sudo tee /etc/udev/rules.d/99-basys3-getty.rules
|
||
```
|
||
|
||
Set SW6 up so Backspace sends DEL, which the `basys3` entry expects.
|
||
|
||
### Speed
|
||
|
||
SW1:0 sets the serial speed: `00` 115200, `01` 9600, `10` 921600, `11` 3
|
||
Mbaud. The terminal paces the PC with XON/XOFF (Linux honours it by default),
|
||
so the PC can send at full speed. Tested on the board: a 17 KB, 300-line
|
||
program sent to BASIC in one burst at 921600 and at 3 Mbaud listed back
|
||
identical.
|
||
|
||
For the fastest terminal:
|
||
- **SW8 down.** Smooth scrolling deliberately holds output to 7.5 lines a
|
||
second (15 with SW9). A program can also turn it on with `ESC[?4h`;
|
||
`printf '\033[?4l'` turns it off.
|
||
- **The PC at the same speed**, for example the getty override above with
|
||
`3000000` in place of `115200`, or `picocom -b 3000000 /dev/ttyUSB1`.
|
||
- **Programs that write to the port must also read from it.** If nothing
|
||
reads, the PC's input buffer fills and Linux stops reading the port. It then
|
||
never sees the terminal's XON and stops sending. `tools/send-bas.py` reads the
|
||
echo as it sends for this reason.
|
||
|
||
## Controls
|
||
|
||
| Control | Function |
|
||
|---|---|
|
||
| SW1:0 | Baud: `00` 115200, `01` 9600, `10` 921600, `11` 3000000 (see Speed below) |
|
||
| SW2 | Local echo |
|
||
| SW3 | Received LF also does CR (for hosts that send bare `\n`) |
|
||
| SW5:4 | Default text colour: `00` green, `01` yellow, `10` white, `11` cyan |
|
||
| SW6 | Backspace sends DEL (`7F`) instead of BS (`08`) |
|
||
| SW7 | Enter sends CR LF instead of CR |
|
||
| SW8 | Smooth scrolling (the host can also turn it on with `ESC[?4h`) |
|
||
| SW9 | Fast smooth scrolling: 15 lines/s instead of 7.5 |
|
||
| SW14 | Z-80 mode: link the PC's serial port to the Z-80 too (PC input is typed into BASIC, BASIC's output is copied to the PC) |
|
||
| SW15 | Z-80 mode: the terminal is the Z-80's console |
|
||
| BTNC | Reset (clears screen, shows banner, restarts the Z-80) |
|
||
| BTNU | Clear screen |
|
||
| BTND | Reset the Z-80 only (or Ctrl-Alt-Del on the keyboard, in Z-80 mode) |
|
||
| Pause key | Z-80 mode: stop the Z-80 in the machine-code monitor |
|
||
| LED7:0 | Last byte received |
|
||
| LED11:8 | VT220 keyboard LEDs L4..L1 (`ESC[n q`) |
|
||
| LED12 / 13 / 14 / 15 | Bell / Caps Lock / UART RX activity / keyboard activity |
|
||
| 7-segment | Left: last keyboard scan code. Right: last byte sent. In Z-80 mode: whatever BASIC sends to ports 33/32 (`OUT 32,n`). |
|
||
|
||
## Terminal features
|
||
|
||
- **Controls**: BEL, BS, HT, LF/VT/FF, CR, SO/SI, CAN/SUB. Controls act even in
|
||
the middle of an escape sequence, as on a real VT220.
|
||
- **Cursor**:
|
||
- Movement: `CUU CUD CUF CUB CNL CPL CHA HPA VPA CUP HVP`
|
||
- Position save and restore: `DECSC`/`DECRC` (`ESC 7`/`ESC 8`), also `CSI s`/`CSI u`
|
||
- `IND`, `NEL` and `RI`
|
||
- **Editing**:
|
||
- Insert and delete characters: `ICH DCH ECH`
|
||
- Insert and delete lines: `IL DL`
|
||
- Erase in display and line: `ED EL`, including `DECSED`/`DECSEL`
|
||
- Scroll up and down: `SU SD`
|
||
- Insert mode (`IRM`)
|
||
- **Scroll regions** (`DECSTBM`), origin mode (`DECOM`), auto-wrap (`DECAWM`,
|
||
deferred wrap like a real VT).
|
||
- **Tabs**: settable stops with `HTS`, `TBC`, `CHT` and `CBT`.
|
||
- **Character sets**: G0/G1 designation with `ESC ( 0`, `ESC ) 0` and `ESC ( A`,
|
||
and SO/SI switching. DEC special graphics are drawn with the CP437 line-drawing
|
||
characters.
|
||
- **SGR attributes**: bold (bright colour), underline, blink, reverse,
|
||
concealed, and their resets.
|
||
- **SGR colours**: the 8 standard and 8 bright colours, foreground and
|
||
background. 256-colour (`38;5;n`) and RGB (`38;2;r;g;b`) codes are
|
||
approximated to the 16 colours.
|
||
- **Modes**: `DECCKM` (cursor keys), `DECKPAM`/`DECKPNM` (keypad), `LNM`,
|
||
`DECTCEM` (cursor on/off), `DECSCLM` (smooth scroll), alternate screen
|
||
(`CSI ?47 h`/`l`, a second page; graphics are hidden while it is shown),
|
||
`DECCOLM` (`CSI ?3 h`/`l`: 132x64 / 80x32, clearing the screen as a VT100
|
||
does).
|
||
- **Replies to the host**:
|
||
- `DA` gets `ESC[?62;22c` (a VT220 with colour)
|
||
- Secondary `DA` gets `ESC[>1;10;0c`
|
||
- `DSR 5` and `DSR 6`/`CPR` are answered
|
||
- **Resets**: `RIS` (`ESC c`), `DECSTR` (`ESC[!p`), `DECALN` (`ESC # 8`).
|
||
- **Flow control**: the terminal sends XOFF when its 1 KB input buffer passes 256
|
||
bytes and XON when it drains below 32. Smooth scrolling relies on this. Linux
|
||
serial ports honour it by default (`stty ixon`).
|
||
|
||
### Keyboard
|
||
|
||
| Key | Sends |
|
||
|---|---|
|
||
| Arrows | `ESC [ A`..`D`, or `ESC O A`..`D` when the host sets `DECCKM` |
|
||
| Home / End | `ESC [ 1 ~` / `ESC [ 4 ~` (VT220 Find / Select) |
|
||
| Insert / Delete / PgUp / PgDn | `ESC [ 2 ~` / `3 ~` / `5 ~` / `6 ~` |
|
||
| F1–F4 | `ESC O P` … `ESC O S` |
|
||
| F5–F12 | `ESC [ 15 ~`, `17 ~`, `18 ~`, `19 ~`, `20 ~`, `21 ~`, `23 ~`, `24 ~` |
|
||
| Keypad | Digits; in application mode (`ESC =`) `ESC O p`..`y`, `ESC O M` for Enter |
|
||
| Alt + key | `ESC` then the key |
|
||
| Ctrl + key | `^@`, `^A`..`^Z`, `^[ ^\ ^] ^^ ^_` |
|
||
|
||
### Limits
|
||
|
||
- Text from the host is drawn as CP437 bytes; there is no UTF-8 decoding. Use a
|
||
non-UTF-8 locale such as `LANG=C`, or ASCII-only output, for clean line drawing.
|
||
- No 132-column mode, double-width/height lines, soft fonts, or printer port.
|
||
|
||
## Z-80 BASIC
|
||
|
||
Flip **SW15 up**. The Z-80 runs all the time; while the switch is down it simply
|
||
waits at its next character of output, so flipping back and forth loses
|
||
nothing. The first time, the BASIC banner and `READY` appear.
|
||
|
||
```
|
||
10 FOR I = 1 TO 10
|
||
20 PRINT I, SQR(I)
|
||
30 NEXT I
|
||
RUN
|
||
```
|
||
|
||
Type numbered lines to store a program, or a statement without a number to run
|
||
it at once (`PRINT 2^10`). Ctrl-C stops a running program; Backspace and Ctrl-U
|
||
edit the line being typed.
|
||
|
||
- **Commands**: `RUN [line]`, `LIST [a][-b]`, `NEW` (also `SCRATCH`).
|
||
- **Files in flash**: `SAVE "NAME"`, `LOAD "NAME"`, `RUN "NAME"`, `DIR`,
|
||
`DEL "NAME"`; data files with `OPEN "NAME" FOR INPUT|OUTPUT|APPEND AS #n`,
|
||
`PRINT #n`, `INPUT #n`, `LINE INPUT #n`, `EOF(n)`, `CLOSE [#n]`; memory
|
||
blocks with `BSAVE "NAME",start,length` and `BLOAD "NAME"[,address]`.
|
||
- **Date**: `DATE "2026-11-28 09:30"` sets the clock (the PC tools do it when
|
||
they connect), `DATE$` reads it, and `DIR` shows when each file was made.
|
||
- **Statements**:
|
||
- Assignment and output: `LET` (optional), `PRINT` (`,` for 15-column zones,
|
||
`;` to join, `TAB(n)`), `INPUT ["prompt";] vars`
|
||
- Control: `IF expr THEN line|statement`, `GOTO`, `GOSUB`/`RETURN`,
|
||
`ON expr GOTO|GOSUB list`, `FOR v = a TO b [STEP s]` / `NEXT [v]`, `END`,
|
||
`STOP`
|
||
- Data: `DIM`, `DEF FNx(v) = expr`, `READ`/`DATA`/`RESTORE`, `REM`
|
||
- Machine access: `RANDOMIZE`, `POKE addr,v`, `OUT port,v`, `CALL addr`,
|
||
`MONITOR`
|
||
- Graphics: `CLS`, `COLOR c`, `PLOT x,y[,c]`, `LINE`, `RECT`, `FILL`
|
||
(`x1,y1,x2,y2[,c]`), `CIRCLE x,y,r[,c]`
|
||
- Text placement: `LOCATE row,col`, `INK fg[,bg]`
|
||
- Several statements can share a line, separated by `:`.
|
||
- **Variables**:
|
||
- Numbers: a letter or a letter and digit (`X`, `A1`), single-precision
|
||
floating point.
|
||
- Arrays: one letter, one or two subscripts from 0, 10 by default.
|
||
- Strings: `A$`..`Z$`, up to 79 characters.
|
||
- **Operators**: `+ - * / ^`, `= <> < > <= >=`, `AND OR NOT`.
|
||
- **Functions**:
|
||
- Numeric: `SIN COS TAN ATN EXP LOG ABS SQR INT RND SGN`, `FNx`
|
||
- Strings: `LEN VAL ASC`, `CHR$ STR$ LEFT$ RIGHT$ MID$`
|
||
- Machine: `PEEK(addr)`, `INP(port)`, `TIM` (seconds since reset), `DATE$`, `EOF(n)`,
|
||
`POINT(x,y)` (graphics pixel colour)
|
||
- Spaces are optional, as at Dartmouth: `FORI=1TO10` works.
|
||
- `DATA` takes the rest of its line.
|
||
|
||
About 20.5 KB of program space is free; F000h-F3F7h is kept free for machine code.
|
||
|
||
**Graphics:** the layer is 320×240 pixels in the 16 terminal colours, each
|
||
pixel a 4×4 block, with (0,0) at the top left. Colour 0 is transparent. Text is
|
||
drawn on top, and the graphics show through blank text.
|
||
|
||
**Sprites:** 32 hardware sprites of 16×16 graphics pixels, from 64 shapes, in
|
||
front of the graphics and behind the text, with flipping and sprite-sprite and
|
||
sprite-graphics collision flags. BASIC moves them with `OUT` (ports 112–119)
|
||
and reads the frame counter and collisions with `INP` (120, 128–135); see the
|
||
manual. `basic/examples/sprites.bas` is a small example.
|
||
|
||
**Scrolling:** ports 35h–37h set the point of the 320×240 graphics shown at
|
||
the top left; the picture wraps round. Bit 1 of port 36h hides the graphics in
|
||
a border (4 columns each side, 2 rows top and bottom) so a program can draw the
|
||
strip scrolling into view unseen. The video keeps its own column and row
|
||
counters, loaded from the scroll registers at the end of each line and frame,
|
||
so scrolling adds no arithmetic to the pixel pipeline.
|
||
|
||
**Held keys:** port 88h reads the arrows/WASD, fire, Enter, Shift and Esc as
|
||
held-down bits, and 89h any key by scan code (`rtl/ps2_keyboard.v`,
|
||
`ps2_keystate`), so games don't depend on typematic repeat.
|
||
|
||
**The Iron Keep** (`games/keep/`) is a top-down escape game in C for the Z-80
|
||
using all of this: twelve rooms, guards that patrol, see along rows and
|
||
columns and shoot, keys and locked doors, gold, ammunition and a crown to
|
||
steal. `RUN "KEEP"` on the board. To build and install it:
|
||
|
||
```bash
|
||
games/keep/build.sh # -> keep.ihx (SDCC)
|
||
tools/send-hex.py games/keep/keep.ihx --save KEEPGAME --baud 3000000 # through the monitor
|
||
tools/send-bas.py games/keep/keep.bas --baud 3000000 # the loader, then SAVE "KEEP"
|
||
python3 games/keep/test-keep.py --play --shots /tmp/keep # emulator test (pyte, Pillow)
|
||
```
|
||
|
||
**Bastion Raid** (`games/raid/`) is an isometric scrolling shooter: fly over a
|
||
fortress, climb over low walls and through the doorways in tall ones, shoot
|
||
turrets, fuel tanks and fighters, and destroy the reactor core. `RUN "RAID"`.
|
||
It draws the world pixel by pixel from a formula into the scrolled graphics:
|
||
two columns and a row a frame, about 40% of the Z-80's time. Build and install
|
||
it the same way (`games/raid/build.sh`, then `send-hex.py raid.ihx --save
|
||
RAIDGAME` and `raid.bas` saved as `RAID`). `test-raid.py --play` flies the
|
||
whole level with an autopilot, checks every frame fits in a 60th of a second,
|
||
and takes screenshots.
|
||
|
||
`tools/boardemu.py` models the board's game hardware (graphics, scrolling,
|
||
sprites, held keys, terminal) around `tools/z80emu.py` for both tests.
|
||
|
||
`gen.py` holds the art and the castle map and checks that every room joins up
|
||
and every key, door and the crown can be reached. `test-keep.py` runs the game
|
||
in `tools/z80emu.py` on a model of the board's ports, takes screenshots, and
|
||
lets a bot play it through.
|
||
|
||
**Manual:** [docs/basic-manual.md](docs/basic-manual.md) describes every
|
||
statement and function, with examples, error messages and limits.
|
||
`docs/build-manual.sh` rebuilds the PDF from it.
|
||
|
||
**Files on the board:** BASIC keeps saved programs and data files in the
|
||
configuration flash above the bitstream, from 240000h to the end of the 4 MB
|
||
chip. There is room for 64 files, 1,784 KB in all and up to 32 KB each, and
|
||
they survive power-off. Each directory entry records the file's creation date
|
||
(directory format `BFS2`; a `BFS1` directory from before dates is converted
|
||
when read).
|
||
|
||
- **Layout:** the area is 448 blocks of 4 KB. Blocks 0 and 1 hold the
|
||
directory, written alternately with a sequence number and checksum, so a
|
||
power cut mid-save leaves the previous directory, and the previous version of
|
||
the program, in place. The other blocks hold program listings.
|
||
- **Bitstream protection:** the flash port (`rtl/flash_spi.v`) only passes
|
||
read, status, write enable/disable, ID, page program and 4 KB erase. It drops
|
||
chip select before the address of any program or erase below 240000h reaches
|
||
the chip, so nothing the Z-80 runs can damage the bitstream. Tested on the
|
||
board: an erase at 0 and a write at 200000h were both refused and left the
|
||
flash unchanged.
|
||
- **Reflashing keeps programs:** `scripts/build.sh flash` erases only the
|
||
bitstream's range (about 1.2 MB, compressed), so saved programs survive.
|
||
|
||
**Programs on the PC:** with SW14 and SW15 up, the PC's serial port is linked to
|
||
BASIC both ways. First stop the getty for this boot: it would read BASIC's
|
||
output as login names and type its replies back into BASIC, in a loop.
|
||
|
||
```bash
|
||
sudo systemctl mask --runtime serial-getty@ttyUSB1
|
||
sudo systemctl stop serial-getty@ttyUSB1
|
||
```
|
||
|
||
Then, at the SW1:0 baud rate:
|
||
|
||
```bash
|
||
tools/send-bas.py basic/examples/graphics-demo.bas --baud 9600 --run # type a program in
|
||
tools/get-bas.py myprog.bas --baud 9600 # LIST it into a file
|
||
tools/get-bas.py --baud 9600 --cmd 'DIR' --cmd 'SAVE "DEMO"' # run commands, show replies
|
||
```
|
||
|
||
Both tools set BASIC's date from the PC's clock first (`--no-date` to skip).
|
||
If the port is left root-only (`crw-------`) after stopping the getty,
|
||
`sudo chmod 666 /dev/ttyUSB1` opens it. `sudo systemctl unmask --runtime
|
||
serial-getty@ttyUSB1` (or a reboot) brings the getty back; flip SW14 down
|
||
first.
|
||
|
||
The terminal holds the PC back with XON/XOFF while BASIC catches up, and the
|
||
Z-80 waits when the copy to the PC falls behind.
|
||
`basic/examples/graphics-demo.bas` shows off the graphics: colour bars,
|
||
circles, lines, curves, random shapes, a bouncing ball and a Mandelbrot set.
|
||
|
||
### The machine-code monitor
|
||
|
||
The Pause key, BASIC's `MONITOR`, a breakpoint or a single step stops the
|
||
Z-80 in a monitor in the style of the C64's cartridge monitors. It runs on the
|
||
terminal's alternate screen, so BASIC's screen and graphics come back
|
||
untouched, and shows:
|
||
- the registers and flags;
|
||
- a disassembly from PC, with the next instruction highlighted;
|
||
- the stack and a memory window.
|
||
|
||
Commands: Enter steps one instruction, `S n` steps *n*, `O` steps over a call,
|
||
`G`/`X` carries on, `B addr` sets the breakpoint, `D`/`M addr` move the windows,
|
||
`E addr bytes` writes memory, `R HL=1234` sets a register, and
|
||
`SAVE "NAME" start end`, `LOAD "NAME" [addr]` and `DIR` move memory to and
|
||
from files in flash (the same files as BASIC's `BSAVE`/`BLOAD`). `ASM "NAME"`
|
||
assembles Z-80 source (typed into BASIC as numbered lines and saved) into
|
||
memory, and `A addr` assembles a line at a time. A line starting with `:` is
|
||
an Intel HEX record, written into memory (`tools/send-hex.py` sends whole
|
||
files that way). The manual's section 10 has the details.
|
||
|
||
How it works:
|
||
- **Entry:** the NMI pushes PC and jumps to 0066h. Both BASIC's ROM and the
|
||
monitor's have the same trampoline there (`basic/tramp.s`). It saves AF,
|
||
switches in the monitor's 32 KB bank (`monitor/`, ROM 0000-5FFF and RAM
|
||
6000-7FFF, replacing 0000-7FFF) and enters it.
|
||
- **Reading memory:** the monitor reads the program's memory below 8000h
|
||
through a debug port (62h-64h).
|
||
- **Leaving:** through 0070h, which switches the bank out and does `POP AF`
|
||
and `RETN`.
|
||
- **Stepping:** the hardware counts instruction starts after the leaving
|
||
write and raises the NMI as the program's next instruction begins, so
|
||
exactly one instruction runs.
|
||
- **Breakpoints:** two hardware comparators (the user's and a temporary one
|
||
for step-over) watch each instruction's address. Both work in ROM.
|
||
- **The assembler** (`monitor/asm.c`): two passes with labels,
|
||
expressions and `ORG`/`EQU`/`DB`/`DW`/`DS`/`END`. Its opcode table
|
||
(`monitor/asmtab.h`, 912 forms) is generated from the disassembler by
|
||
`tools/gen-asmtab.py`, so the two agree.
|
||
- `monitor/test-asm.py` assembles every disassembled form back: 913 come
|
||
back exactly, 468 duplicates give the documented encoding.
|
||
- `monitor/test-asm-z80.sh` runs the same lines through the Z-80 build in
|
||
the emulator and compares the output with the PC build.
|
||
- A test program matched sdasz80 byte for byte.
|
||
- SDCC 4.5 can lose a value held in A around an inline `strcpy`, which gave
|
||
the assembler a bad pointer. The monitor copies strings with its own
|
||
function instead.
|
||
- **The disassembler:** it covers every opcode. `monitor/test-disasm.py`
|
||
disassembles all 1,784 forms and assembles each back with `sdasz80`. The
|
||
664 documented forms come back byte for byte. The 455 undocumented
|
||
duplicates assemble to their documented equivalents. 665 undocumented forms
|
||
can't be assembled by `sdasz80`.
|
||
|
||
```bash
|
||
monitor/build.sh # -> monitor/monitor.mem, loaded by the bitstream build
|
||
monitor/test-disasm.py # check the disassembler (needs gcc and sdasz80)
|
||
monitor/test-asm.py # check the assembler against the disassembler
|
||
monitor/test-asm-z80.sh # the same, for the Z-80 build (about 2 minutes)
|
||
tools/gen-asmtab.py # regenerate monitor/asmtab.h after changing the disassembler
|
||
```
|
||
|
||
### The Z-80
|
||
|
||
`rtl/z80_cpu.v` is a Z-80 written for speed rather than cycle accuracy:
|
||
|
||
- Every memory access takes one clock from block RAM.
|
||
- The CPU reads the next byte while it decodes the current one, so a
|
||
register-to-register instruction takes 1 clock, `LD r,n` 2, `LD r,(HL)` 3,
|
||
`JP` 4, `CALL` 6, `RET` 5.
|
||
- `LDIR` moves a byte every 3 clocks.
|
||
- BASIC averages about 2.7 clocks per instruction. At 90 MHz that is about 33
|
||
million instructions a second, against roughly 0.6 million for a 4 MHz Z-80.
|
||
- It runs at 90 MHz from its own clock (an MMCM), the fastest that meets
|
||
timing. The limit is the path from the RAM through opcode decoding into the
|
||
registers.
|
||
- It has the documented instruction set plus the undocumented IXH/IXL/IYH/IYL
|
||
forms, `SLL` and the DDCB register copies, with the undocumented X/Y flags.
|
||
- The only interrupt is a non-maskable one (NMI) for the monitor. It is
|
||
taken at an instruction start, pushes the address of the next instruction
|
||
and jumps to 0066h. It also wakes the CPU from HALT.
|
||
|
||
The 320×240×4-bit graphics layer is a separate dual-clock block RAM: the Z-80
|
||
writes it on its own clock, and the video reads it on the 108 MHz pixel clock.
|
||
`rtl/text_display.v` overlays it on the text. A hardware fill clears it in
|
||
76,800 clocks.
|
||
|
||
`rtl/sprites.v` draws the sprites. The video asks for each graphics line one
|
||
line ahead; the engine clears a 320-pixel line buffer, then walks the sprites
|
||
from 31 down to 0 writing their visible pixels (about 900 clocks of the 6,752
|
||
a graphics line lasts), while the video reads the other buffer. A pixel
|
||
written over another sprite's flags both; a sprite pixel shown over a graphics
|
||
pixel flags that sprite. The flags are collected per frame and handed to the
|
||
Z-80 at the start of vertical blank, along with a frame counter. Shapes are a
|
||
dual-clock block RAM (64 × 16 × 16 × 4 bits); positions and shapes are in
|
||
distributed RAM.
|
||
|
||
Memory is 64 KB of block RAM loaded with BASIC at configuration. Writes below
|
||
8000h are ignored, so the interpreter can't be damaged. BASIC's data and the
|
||
stack fill the top half.
|
||
|
||
| Port | In | Out |
|
||
|---|---|---|
|
||
| 00h | bit 0: key waiting, bit 1: console ready | |
|
||
| 01h | key | character to the screen |
|
||
| 10h–13h | millisecond counter (reading 10h latches the rest) | |
|
||
| 20h / 21h | | 7-segment display, right / left byte |
|
||
| 30h, 31h, 32h | | graphics X low byte, X bit 8, Y |
|
||
| 33h | colour at X,Y | plot at X,Y, then X+1 |
|
||
| 34h | bit 0: fill busy | fill the whole graphics layer with a colour; also turns the sprites off and resets the scroll unless bit 7 is set |
|
||
| 35h, 36h, 37h | | scroll: X low byte; X bit 8 and bit 1 = hide the border; Y (0–239) |
|
||
| 40h | bit 0: SPI byte busy, bit 1: command refused | 1 starts a flash command (chip select low), 0 ends it |
|
||
| 41h | byte received during the last transfer | send a byte to the flash |
|
||
| 60h | why the monitor was entered (1 Pause, 2 port 61h, 3 step, 4/5 breakpoint) | bit 0: monitor bank in; bit 1: stop after one instruction |
|
||
| 61h | | enter the monitor (NMI) |
|
||
| 62h, 63h, 64h | 64h: byte of main memory at the debug address, then address+1 | 62h/63h: debug address |
|
||
| 65h/66h, 68h/69h, 67h | | breakpoint 0 and 1 addresses; 67h bits 1:0 turn them on |
|
||
| 70h | | select sprite 0–31 |
|
||
| 71h, 72h, 73h | | sprite X low byte, X bit 8, Y (writing Y moves it) |
|
||
| 74h, 75h | | sprite shape 0–63; bit 0 on, bit 1 flip X, bit 2 flip Y |
|
||
| 76h, 77h | | start loading shape n; two pixels (left in bits 7:4), then next |
|
||
| 78h | frame counter (+1 each vertical blank) | |
|
||
| 80h–83h | sprites that touched another sprite last frame (bit per sprite) | |
|
||
| 84h–87h | sprites that touched a graphics pixel last frame | |
|
||
| 88h | keys held: bit 0 up (W, cursor, keypad 8), 1 down, 2 left, 3 right, 4 fire (Space, Ctrl), 5 Enter, 6 Shift, 7 Esc | |
|
||
| 89h | 1 if the picked key is held | pick a key by scan code (set 2, +80h for E0 codes) |
|
||
|
||
BASIC is C (`basic/basic.c`) compiled with SDCC (`sudo apt install sdcc`):
|
||
|
||
```bash
|
||
basic/build.sh # -> basic/basic.mem, loaded by the bitstream build
|
||
```
|
||
|
||
The same source builds natively for trying the interpreter on a PC
|
||
(`gcc basic/basic.c -lm`).
|
||
|
||
### Testing the CPU
|
||
|
||
`tools/z80emu.py` is an independent Z-80 emulator in Python.
|
||
`scripts/cpusim.sh` runs an image on the Verilog CPU in xsim and on the
|
||
emulator, then compares every register after every instruction and the RAM at
|
||
the end.
|
||
|
||
```bash
|
||
cd build/cputest && python3 ../../tools/cputest.py 1 1000 && cd ../..
|
||
scripts/cpusim.sh build/cputest/cputest.mem
|
||
```
|
||
|
||
- **Random tests**: `tools/cputest.py <seed>` writes 1000 blocks. Each loads
|
||
random registers, then runs one random instruction from the whole instruction
|
||
set (prefixes, memory forms and block moves included). 50 seeds pass.
|
||
- **BASIC**: `scripts/cpusim.sh basic/basic.mem input.txt` boots BASIC and runs
|
||
a program typed from `input.txt`. That is 1.1 million instructions, all
|
||
identical.
|
||
|
||
## Build and program
|
||
|
||
Requires Vivado. The scripts use the newest install in `~/vivado/<version>/Vivado`;
|
||
set `VIVADO=/path/to/Vivado` to pick another. On this machine 2026.1 has no
|
||
license, so use 2025.2 (`export VIVADO=~/vivado/2025.2/Vivado`).
|
||
|
||
```bash
|
||
./scripts/build.sh # bitstream -> build/basys3_terminal.bit (+ .mcs)
|
||
```
|
||
|
||
The Z-80 clock is `100 MHz × CPU_MULT / CPU_DIV`. The default is 9 / 10, which
|
||
gives 90 MHz, the fastest that meets timing. To try another speed:
|
||
|
||
```bash
|
||
CPU_MULT=8.5 CPU_DIV=10 ./scripts/build.sh
|
||
```
|
||
|
||
```bash
|
||
./scripts/build.sh program # build and load into the FPGA (until power-off)
|
||
```
|
||
|
||
```bash
|
||
./scripts/build.sh flash # build, write QSPI flash and reboot from it (JP1 on QSPI)
|
||
```
|
||
|
||
The flash script handles both Basys 3 flash chips (Spansion `s25fl032p` on
|
||
older boards, Macronix `mx25l3273f` on newer ones).
|
||
|
||
## Simulation
|
||
|
||
`sim/tb_terminal.v` covers the whole design:
|
||
|
||
- It types keys over PS/2 and checks the bytes sent on the UART, including
|
||
`DECCKM` and keypad application mode.
|
||
- It checks the `DA`, secondary `DA` and `CPR` replies, and the `DECLL` LEDs.
|
||
- It draws colours, line graphics, insert/delete, scroll regions and a smooth
|
||
scroll, then checks the screen buffer.
|
||
- It checks VGA sync timing and saves two frames, `sim/work/frame_1.png` and
|
||
`sim/work/frame_2.png` (the second is taken mid-scroll).
|
||
- It switches to Z-80 mode, types `PRINT 2+2` and a short program over the
|
||
UART, and checks BASIC's output on the screen.
|
||
- It enters the monitor with `MONITOR`, checks the screen, single-steps a
|
||
`JP` onto its target and sets a breakpoint that BASIC then hits. It also
|
||
enters through the Pause key and checks BASIC's screen comes back.
|
||
- It draws graphics from BASIC and checks the pixels.
|
||
- It defines sprite shapes and places overlapping, flipped and edge-clipped
|
||
sprites from BASIC, then checks the pixels on screen, the collision ports and
|
||
that `CLS` turns the sprites off.
|
||
- It holds Ctrl and right Shift on the PS/2 line and reads them back on the
|
||
held-key ports, then releases them.
|
||
- In the monitor, it sends an Intel HEX record and checks memory.
|
||
- It scrolls the graphics and checks where pixels land, wrapping round, with
|
||
and without the border, and that `CLS` resets it.
|
||
- Against a model flash (`sim/spiflash_model.v`) it sets the date, saves,
|
||
loads, runs and lists a program (checking the date in `DIR`), tries to erase
|
||
address 0 and checks the model saw no write below 240000h, then writes a data
|
||
file and reads it back.
|
||
|
||
```bash
|
||
VIVADO=~/vivado/2025.2/Vivado ./scripts/sim.sh
|
||
```
|
||
|
||
`scripts/vivado_env.sh` adds an ncurses 5 compatibility link under `build/`,
|
||
which Vivado needs on newer distros.
|
||
|
||
## Layout
|
||
|
||
| Path | Contents |
|
||
|---|---|
|
||
| `rtl/basys3_terminal.v` | Top level: reset, switches, FIFOs, flow control, banner, LEDs, Z-80 clock |
|
||
| `rtl/z80_cpu.v` | Z-80 CPU |
|
||
| `rtl/z80_system.v` | Z-80 RAM, console, timer, graphics and flash ports, monitor bank, step and breakpoints |
|
||
| `rtl/sprites.v` | Hardware sprites: shapes, line buffers, collisions |
|
||
| `rtl/flash_spi.v` | SPI port to the configuration flash, with bitstream write protection |
|
||
| `monitor/` | Machine-code monitor (C and start-up code), its build script and disassembler test |
|
||
| `basic/tramp.s` | The NMI entry and exit bytes shared by BASIC and the monitor |
|
||
| `tools/send-bas.py`, `tools/get-bas.py` | Send a BASIC program to the board / copy one back, run commands |
|
||
| `tools/send-hex.py` | Load an Intel HEX file through the monitor and save it as a memory file |
|
||
| `games/keep/` | The Iron Keep: game (C), art and map generator, loader, emulator test |
|
||
| `games/raid/` | Bastion Raid: game (C), art and level generator, loader, emulator test with autopilot |
|
||
| `tools/boardemu.py` | Model of the board's game hardware around `z80emu.py`, with screenshots |
|
||
| `basic/` | BASIC interpreter (C), start-up code, build script, `basic.mem` |
|
||
| `tools/z80emu.py`, `tools/cputest.py`, `scripts/cpusim.sh` | CPU test bench: reference emulator, random tests |
|
||
| `rtl/term_ctrl.v` | VT220 engine (parser, modes, attributes, copy/fill engine, smooth scroll) |
|
||
| `rtl/text_display.v` | VGA timing, colour palette, character RAM, font lookup |
|
||
| `rtl/ps2_keyboard.v` | PS/2 receiver and scan code set 2 to ASCII / VT220 keys |
|
||
| `rtl/uart.v` | UART receiver and transmitter |
|
||
| `rtl/fifo.v`, `rtl/sevenseg.v` | Helpers |
|
||
| `font/font.mem` | 256x16 font ROM, made by `tools/psf2mem.py` from the Linux console fonts |
|
||
| `terminfo/basys3.ti` | terminfo entries: `basys3` (VT220, 16 colours, 80x32) and `basys3-w` (132x64) |
|
||
| `constraints/basys3.xdc` | Pin assignments |
|
||
|
||
## License
|
||
|
||
MIT; see [LICENSE](LICENSE). The glyphs in `font/font.mem` come from the Linux
|
||
console fonts named in its first line, which keep their own licenses.
|