Flash file system for BASIC, with bitstream write protection

BASIC gets SAVE, LOAD, RUN "NAME", DIR and DEL, storing program listings
in the configuration flash from 240000h (448 x 4 KB blocks, 64 files,
32 KB each). The directory is kept in two alternating blocks with a
sequence number and checksum, new data is written before the directory
switches to it, and every page is verified after programming.

rtl/flash_spi.v drives the flash through STARTUPE2 on ports 40h/41h. It
only passes read, status, WREN/WRDI, RDID, page program and 4 KB erase,
and abandons any program or erase below 240000h before the address
reaches the chip. Tested on the board: an erase at 0 and a write at
200000h were refused and left the flash unchanged.

With SW14 up, the Z-80's output is also copied to the PC's serial port,
and tools/get-bas.py uses that to LIST a program into a file or run
commands and print the replies.

Also fixes port 10h returning the previous millisecond latch (the first
read after reset was undefined). Simulation adds a model flash and a
save/load/run/protection test. Manual and README updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
brad ArantandClaude Opus 5.5 committed 2026-11-28 08:33:52 -08:00
1 parent dc7c7c22c5
commit 29a15bf7c7
15 files changed
+6905 -6054

No files matched your search

+1
View File
@@ -6,3 +6,4 @@ build/
*_out.txt
basic/out/
sim/cpu/
__pycache__/
+49 -8
View File
@@ -73,7 +73,7 @@ Set SW6 up so Backspace sends DEL, which the `basys3` entry expects.
| 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: text from the PC's serial port also goes to the Z-80 (for pasting programs) |
| 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 |
@@ -156,6 +156,8 @@ 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"`.
- **Statements**:
- Assignment and output: `LET` (optional), `PRINT` (`,` for 15-column zones,
`;` to join, `TAB(n)`), `INPUT ["prompt";] vars`
@@ -192,17 +194,48 @@ drawn on top, and the graphics show through blank text.
statement and function, with examples, error messages and limits.
`docs/build-manual.sh` rebuilds the PDF from it.
**Loading programs from the PC:**
**Saving programs on the board:** BASIC keeps programs in the configuration
flash above the bitstream, from 240000h to the end of the 4 MB chip. There is
room for 64 programs, 1,784 KB in all and up to 32 KB of listing each, and they
survive power-off.
1. Flip SW14 and SW15 up.
2. Stop the getty: `sudo systemctl stop serial-getty@ttyUSB1`.
3. Send the program at the SW1:0 baud rate:
- **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
tools/send-bas.py basic/examples/graphics-demo.bas --baud 9600 --run
sudo systemctl mask --runtime serial-getty@ttyUSB1
sudo systemctl stop serial-getty@ttyUSB1
```
The terminal holds the PC back with XON/XOFF while BASIC catches up.
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
```
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.
@@ -242,6 +275,8 @@ stack fill the top half.
| 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 |
| 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 |
BASIC is C (`basic/basic.c`) compiled with SDCC (`sudo apt install sdcc`):
@@ -312,6 +347,10 @@ older boards, Macronix `mx25l3273f` on newer ones).
`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 draws graphics from BASIC and checks the pixels.
- Against a model flash (`sim/spiflash_model.v`) it saves, loads, runs and
lists a program, then tries to erase address 0 and checks the model saw no
write below 240000h.
```bash
VIVADO=~/vivado/2025.2/Vivado ./scripts/sim.sh
@@ -326,7 +365,9 @@ which Vivado needs on newer distros.
|---|---|
| `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 and timer ports, clock-domain handshakes |
| `rtl/z80_system.v` | Z-80 RAM, console, timer, graphics and flash ports |
| `rtl/flash_spi.v` | SPI port to the configuration flash, with bitstream write protection |
| `tools/send-bas.py`, `tools/get-bas.py` | Send a BASIC program to the board / copy one back, run commands |
| `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) |
BIN
View File
Binary file not shown.
+383 -11
View File
@@ -12,6 +12,9 @@
* transparent. CLS COLOR PLOT LINE RECT FILL CIRCLE and POINT(x,y); LOCATE and
* INK place and colour text.
*
* Files: SAVE "NAME", LOAD "NAME", RUN "NAME", DIR, DEL "NAME" keep programs
* in the spare part of the configuration flash (see the file system below).
*
* Builds with SDCC for the Z-80 (console on I/O ports 0/1) or with a host C
* compiler for testing (stdin/stdout).
*/
@@ -80,6 +83,44 @@ static void g_at(u16 x, u8 y) { gx_lo = x; gx_hi = x >> 8; gy_p = y; }
static void g_put(u8 c) { gpix = c; }
static u8 g_get(void) { return gpix; }
static void g_clear(u8 c) { gfill = c; while (gfill & 1); }
/* SPI flash: port 40h opens/ends a command (bit 1 reads back "refused"),
41h shifts a byte. The hardware refuses to write below the file area. */
__sfr __at 0x40 fl_ctl;
__sfr __at 0x41 fl_dat;
static u8 spi(u8 b) { fl_dat = b; while (fl_ctl & 1); return fl_dat; }
static void fl_open(u8 cmd) { fl_ctl = 1; spi(cmd); }
static void fl_close(void) { fl_ctl = 0; }
static void fl_addr(u32 a) { spi(a >> 16); spi(a >> 8); spi(a); }
static u8 fl_busy(void)
{
u8 st;
fl_open(0x05); st = spi(0); fl_close();
return st & 1;
}
static u8 fl_present(void) /* Macronix MX25L3273F, 4 KB sectors */
{
u8 a, b, c;
fl_open(0x9F); a = spi(0); b = spi(0); c = spi(0); fl_close();
return a == 0xC2 && b == 0x20 && c == 0x16;
}
static void fl_read(u32 a, u8 *p, u16 n)
{
fl_open(0x03); fl_addr(a);
while (n--) *p++ = spi(0);
fl_close();
}
/* page program (02) or sector erase (20); returns 0 if the hardware refused */
static u8 fl_write_op(u8 cmd, u32 a, const u8 *p, u16 n)
{
u8 ok;
fl_open(0x06); fl_close();
fl_open(cmd); fl_addr(a);
while (n--) spi(*p++);
ok = !(fl_ctl & 2);
fl_close();
return ok;
}
#else
#include <stdio.h>
#include <stdlib.h>
@@ -108,6 +149,38 @@ static void g_at(u16 x, u8 y) { hgx = x; hgy = y; }
static void g_put(u8 c) { if (hgx < 320 && hgy < 240) gmem[hgy][hgx] = c; hgx++; }
static u8 g_get(void) { return hgx < 320 && hgy < 240 ? gmem[hgy][hgx] : 0; }
static void g_clear(u8 c) { memset(gmem, c, sizeof gmem); }
/* flash file area kept in basic-flash.img */
#define HOST_BASE 0x240000UL
static u8 hflash[0x1C0000];
static u8 hflash_loaded;
static void hflash_load(void)
{
FILE *f;
if (hflash_loaded) return;
hflash_loaded = 1;
memset(hflash, 0xFF, sizeof hflash);
if ((f = fopen("basic-flash.img", "rb"))) { fread(hflash, 1, sizeof hflash, f); fclose(f); }
}
static void hflash_store(void)
{
FILE *f = fopen("basic-flash.img", "wb");
if (f) { fwrite(hflash, 1, sizeof hflash, f); fclose(f); }
}
static u8 fl_busy(void) { return 0; }
static u8 fl_present(void) { hflash_load(); return 1; }
static void fl_read(u32 a, u8 *p, u16 n) { hflash_load(); memcpy(p, hflash + a - HOST_BASE, n); }
static u8 fl_write_op(u8 cmd, u32 a, const u8 *p, u16 n)
{
u8 *d;
hflash_load();
if (a < HOST_BASE || a >= HOST_BASE + sizeof hflash) return 0;
d = hflash + a - HOST_BASE;
if (cmd == 0x20) memset(hflash + ((a - HOST_BASE) & ~4095UL), 0xFF, 4096);
else while (n--) *d++ &= *p++;
hflash_store();
return 1;
}
#endif
/* ----------------------------------------------------------------- tokens */
@@ -116,7 +189,7 @@ enum {
T_TO, T_STEP, T_NEXT, T_DIM, T_DEF, T_END, T_STOP, T_REM, T_READ, T_DATA,
T_RESTORE, T_ON, T_RANDOMIZE, T_POKE, T_OUT, T_RUN, T_LIST, T_NEW, T_SCRATCH,
T_BYE, T_CLS, T_COLOR, T_PLOT, T_LINE, T_RECT, T_FILL, T_CIRCLE, T_LOCATE, T_INK,
T_AND, T_OR, T_NOT, T_SIN, T_COS, T_TAN, T_ATN, T_EXP, T_LOG, T_ABS,
T_SAVE, T_LOAD, T_DIR, T_DEL, T_AND, T_OR, T_NOT, T_SIN, T_COS, T_TAN, T_ATN, T_EXP, T_LOG, T_ABS,
T_SQR, T_INT, T_RND, T_SGN, T_FN, T_TAB, T_PEEK, T_INP, T_LEN, T_VAL, T_ASC,
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_LAST
};
@@ -126,7 +199,7 @@ static const char *const kw[] = {
"TO", "STEP", "NEXT", "DIM", "DEF", "END", "STOP", "REM", "READ", "DATA",
"RESTORE", "ON", "RANDOMIZE", "POKE", "OUT", "RUN", "LIST", "NEW", "SCRATCH",
"BYE", "CLS", "COLOR", "PLOT", "LINE", "RECT", "FILL", "CIRCLE", "LOCATE", "INK",
"AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS",
"SAVE", "LOAD", "DIR", "DEL", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS",
"SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC",
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "TIM", "POINT", "<=", ">=", "<>"
};
@@ -193,14 +266,16 @@ static void put_u16(u16 v)
/* ----------------------------------------------------------------- errors */
enum {
E_SYNTAX, E_LINE, E_RETURN, E_NEXT, E_DATA, E_SUBSCRIPT, E_DIV0, E_MEMORY,
E_TYPE, E_STRING, E_FUNC, E_UNDEF_FN, E_FOR, E_GOSUB, E_BREAK, E_STOP
E_TYPE, E_STRING, E_FUNC, E_UNDEF_FN, E_FOR, E_GOSUB, E_NOFILE, E_DISKFULL,
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_BREAK, E_STOP
};
static const char *const errmsg[] = {
"SYNTAX ERROR", "UNDEFINED LINE NUMBER", "RETURN WITHOUT GOSUB",
"NEXT WITHOUT FOR", "OUT OF DATA", "SUBSCRIPT OUT OF RANGE", "DIVISION BY ZERO",
"OUT OF MEMORY", "TYPE MISMATCH", "STRING TOO LONG", "ILLEGAL FUNCTION CALL",
"UNDEFINED FUNCTION", "FOR NESTED TOO DEEPLY", "GOSUB NESTED TOO DEEPLY",
"BREAK", "STOP"
"FILE NOT FOUND", "DISK FULL", "TOO MANY FILES", "BAD FILE NAME", "FLASH ERROR",
"PROGRAM TOO BIG TO SAVE", "BREAK", "STOP"
};
static u16 line_no(u8 *ln) { return ln[1] | (u16)ln[2] << 8; }
@@ -353,15 +428,27 @@ static void tokenize(const char *s, u8 *out)
*out = 0;
}
/* Write a program line as text, keywords spelled out, without a line end. */
static void list_to(u8 *ln, void (*out)(char))
{
char b[6], *q = b + 5;
const char *k;
u8 *p = ln + 3;
u16 v = line_no(ln);
*q = 0;
do { *--q = '0' + v % 10; v /= 10; } while (v);
while (*q) out(*q++);
out(' ');
for (; *p; p++) {
if (*p >= T_LET && *p < T_LAST)
for (k = kw[*p - T_LET]; *k; k++) out(*k);
else out(*p);
}
}
static void list_line(u8 *ln)
{
u8 *p = ln + 3;
put_u16(line_no(ln));
putch(' ');
for (; *p; p++) {
if (*p >= T_LET && *p < T_LAST) puts_(kw[*p - T_LET]);
else putch(*p);
}
list_to(ln, putch);
newline();
}
@@ -1287,6 +1374,283 @@ static void graphics(u8 t)
}
}
/* ---------------------------------------------------------- file system
Programs are kept as plain text in the configuration flash from 2.25 MB to
the end (448 blocks of 4 KB). Blocks 0 and 1 hold the directory, written
alternately with a rising sequence number and a checksum, so a power cut
during SAVE or DEL leaves the previous directory intact. A file is saved
into free blocks before the directory names it. */
#define FS_BASE 0x240000UL
#define FS_BLOCKS 448
#define MAXFILES 64
#define FBLK 8 /* blocks per file: 32 KB of text */
struct dirent { char name[8]; u16 len; u16 blk[FBLK]; };
static struct {
char magic[4];
u16 seq, next;
struct dirent e[MAXFILES];
u16 sum;
} dir;
static u8 dir_cur; /* block holding the current directory */
static u8 bmap[FS_BLOCKS / 8]; /* blocks in use */
static u8 page[256];
static u16 w_pos;
static u16 w_blk[FBLK];
static u32 blk_addr(u16 b) { return FS_BASE + ((u32)b << 12); }
static u8 nblk(u16 len) { return (len + 4095) >> 12; }
static u16 dir_sum(void)
{
u8 *p = (u8 *)&dir;
u16 n = sizeof dir - 2, s = 0x5AA5;
while (n--) s = (s << 1 | s >> 15) + *p++;
return s;
}
static void fl_wait(void)
{
i32 t = millis();
while (fl_busy())
if (millis() - t > 3000) error(E_FLASH);
}
static void fl_erase(u16 b)
{
if (!fl_write_op(0x20, blk_addr(b), 0, 0)) error(E_FLASH);
fl_wait();
}
/* program up to 256 bytes within one flash page, then check them */
static void fl_prog(u32 a, const u8 *p, u16 n)
{
u8 chk[32];
u16 i, k;
if (!fl_write_op(0x02, a, p, n)) error(E_FLASH);
fl_wait();
for (i = 0; i < n; i += k) {
k = n - i < 32 ? n - i : 32;
fl_read(a + i, chk, k);
if (memcmp(chk, p + i, k)) error(E_FLASH);
}
}
static u8 load_dir(u8 b)
{
fl_read(blk_addr(b), (u8 *)&dir, sizeof dir);
return !memcmp(dir.magic, "BFS1", 4) && dir.sum == dir_sum();
}
/* Read the newest valid directory, or start an empty one. */
static void fs_mount(void)
{
u8 va, vb;
u16 sa;
if (!fl_present()) error(E_FLASH);
va = load_dir(0);
sa = dir.seq;
vb = load_dir(1);
if (va && (!vb || (i16)(sa - dir.seq) > 0)) { load_dir(0); dir_cur = 0; }
else if (vb) dir_cur = 1;
else {
memset(&dir, 0, sizeof dir);
memcpy(dir.magic, "BFS1", 4);
dir.next = 2;
dir_cur = 1; /* the first directory goes in block 0 */
}
}
static void fs_commit(void)
{
u8 b = dir_cur ^ 1, *p = (u8 *)&dir;
u16 i, n;
dir.seq++;
dir.sum = dir_sum();
fl_erase(b);
for (i = 0; i < sizeof dir; i += 256) {
n = sizeof dir - i < 256 ? sizeof dir - i : 256;
fl_prog(blk_addr(b) + i, p + i, n);
}
dir_cur = b;
}
static void build_bmap(void)
{
u8 i, j, n;
memset(bmap, 0, sizeof bmap);
bmap[0] = 3; /* the two directory blocks */
for (i = 0; i < MAXFILES; i++)
if (dir.e[i].name[0])
for (j = 0, n = nblk(dir.e[i].len); j < n; j++)
bmap[dir.e[i].blk[j] >> 3] |= 1 << (dir.e[i].blk[j] & 7);
}
/* next free block after the last one handed out, spreading the wear */
static u16 alloc_blk(void)
{
u16 b = dir.next, k;
for (k = 0; k < FS_BLOCKS; k++, b++) {
if (b >= FS_BLOCKS) b = 2;
if (!(bmap[b >> 3] & (1 << (b & 7)))) {
bmap[b >> 3] |= 1 << (b & 7);
dir.next = b + 1;
return b;
}
}
error(E_DISKFULL);
return 0;
}
static void fs_putc(char c)
{
if (!(w_pos & 4095)) {
u8 k = w_pos >> 12;
if (k >= FBLK) error(E_TOOBIG);
w_blk[k] = alloc_blk();
fl_erase(w_blk[k]);
}
page[w_pos & 255] = c;
w_pos++;
if (!(w_pos & 255))
fl_prog(blk_addr(w_blk[(w_pos - 1) >> 12]) + ((w_pos - 256) & 4095), page, 256);
}
static void fs_flush(void)
{
u16 n = w_pos & 255;
if (n) fl_prog(blk_addr(w_blk[(w_pos - 1) >> 12]) + ((w_pos - n) & 4095), page, n);
}
/* File name: 1-8 letters and digits, from any string expression. */
static void get_name(char *nm)
{
char s[STRMAX];
u8 i, c;
sexpr(s);
memset(nm, 0, 8);
for (i = 0; s[i]; i++) {
c = s[i];
if (c >= 'a' && c <= 'z') c -= 32;
if (i >= 8 || !(is_alpha(c) || is_digit(c))) error(E_NAME);
nm[i] = c;
}
if (!i) error(E_NAME);
}
static i16 find_file(const char *nm)
{
u8 i;
for (i = 0; i < MAXFILES; i++)
if (!memcmp(dir.e[i].name, nm, 8)) return i;
return -1;
}
static void put_name(const char *nm)
{
u8 i;
for (i = 0; i < 8; i++) putch(nm[i] ? nm[i] : ' ');
}
static void st_save(void)
{
char nm[8];
i16 i;
u8 *p;
get_name(nm);
fs_mount();
build_bmap();
i = find_file(nm);
if (i < 0) {
for (i = 0; i < MAXFILES && dir.e[i].name[0]; i++);
if (i == MAXFILES) error(E_DIRFULL);
}
w_pos = 0;
for (p = arena; *p; p += *p) {
list_to(p, fs_putc);
fs_putc('\n');
}
fs_flush();
memcpy(dir.e[i].name, nm, 8);
dir.e[i].len = w_pos;
memcpy(dir.e[i].blk, w_blk, sizeof w_blk);
fs_commit();
}
/* Store a typed or loaded line "<number> <text>"; ignores lines without a number. */
static void enter_line(char *s)
{
u16 n = 0;
while (*s == ' ') s++;
if (!is_digit(*s)) return;
while (is_digit(*s)) n = n * 10 + (*s++ - '0');
while (*s == ' ') s++;
tokenize(s, tokbuf);
store_line(n, tokbuf);
}
static void fs_load(void)
{
char nm[8];
struct dirent e;
i16 i;
u16 pos;
u8 n = 0, c;
get_name(nm);
fs_mount();
i = find_file(nm);
if (i < 0) error(E_NOFILE);
e = dir.e[i];
new_prog();
for (pos = 0; pos < e.len; pos++) {
if (!(pos & 255))
fl_read(blk_addr(e.blk[pos >> 12]) + (pos & 4095), page, 256);
c = page[pos & 255];
if (c == '\n') {
linebuf[n] = 0;
enter_line(linebuf);
n = 0;
} else if (n < 250)
linebuf[n++] = c;
}
linebuf[n] = 0;
enter_line(linebuf);
}
static void st_dir(void)
{
u8 i, n = 0;
u16 used = 2;
fs_mount();
for (i = 0; i < MAXFILES; i++) {
if (!dir.e[i].name[0]) continue;
put_name(dir.e[i].name);
do putch(' '); while (col < 10);
put_u16(dir.e[i].len);
newline();
used += nblk(dir.e[i].len);
n++;
check_break();
}
put_u16(n);
puts_(n == 1 ? " FILE, " : " FILES, ");
put_u16((FS_BLOCKS - used) * 4);
puts_("K FREE");
newline();
}
static void st_del(void)
{
char nm[8];
i16 i;
get_name(nm);
fs_mount();
i = find_file(nm);
if (i < 0) error(E_NOFILE);
memset(&dir.e[i], 0, sizeof dir.e[i]);
fs_commit();
}
static void statement(void);
static void st_if(void)
@@ -1357,7 +1721,15 @@ static void statement(void)
io_out(p, (u8)to_int(expr()));
break;
}
case T_LOAD:
fs_load();
running = 0; curln = 0; tp = (u8 *)"";
break;
case T_SAVE: st_save(); break;
case T_DIR: st_dir(); break;
case T_DEL: st_del(); break;
case T_RUN:
if (is_str_start()) fs_load();
run_prog();
running = 1;
if (is_digit(peekc())) goto_line(get_lineno());
+6018 -6018
View File
File diff suppressed because it is too large. Load diff
+10
View File
@@ -86,6 +86,16 @@ set_property -dict { PACKAGE_PIN B17 IOSTANDARD LVCMOS33 PULLUP true } [get_por
## Asynchronous / human-speed I/O
set_false_path -from [get_ports {btnC btnU btnD sw[*] RsRx PS2Clk PS2Data}]
# Configuration flash, used by the Z-80 for files (its clock goes through STARTUPE2)
set_property -dict { PACKAGE_PIN K19 IOSTANDARD LVCMOS33 } [get_ports QspiCSn]
set_property -dict { PACKAGE_PIN D18 IOSTANDARD LVCMOS33 } [get_ports {QspiDB[0]}]
set_property -dict { PACKAGE_PIN D19 IOSTANDARD LVCMOS33 } [get_ports {QspiDB[1]}]
set_property -dict { PACKAGE_PIN G18 IOSTANDARD LVCMOS33 } [get_ports {QspiDB[2]}]
set_property -dict { PACKAGE_PIN F18 IOSTANDARD LVCMOS33 } [get_ports {QspiDB[3]}]
# the SPI clock is slow (clk/4) and sampled mid-bit, so the pins need no timing
set_false_path -to [get_ports {QspiCSn QspiDB[*]}]
set_false_path -from [get_ports {QspiDB[*]}]
# The Z-80 clock is only crossed through synchronisers and toggle handshakes.
set_clock_groups -asynchronous -group [get_clocks sys_clk_pin] \
-group [get_clocks -of_objects [get_pins cpu_mmcm/CLKOUT0]]
+102 -9
View File
@@ -11,7 +11,7 @@ and keyboard belong to:
| Switch | Down | Up |
|---|---|---|
| SW15 | Terminal for the PC's serial port | Console of the Z-80 |
| SW14 | — | Also pass text from the PC's serial port to the Z-80 (for loading programs) |
| SW14 | — | Link the PC's serial port to the Z-80 as well: what the PC sends is typed in, and what BASIC prints is also sent to the PC |
Flip **SW15 up**. The first time, BASIC greets you:
@@ -66,10 +66,10 @@ case, except inside quotes.
| `LIST 100` | List line 100 |
| `LIST 100-200` | List lines 100 to 200 (`LIST -200` and `LIST 100-` work too) |
| `NEW` or `SCRATCH` | Erase the program and all variables |
There is no `SAVE` or `LOAD`: the board has no storage for programs. Keep them
as text files on the PC and send them in (section 10). `LIST` shows the program
on the screen, so you can copy it from a PC terminal.
| `SAVE "NAME"` | Keep the program in the board's flash (section 10) |
| `LOAD "NAME"` | Bring a saved program back |
| `RUN "NAME"` | Load a saved program and run it |
| `DIR` / `DEL "NAME"` | List the saved programs / delete one |
## 2. Program lines
@@ -482,6 +482,8 @@ BASIC's own data. Poke with care.
| 48, 49, 50 | — | graphics X (low byte, high bit), Y |
| 51 | colour at X, Y | plot a pixel at X, Y and move right |
| 52 | bit 0: screen fill in progress | fill the whole graphics layer with a colour |
| 64 | bit 0: flash byte in progress; bit 1: last flash command refused | 1 selects the flash and starts a command, 0 ends it |
| 65 | the byte the flash sent back during the last `OUT 65` | a byte to the flash |
```
10 FOR I = 0 TO 255
@@ -514,7 +516,91 @@ Constants in a program are converted from text every time they are used, so a
loop runs a little faster if a constant used inside it is put into a variable
first.
## 10. Loading programs from a PC
## 10. Saving programs
### In the board's flash
The board's configuration flash has room for programs next to the bitstream it
boots from. They stay there when the power is off.
| Command | Does |
|---|---|
| `SAVE "NAME"` | Write the program to flash, replacing any saved program with that name |
| `LOAD "NAME"` | Erase the program in memory and read the saved one in its place |
| `RUN "NAME"` | `LOAD` it, then run it |
| `DIR` | List the saved programs with their sizes in bytes, and the free space |
| `DEL "NAME"` | Delete a saved program |
```
SAVE "SPIRO"
DIR
SPIRO 212
1 FILE, 1780K FREE
```
- Names are 1 to 8 letters and digits; lower case becomes upper case. The name
can be any string expression, so `SAVE N$` works.
- Up to 64 programs, 1,784 KB in all. A program is saved as its listing, in 4 KB
blocks; one can use at most 8 blocks (32 KB of listing).
- Variables aren't saved, and `LOAD` clears them.
- Each block is read back and checked after it is written.
- If the power goes off while saving, you keep the old version of that program:
the new copy is written to free space first and the list of programs is
switched over to it last.
The flash also holds the bitstream the board starts from. The hardware refuses
to erase or write anything below the area kept for programs, so no program can
stop the board from starting, even one that sends commands to the flash itself
with `OUT` (ports 64 and 65, section 9).
## 11. Programs on the PC
Programs can also be kept as plain text files on the PC, one numbered line per
line. SW14 links the PC's serial port to the Z-80: what the PC sends is typed
into BASIC, and what BASIC prints is also sent back to the PC. The tools need:
1. **SW15** and **SW14** up.
2. Nothing else using the serial port. A login getty on it is worse than in the
way: it takes BASIC's output for login names and its "Login incorrect"
replies are typed back into BASIC, round and round. Keep it off until the
next reboot with:
```
sudo systemctl mask --runtime serial-getty@ttyUSB1
sudo systemctl stop serial-getty@ttyUSB1
```
If the port is then only open to root (`ls -l /dev/ttyUSB1`), the getty left
it that way; `sudo chmod 666 /dev/ttyUSB1` opens it again.
3. The baud rate set by SW1:0 (SW0 up is 9600).
**Sending a program to the board:**
```
tools/send-bas.py basic/examples/graphics-demo.bas --baud 9600 --run
```
This sends `NEW`, then the program, then `RUN`. Leave out `--run` to only load
it, and add `--keep` to merge it into the program already there. Pasting into a
terminal program such as `picocom` works too.
**Copying the program in memory to the PC:**
```
tools/get-bas.py myprog.bas --baud 9600
```
**Running a command and seeing the answer on the PC:**
```
tools/get-bas.py --baud 9600 --cmd 'DIR' --cmd 'LOAD "SPIRO"' --cmd 'LIST'
```
`--cmd` can be repeated; each one waits for `READY` (up to `--timeout`
seconds, 30 by default). Program lines typed this way get no `READY`, so they
take the full timeout each; use `send-bas.py` for those.
When you're done, flip SW14 back down, and bring the getty back with
`sudo systemctl unmask --runtime serial-getty@ttyUSB1` (a reboot does it too).
Don't do that with SW14 up.
Keep programs as plain text files with one numbered line per line. To type one
into the board:
@@ -536,7 +622,7 @@ into the board:
Pasting into a terminal program such as `picocom` works too.
## 11. Error messages
## 12. Error messages
An error stops the program and reports the line, for example
`?DIVISION BY ZERO IN 120`.
@@ -557,10 +643,16 @@ An error stops the program and reports the line, for example
| `UNDEFINED FUNCTION` | `FNx` used before its `DEF` |
| `FOR NESTED TOO DEEPLY` | More than 16 loops open |
| `GOSUB NESTED TOO DEEPLY` | More than 32 subroutines in progress |
| `FILE NOT FOUND` | `LOAD`, `RUN` or `DEL` of a name not in `DIR` |
| `BAD FILE NAME` | A name that is empty, longer than 8 or not just letters and digits |
| `DISK FULL` | Not enough free flash for the program |
| `TOO MANY FILES` | 64 programs are saved already |
| `PROGRAM TOO BIG TO SAVE` | The listing is over 32 KB |
| `FLASH ERROR` | The flash didn't answer, or read back wrong after writing |
| `BREAK IN n` | You pressed Ctrl-C |
| `STOP IN n` | The program ran `STOP` |
## 12. Example programs
## 13. Example programs
### Times table
@@ -604,7 +696,7 @@ An error stops the program and reports the line, for example
bars, circles, a burst of lines, sine and cosine curves, random rectangles, a
bouncing ball and a Mandelbrot set, then prints how long it all took.
## 13. Limits at a glance
## 14. Limits at a glance
| Item | Limit |
|---|---|
@@ -618,3 +710,4 @@ bouncing ball and a Mandelbrot set, then prints how long it all took.
| FOR nesting / GOSUB nesting | 16 / 32 |
| Graphics | 320 × 240, 16 colours |
| Text | 80 × 30 |
| Saved programs | 64, 1,784 KB in all, 32 KB of listing each |
Binary file not shown.
+43 -4
View File
@@ -13,7 +13,8 @@
// SW7 Enter sends CR LF instead of CR
// SW8 smooth scrolling (also turned on by ESC [ ? 4 h)
// SW9 fast smooth scrolling
// SW14 in Z-80 mode, bytes from the PC's UART also go to the Z-80 (paste programs)
// SW14 in Z-80 mode, link the PC's UART too: bytes from the PC also go to the
// Z-80, and the Z-80's output is copied to the PC
// SW15 Z-80 mode
// BTNC reset BTNU clear screen BTND reset the Z-80 only
// LED7:0 last byte received LED11:8 VT220 LEDs L4..L1 (DECLL)
@@ -49,7 +50,9 @@ module basys3_terminal #(
input RsRx,
output RsTx,
input PS2Clk,
input PS2Data
input PS2Data,
output QspiCSn,
inout [3:0] QspiDB
);
localparam [7:0] XON = 8'h11, XOFF = 8'h13;
@@ -156,6 +159,19 @@ module basys3_terminal #(
.rd(zin_rd), .dout(zin), .empty(zin_empty), .full(zin_full), .count(zin_count)
);
// Z-80 output copied to the PC when linked
wire [7:0] mq;
wire mq_empty;
wire [10:0] mq_count;
reg mq_rd;
wire z80_out; // a Z-80 byte is going to the screen
wire [7:0] z80_out_byte;
fifo #(.W(8), .A(10)) mirror_fifo (
.clk(clk), .rst(rst), .din(z80_out_byte), .wr(z80_out && z80_link),
.rd(mq_rd), .dout(mq), .empty(mq_empty), .full(), .count(mq_count)
);
wire [10:0] tq_count;
wire [10:0] flow_count = z80_mode ? zin_count : tq_count;
reg xoff_sent;
@@ -164,6 +180,7 @@ module basys3_terminal #(
tx_start <= 1'b0;
kq_rd <= 1'b0;
rq_rd <= 1'b0;
mq_rd <= 1'b0;
if (rst) begin
from_resp <= 1'b0;
flow_pend <= 1'b0;
@@ -191,6 +208,10 @@ module basys3_terminal #(
tx_start <= 1'b1;
kq_rd <= !from_resp;
rq_rd <= from_resp;
end else if (z80_mode && !mq_empty && !mq_rd) begin
tx_byte <= mq;
tx_start <= 1'b1;
mq_rd <= 1'b1;
end
end
end
@@ -268,6 +289,7 @@ module basys3_terminal #(
always @(posedge clk) ztx_req_s <= {ztx_req_s[0], ztx_req};
wire [15:0] z80_seg;
wire fl_sck;
wire [16:0] gfx_addr;
wire [3:0] gfx_pix;
@@ -276,9 +298,22 @@ module basys3_terminal #(
.rx_req(zrx_req), .rx_data(zrx_data), .rx_ack(zrx_ack),
.tx_req(ztx_req), .tx_data(ztx_data), .tx_ack(ztx_ack),
.seg_val(z80_seg), .halted(),
.vclk(clk), .gfx_vaddr(gfx_addr), .gfx_vpix(gfx_pix)
.vclk(clk), .gfx_vaddr(gfx_addr), .gfx_vpix(gfx_pix),
.fl_cs_n(QspiCSn), .fl_sck(fl_sck), .fl_mosi(QspiDB[0]), .fl_miso(QspiDB[1])
);
// The flash clock is the configuration clock pin, reached through STARTUPE2.
// DQ2/DQ3 (write protect, hold) stay high.
assign QspiDB[1] = 1'bz;
assign QspiDB[3:2] = 2'b11;
`ifndef SIMULATION
STARTUPE2 #(.PROG_USR("FALSE"), .SIM_CCLK_FREQ(0.0)) startup (
.CFGCLK(), .CFGMCLK(), .EOS(), .PREQ(),
.CLK(1'b0), .GSR(1'b0), .GTS(1'b0), .KEYCLEARB(1'b1), .PACK(1'b0),
.USRCCLKO(fl_sck), .USRCCLKTS(1'b0), .USRDONEO(1'b1), .USRDONETS(1'b1)
);
`endif
// terminal input: Z-80 output or received bytes, local echo, banner
reg echo_pend;
reg [7:0] echo_byte;
@@ -286,6 +321,10 @@ module basys3_terminal #(
reg tin_wr;
wire tin_full;
assign z80_out = z80_mode && ztx_req_s[1] != ztx_ack && !tin_wr && tq_count < 1000 &&
(!z80_link || mq_count < 1000);
assign z80_out_byte = ztx_data;
always @(posedge clk) begin
tin_wr <= 1'b0;
if (kq_rd && sw_r[2] && !z80_mode) begin
@@ -296,7 +335,7 @@ module basys3_terminal #(
echo_pend <= 1'b0;
ban_i <= z80_mode ? 8'hFF : 8'd199;
end else if (z80_mode) begin
if (ztx_req_s[1] != ztx_ack && !tin_wr && tq_count < 1000) begin
if (z80_out) begin
tin <= ztx_data;
tin_wr <= 1'b1;
ztx_ack <= ~ztx_ack;
+100
View File
@@ -0,0 +1,100 @@
`timescale 1ns / 1ps
// SPI port to the configuration flash for the Z-80, with write protection for
// the bitstream.
//
// port 40h out: bit 0 = 1 opens a command, 0 ends it (chip select high)
// in: bit 0 = byte in progress, bit 1 = command refused
// port 41h out: send a byte (the reply byte is read back from 41h)
//
// The first byte of a command is checked before the chip is selected. Only
// read (03), read status (05), write enable/disable (06/04), read ID (9F), page
// program (02) and 4 KB sector erase (20) are allowed. Program and erase are
// abandoned after the opcode, before any address byte reaches the flash,
// unless the address is at or above PROTECT (a 64 KB boundary), so the
// bitstream below it can never be changed by the Z-80.
//
// SCK is clk/4, SPI mode 0.
module flash_spi #(
parameter [7:0] PROTECT_HI = 8'h24 // first writable address = PROTECT_HI << 16
) (
input clk,
input rst,
input wr_ctl, // port 40h written
input wr_dat, // port 41h written
input [7:0] wdata,
output [7:0] ctl_q, // port 40h read value
output [7:0] dat_q, // port 41h read value
output reg cs_n,
output reg sck,
output mosi,
input miso
);
reg [7:0] sh;
reg [3:0] nbits;
reg [1:0] ph;
reg busy, rbit;
reg open_, refused, first, guarded;
reg [1:0] nbytes;
assign mosi = sh[7];
assign ctl_q = {6'd0, refused, busy};
assign dat_q = sh;
(* IOB = "TRUE" *) reg miso_r;
always @(posedge clk) miso_r <= miso;
task start(input [7:0] b, input [3:0] n);
begin sh <= b; nbits <= n; ph <= 2'd0; busy <= 1'b1; end
endtask
always @(posedge clk)
if (rst) begin
cs_n <= 1'b1; sck <= 1'b0; open_ <= 1'b0; refused <= 1'b0;
start(8'hFF, 4'd8); // a few clocks so STARTUPE2 hands over CCLK
end else begin
if (busy) begin
ph <= ph + 1'b1;
case (ph)
2'd1: sck <= 1'b1;
2'd2: rbit <= miso_r;
2'd3: begin
sck <= 1'b0;
sh <= {sh[6:0], rbit};
nbits <= nbits - 1'b1;
if (nbits == 4'd1) busy <= 1'b0;
end
default: ;
endcase
end
if (wr_ctl && !busy) begin
open_ <= wdata[0];
first <= 1'b1;
nbytes <= 2'd0;
refused <= 1'b0;
if (!wdata[0]) cs_n <= 1'b1;
end else if (wr_dat && !busy && open_) begin
if (nbytes != 2'd3) nbytes <= nbytes + 1'b1;
if (refused)
sh <= 8'hFF;
else if (first) begin
first <= 1'b0;
guarded <= wdata == 8'h02 || wdata == 8'h20;
if (wdata == 8'h03 || wdata == 8'h05 || wdata == 8'h06 || wdata == 8'h04 ||
wdata == 8'h9F || wdata == 8'h02 || wdata == 8'h20) begin
cs_n <= 1'b0;
start(wdata, 4'd8);
end else begin
refused <= 1'b1;
sh <= 8'hFF;
end
end else if (nbytes == 2'd1 && guarded && wdata < PROTECT_HI) begin
refused <= 1'b1; // incomplete command: the flash ignores it
cs_n <= 1'b1;
sh <= 8'hFF;
end else
start(wdata, 4'd8);
end
end
endmodule
+20 -2
View File
@@ -12,6 +12,7 @@
// 30 out graphics X bits 7:0 31 out X bit 8 32 out Y
// 33 out plot colour at (X,Y), then X+1 in colour at (X,Y)
// 34 out fill the whole graphics screen in bit 0 = fill busy
// 40 SPI flash control, 41 SPI flash data (see flash_spi.v)
//
// Graphics are 320x240 in 16 colours (0 = transparent), shown over the text.
// Writes below ROM_TOP are ignored so a crashed program cannot damage BASIC.
@@ -35,7 +36,12 @@ module z80_system #(
// graphics layer read port, on the video clock
input vclk,
input [16:0] gfx_vaddr,
output reg [3:0] gfx_vpix
output reg [3:0] gfx_vpix,
// configuration flash (SPI)
output fl_cs_n,
output fl_sck,
output fl_mosi,
input fl_miso
);
wire [15:0] ma, io_addr;
wire we, io_rd, io_wr;
@@ -105,6 +111,15 @@ module z80_system #(
end
end
// --------------------------------------------------------------- flash
wire [7:0] fl_ctl_q, fl_dat_q;
flash_spi flash (
.clk(clk), .rst(rst),
.wr_ctl(io_wr && io_addr[7:0] == 8'h40), .wr_dat(io_wr && io_addr[7:0] == 8'h41),
.wdata(io_wd), .ctl_q(fl_ctl_q), .dat_q(fl_dat_q),
.cs_n(fl_cs_n), .sck(fl_sck), .mosi(fl_mosi), .miso(fl_miso)
);
// millisecond timer
localparam MS_DIV = CPU_HZ / 1000;
reg [31:0] ms, ms_latch;
@@ -120,12 +135,14 @@ module z80_system #(
always @* case (io_addr[7:0])
8'h00: io_din = {6'd0, tx_ready, rx_avail};
8'h01: io_din = rx_data;
8'h10: io_din = ms_latch[7:0];
8'h10: io_din = ms[7:0]; // sampled on the same edge that fills ms_latch
8'h11: io_din = ms_latch[15:8];
8'h12: io_din = ms_latch[23:16];
8'h13: io_din = ms_latch[31:24];
8'h33: io_din = {4'd0, gfx_q};
8'h34: io_din = {7'd0, fill_busy};
8'h40: io_din = fl_ctl_q;
8'h41: io_din = fl_dat_q;
default: io_din = 8'hFF;
endcase
@@ -134,6 +151,7 @@ module z80_system #(
rx_ack <= rx_req_s[1];
tx_req <= tx_ack_s[1];
seg_val <= 16'h2080;
ms_latch <= 32'd0;
end else begin
if (io_rd && io_addr[7:0] == 8'h01 && rx_avail) rx_ack <= ~rx_ack;
if (io_rd && io_addr[7:0] == 8'h10) ms_latch <= ms;
+1 -1
View File
@@ -6,7 +6,7 @@ ROOT=$(pwd)
source scripts/vivado_env.sh
mkdir -p sim/work
cd sim/work
xvlog -d SIMULATION -d FONT_FILE="\"$ROOT/font/font.mem\"" -d MEM_FILE="\"$ROOT/basic/basic.mem\"" "$ROOT"/rtl/*.v "$ROOT"/sim/tb_terminal.v
xvlog -d SIMULATION -d FONT_FILE="\"$ROOT/font/font.mem\"" -d MEM_FILE="\"$ROOT/basic/basic.mem\"" "$ROOT"/rtl/*.v "$ROOT"/sim/spiflash_model.v "$ROOT"/sim/tb_terminal.v
xelab -debug off tb_terminal -s tb_terminal
xsim tb_terminal -R
if command -v python3 >/dev/null; then
+82
View File
@@ -0,0 +1,82 @@
`timescale 1ns / 1ps
// Behavioural SPI flash (mode 0) with the commands the Z-80 uses:
// 03 read, 05 status, 06/04 write enable/disable, 9F ID (Macronix MX25L3273F),
// 02 page program, 20 4 KB erase. Reports any program or erase below PROTECT.
module spiflash_model #(
parameter PROTECT = 24'h240000
) (
input cs_n,
input sck,
input mosi,
output reg miso = 1'b1
);
reg [7:0] mem [0:(1 << 22) - 1];
reg [7:0] in_sh, out_sh, cmd;
reg [7:0] pagebuf [0:255];
reg [23:0] addr;
reg [2:0] bitn;
integer nbytes, ndata, i;
reg wel = 1'b0;
realtime busy_until = 0;
integer violations = 0, programs = 0, erases = 0;
initial for (i = 0; i < (1 << 22); i = i + 1) mem[i] = 8'hFF;
always @(negedge cs_n) begin
bitn = 0; nbytes = 0; ndata = 0; out_sh = 8'hFF;
end
always @(posedge sck) if (!cs_n) begin
in_sh = {in_sh[6:0], mosi};
bitn = bitn + 1;
if (bitn == 0) begin // a whole byte
if (nbytes == 0) cmd = in_sh;
else if (nbytes <= 3) addr = {addr[15:0], in_sh};
else if (cmd == 8'h02 && ndata < 256) begin pagebuf[ndata] = in_sh; ndata = ndata + 1; end
nbytes = nbytes + 1;
case (cmd)
8'h03: out_sh = nbytes >= 4 ? mem[addr + nbytes - 4] : 8'hFF;
8'h05: out_sh = {6'd0, wel, $realtime < busy_until};
8'h9F: out_sh = nbytes == 1 ? 8'hC2 : nbytes == 2 ? 8'h20 : 8'h16;
default: out_sh = 8'hFF;
endcase
end
end
always @(negedge sck) if (!cs_n) begin
miso = out_sh[7];
out_sh = {out_sh[6:0], 1'b1};
end
task busy_for(input integer ns);
busy_until = $realtime + ns;
endtask
always @(posedge cs_n) if (bitn == 0) begin
case (cmd)
8'h06: wel = 1'b1;
8'h04: wel = 1'b0;
8'h02: if (wel && nbytes >= 5) begin
if (addr < PROTECT) begin
$display("FLASH VIOLATION: program at %h", addr); violations = violations + 1;
end
for (i = 0; i < ndata; i = i + 1)
mem[{addr[23:8], addr[7:0] + i[7:0]}] = mem[{addr[23:8], addr[7:0] + i[7:0]}] & pagebuf[i];
programs = programs + 1;
wel = 1'b0;
busy_for(3000);
end
8'h20: if (wel && nbytes == 4) begin
if (addr < PROTECT) begin
$display("FLASH VIOLATION: erase at %h", addr); violations = violations + 1;
end
for (i = 0; i < 4096; i = i + 1) mem[{addr[23:12], 12'd0} + i] = 8'hFF;
erases = erases + 1;
wel = 1'b0;
busy_for(20000);
end
default: ;
endcase
end
endmodule
+24 -1
View File
@@ -14,13 +14,18 @@ module tb_terminal;
wire rstx, hs, vs;
wire [3:0] r, g, b;
wire [15:0] led;
wire qcs;
wire [3:0] qdb;
basys3_terminal #(.FONT_FILE(`FONT_FILE), .MEM_FILE(`MEM_FILE)) dut (
.clk(clk), .btnC(btnC), .btnU(btnU), .btnD(btnD), .sw(sw), .led(led), .seg(), .dp(), .an(),
.vgaRed(r), .vgaGreen(g), .vgaBlue(b), .Hsync(hs), .Vsync(vs),
.RsRx(rsrx), .RsTx(rstx), .PS2Clk(ps2c), .PS2Data(ps2d)
.RsRx(rsrx), .RsTx(rstx), .PS2Clk(ps2c), .PS2Data(ps2d),
.QspiCSn(qcs), .QspiDB(qdb)
);
spiflash_model flash (.cs_n(qcs), .sck(dut.fl_sck), .mosi(qdb[0]), .miso(qdb[1]));
localparam BIT_NS = 1_000_000_000 / 115200;
integer errors = 0;
@@ -280,6 +285,24 @@ module tb_terminal;
end
capture_frame("frame_3.ppm");
// ---- files in the flash, and the bitstream protection
uart_str({"CLS:NEW\01510 PRINT \"SAVED\";6*7\015SAVE \"TEST1\"\015NEW\015",
"LOAD \"TEST1\"\015RUN\015DIR\015"});
#20_000_000;
expect_row(13, "SAVED 42");
expect_row(17, "TEST1 21");
expect_row(18, "1 FILE, 1780K FREE");
uart_str("OUT 64,1:OUT 65,6:OUT 64,0:OUT 64,1:OUT 65,32:OUT 65,0:OUT 65,0:OUT 65,0:OUT 64,0\015");
#3_000_000;
if (flash.programs > 0 && flash.erases > 0 && flash.violations == 0)
$display("PASS flash: %0d programs, %0d erases, bitstream untouched",
flash.programs, flash.erases);
else begin
$display("FAIL flash: %0d programs, %0d erases, %0d violations",
flash.programs, flash.erases, flash.violations);
errors = errors + 1;
end
dump_screen;
if (errors == 0) $display("ALL TESTS PASSED");
else $display("%0d TESTS FAILED", errors);
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Copy the program in the Basys 3 Z-80's memory to a file on the PC, or send
BASIC a command and print what it answers.
The board needs SW15 and SW14 up (Z-80 mode, PC serial linked: the Z-80's
output is then copied to the PC), and nothing else may be using the port
(stop the getty first). The baud rate must match SW1:0.
tools/get-bas.py myprog.bas --baud 9600 # LIST into myprog.bas
tools/get-bas.py --cmd 'LOAD "DEMO"' --baud 9600 # run a command, show output
"""
import argparse
import os
import re
import select
import termios
import time
BAUDS = {9600: termios.B9600, 19200: termios.B19200, 57600: termios.B57600,
115200: termios.B115200}
ap = argparse.ArgumentParser()
ap.add_argument("file", nargs="?", help="where to write the listing")
ap.add_argument("--cmd", action="append", help="send this command instead (repeatable)")
ap.add_argument("--port", default="/dev/ttyUSB1")
ap.add_argument("--baud", type=int, default=115200, choices=sorted(BAUDS))
ap.add_argument("--timeout", type=float, default=30, help="seconds to wait for READY")
a = ap.parse_args()
if not a.file and not a.cmd:
ap.error("give a file name or --cmd")
fd = os.open(a.port, os.O_RDWR | os.O_NOCTTY)
t = termios.tcgetattr(fd)
t[0] = termios.IXON
t[1] = 0
t[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
t[3] = 0
t[4] = t[5] = BAUDS[a.baud]
t[6][termios.VMIN] = 0
t[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, t)
termios.tcflush(fd, termios.TCIFLUSH)
def run(cmd):
"""Send one line; return everything BASIC prints up to its next READY."""
os.write(fd, cmd.encode("ascii") + b"\r")
buf = b""
end = time.time() + a.timeout
while time.time() < end:
r, _, _ = select.select([fd], [], [], 0.2)
if r:
buf += os.read(fd, 4096)
if re.search(rb"\r\nREADY\r\n$", buf):
break
text = buf.decode("latin-1").replace("\r", "")
lines = text.split("\n")
if lines and lines[0].strip() == cmd.strip(): # BASIC echoes the command
lines = lines[1:]
return "\n".join(l for l in lines if l != "READY").strip("\n")
if a.cmd:
for c in a.cmd:
print(run(c))
else:
out = run("LIST")
prog = [l for l in out.split("\n") if re.match(r"\d+ ", l)]
with open(a.file, "w") as f:
f.write("\n".join(prog) + "\n")
print("%d lines written to %s" % (len(prog), a.file))
os.close(fd)