Files
Basys3RiscV/README.md
T
brad ArantandClaude Opus 5.5 2e668c708f BASIC compiler (tools/basc.py) and a runtime jump table in BASIC's ROM
tools/basc.py compiles a BASIC program to C and through GCC to an Intel HEX
file loaded at A200h like the games, with a two-line BLOAD/CALL loader.
Arithmetic, variables, arrays, all control flow and graphics arguments are
compiled; PRINT, INPUT, strings, files, sound, DATA and the remaining
functions go through BASIC's ROM via a fixed jump table at 9F00h (RT_ABI 1),
so they behave identically. basic/test-compile.py runs 31 programs both
ways and checks identical screens and graphics; typical loops run 7-26x
faster. New error PROGRAM NEEDS ANOTHER BASIC.

Fixes a bug present since the first version: variable numbers past 255
wrapped, so X1-Z9 shared storage with A-B9 (A7 and Y were the same
variable). test-blocks.py checks it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:29:59 -08:00

228 lines
11 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Basys 3 RISC-V Computer
A complete home computer on a Digilent Basys 3 FPGA board, built around a
RISC-V processor written from scratch in Verilog:
- **RV32IMF processor at 100 MHz**: integer, multiply/divide and IEEE 754
single-precision floating point in hardware, with traps, interrupts, hardware
breakpoints and single step.
- **VT220 terminal** with ANSI colour on 1280×1024 VGA: 132 × 64 text, or 80 × 32
in a double-size font.
- **Graphics** over the text: 320 × 240 in 16 colours with hardware scrolling,
or 640 × 480 in two colours, plus 32 hardware sprites.
- **Sound**: a three-voice chip with noise and envelopes (PmodAMP2 on JA).
- **USB keyboard** on the board's USB host port, with a keys-held port for
games.
- **Files** saved in the board's configuration flash.
- **Software**: Dartmouth-style BASIC with graphics, sound and files,
`DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`, and scientific
functions (inverse and hyperbolic trigonometry in radians or degrees,
`LOG10`, `ROUND`, `MOD`, `FACT` …), and `UCASE$`/`LCASE$`; a
machine-code monitor with a RISC-V disassembler and assembler, and five
original games.
- **A BASIC compiler** for the PC (`tools/basc.py`): the same program, the
same results and error messages, 7 to 26 times as fast in loops and
arithmetic.
The [BASIC manual](docs/basic-manual.md) ([PDF](docs/basic-manual.pdf))
describes the computer from the user's side: BASIC, graphics, sprites, sound,
files, the monitor and the games.
## Getting started
Download `basys3_terminal.bit` (or `basys3_terminal.mcs` to keep it in the
flash) from the [latest release](https://git.barant.com/barant/Basys3RiscV/releases),
or build it yourself (below).
1. Plug a VGA monitor, a USB keyboard, and optionally a PmodAMP2 into JA.
2. Load the bitstream with Vivado's Hardware Manager, or `scripts/build.sh
program` / `flash` from a checkout.
3. Flip **SW15 up**. The screen shows BASIC's banner and `READY`.
With SW15 down the board is a plain VT220 terminal on its USB serial port, for
a PC. The computer keeps running underneath, waiting at its next character of
output, so flipping back and forth loses nothing.
The games come in the release as `*.ihx` (the program) and `*.bas` (the
loader). From a checkout of this repository, on a PC connected to the board's
serial port:
```bash
tools/send-hex.py keep.ihx --save KEEPGAME --baud 3000000
```
```bash
tools/send-bas.py keep.bas --baud 3000000
```
then `SAVE "KEEP"` in BASIC, and `RUN "KEEP"` from then on.
## Controls
| Control | Function |
|---|---|
| SW1:0 | Serial speed: `00` 115200, `01` 9600, `10` 921600, `11` 3000000 |
| SW2 | Local echo |
| SW3 | Received LF also does CR |
| SW5:4 | Text colour at start-up: `00` white, `01` yellow, `10` green, `11` cyan |
| SW6 | Backspace sends DEL (`7F`) instead of BS (`08`) |
| SW7 | Enter sends CR LF instead of CR |
| SW8 | Smooth scrolling (also `ESC[?4h`) |
| SW9 | Fast smooth scrolling: 15 lines a second instead of 7.5 |
| SW14 | Computer mode: link the PC's serial port too (PC input is typed into BASIC, BASIC's output is copied to the PC) |
| SW15 | Computer mode: the terminal is the computer's console |
| BTNC | Reset everything |
| BTNU | Clear the screen |
| BTND | Restart the computer only (or Ctrl-Alt-Del in computer mode) |
| Pause key | Stop the program in the machine-code monitor |
| LED7:0 | Last byte received |
| LED11:8 | VT220 keyboard LEDs L4..L1 (`ESC[n q`) |
| LED12–15 | Bell, Caps Lock, serial activity, keyboard activity |
| 7-segment | In computer mode, whatever a program writes to ports 33/32 (`OUT 32,n`); otherwise the last scan code and the last byte sent |
## The terminal
The terminal understands what a VT220 does, plus ANSI colour:
- Cursor movement, save and restore, `IND`/`NEL`/`RI`; insert and delete of
characters and lines, erase, scroll, insert mode.
- Scroll regions, origin mode, deferred auto-wrap, tab stops.
- DEC special graphics (drawn with the CP437 line characters).
- Bold, underline, blink, reverse, concealed; 16 foreground and background
colours (256-colour and RGB codes are mapped to the nearest).
- Cursor and keypad application modes, cursor on/off, smooth scrolling, the
alternate screen, `DECCOLM` (`ESC[?3h` 132 × 64, `ESC[?3l` 80 × 32).
- Replies to `DA`, secondary `DA` and `DSR`/`CPR`; `RIS`, `DECSTR`,
`DECALN`.
- XON/XOFF flow control, so a PC can send at full speed.
For a Linux login on the board, install the terminfo entry and run a getty
on the board's port (the second of its two, usually `/dev/ttyUSB1`):
```bash
tic -x -o ~/.terminfo terminfo/basys3.ti
```
```bash
sudo /usr/sbin/agetty -L 115200 ttyUSB1 basys3-w
```
`basys3-w` is the 132 × 64 entry (`stty rows 64 cols 132`); `basys3` is
80 × 32. Set SW6 up so Backspace sends DEL. Text is drawn as CP437 bytes, with
no UTF-8 decoding, so use `LANG=C` for clean line drawing.
## The processor (`rtl/rv32_cpu.v`)
RV32IMF in machine mode: the base integer set, multiply/divide,
single-precision floating point (`rtl/rv32_fpu.v`: IEEE 754 with all five
rounding modes, subnormals and the exception flags), CSRs, counters
(`cycle`, `time`, `instret`), `fence.i`, `ecall`/`ebreak`/`mret`/`wfi`, traps
and interrupts (`mtvec`, `mepc`, `mcause`, `mtval`; software, timer, external
and 16 local interrupt lines), two hardware triggers for execute, load and
store breakpoints, and a resumable NMI (after the Smrnmi extension: `mnepc`,
`mnstatus`, `mnret`) with a single-step input, for the monitor.
It is a multi-cycle design with the next instruction fetched while the current
one decodes: 2 clocks for most instructions, 3 for taken branches, jumps, loads
and stores, 4 for multiplies, 35 for divides; BASIC averages about 2.5.
Floating-point add, subtract, multiply and the fused multiply-adds take 13
clocks, divide and square root 37. It runs at 100 MHz and takes about 5,300
LUTs (3,000 of them the FPU), 1,900 flip-flops and 6 DSP slices.
## The machine (`rtl/rv32_system.v`)
| Addresses | |
|---|---|
| 0000_0000–0001_3FFF | RAM, 80 KB of block RAM, BASIC preloaded; writes below A000h (BASIC's code) are ignored |
| 0002_0000–0002_7FFF | the monitor's ROM (32 KB of block RAM); the NMI enters at 20000h, traps at 20004h |
| 0002_8000–0002_9FFF | the monitor's RAM (8 KB of distributed RAM, data only) |
| FFFF_FE00–FFFF_FEFF | 32-bit registers: milliseconds, microseconds, the timer interrupt's compare, breakpoints |
| FFFF_FF00–FFFF_FFFF | byte-wide I/O ports: port *N* at FFFF_FF00 + *N*, one instruction from `x0` (`sb a0,-255(zero)` writes port 1) |
The ports (listed at the top of `rv32_system.v` and in the manual) cover the
console, the millisecond counter, the 7-segment display, graphics, sprites,
sound, the keys held down and the flash. The peripherals are `term_ctrl.v`
(the VT220), `text_display.v` (video), `sprites.v`, `sound.v`,
`flash_spi.v`, `uart.v`, `ps2_keyboard.v` and `sevenseg.v`.
The graphics memory is 76,800 four-bit entries: 320 × 240 pixels in 16
colours, or, with port 38 set, 640 × 480 pixels at one bit each (four to an
entry; a plot reads the entry and writes it back with one bit changed). To
fit the block RAM, the text screen and the graphics are each split into a
power-of-two array and a small one, because Vivado builds an array of 16,896
or 76,800 entries as 32K or 96K deep. That saves 10.5 block RAMs. The design
uses 49.5 of the XC7A35T's 50.
## Software
All in C (plus a little assembly), compiled with GCC:
- `basic/` — BASIC, with single-precision arithmetic on the FPU (`rv32imf`,
`ilp32f`), correctly rounded, and the structured statements of later
Dartmouth BASIC and True BASIC (`DO … LOOP`, `EXIT`, block `IF`, `SELECT
CASE`). `lib/` has the few C library functions it
needs (small string functions, `setjmp`, and `sinf` … `sqrtf`, `asinf`,
`sinhf`, `atanhf`, `log10f`, an exact `fmodf` and the rest, each within 3
ulp), since
newlib's bring in its stdio and malloc.
- `monitor/` — the machine-code monitor: memory, registers (integer and
floating point), step, breakpoints, a RISC-V disassembler and a two-pass
assembler that both use GNU as syntax (`.org`, `.word`, `.string`,
`%hi`/`%lo`, `#` comments; the disassembly reads like `objdump`'s), Intel
HEX in and out.
- `tools/basc.py` — the BASIC compiler. It reads a program with BASIC's own
tokens and turns it into C for GCC: arithmetic, variables, arrays, control
statements and graphics become machine code on the FPU; everything else is
handed, as tokens, to the interpreter in ROM through a jump table at 9F00h
(`rt_table` in `basic.c`), so it behaves the same. It loads at A200h like the
games.
- `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal
Cavern; they load at A200h (`CALL 41472`).
| BASIC on the board | |
|---|---|
| `Y = SIN(X)` | 33 µs |
| `Y = EXP(1)` | 33 µs |
| `X = I * 1.5` | 23 µs |
| An empty `FOR` loop, each time round | 6.4 µs |
## Building
```bash
export VIVADO=~/vivado/2025.2/Vivado
```
```bash
basic/build.sh && monitor/build.sh && for g in keep raid warden swarm cavern; do games/build-game.sh $g; done
```
```bash
scripts/build.sh
```
`scripts/build.sh program` loads the bitstream over JTAG; `flash` writes it to
the configuration flash.
## Tests
| | |
|---|---|
| `scripts/fputest.sh` | `rtl/rv32_fpu.v` against `tools/f32.py`, an exact model of RISC-V's single precision (itself checked against the PC's FPU), on random vectors: every F instruction, every rounding mode, special values, subnormals and near-cancellations |
| `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. |
| `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. |
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as, byte for byte, on a program in GNU syntax and one in the assembler's older spellings |
| `basic/test-compile.py` | every program in `basic/examples` and in the other BASIC tests, plus programs for each statement and error, run interpreted and compiled in the emulator: the screen and the graphics must come out the same. It also times them. |
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. |
| `bench/` | the processor alone with 64 KB of RAM, for timing |
## Toolchain
- Vivado (2025.2 is the licensed install here).
- RISC-V GCC: Vivado ships one for MicroBlaze V (`~/vivado/*/gnu/riscv/lin/bin/riscv64-unknown-elf-gcc`,
GCC 13 with an `rv32im/ilp32` multilib), which `scripts/rv_env.sh` finds
if there is no `riscv64-unknown-elf-gcc` on the PATH. `RV_PREFIX` overrides.
## License
MIT; see [LICENSE](LICENSE).