BASIC: file dates and data files

DATE "YYYY-MM-DD[ HH:MM[:SS]]" sets a clock kept from the millisecond
counter, DATE prints it and DATE$ returns it. Directory entries now
record each file's creation date (format BFS2; a BFS1 directory is
widened when read), and DIR shows it. send-bas.py and get-bas.py set
the date from the PC when they connect (--no-date to skip).

Data files: OPEN "NAME" FOR INPUT|OUTPUT|APPEND AS #n (n = 1-3),
PRINT #n, INPUT #n, LINE INPUT [#n,], EOF(n), CLOSE [#n]. SAVE and LOAD
now use the same channel code. A written file replaces the old one only
at CLOSE; APPEND shares the old file's full blocks and copies the last
part block. New errors FILE ALREADY OPEN, FILE NOT OPEN, INPUT PAST END;
PROGRAM TOO BIG TO SAVE becomes FILE TOO BIG.

The program area shrinks from 23000 to 22100 bytes to keep the stack
at about 3 KB beside the file buffers. Code now ends at 7EBFh.

The simulation sets the date, checks it in DIR and round-trips a data
file, waiting for expected rows instead of fixed delays. Tested on the
board: dates, write/append/read, EOF, the BFS1 conversion.

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:50:15 -08:00
1 parent 29a15bf7c7
commit 767377f38d
9 files changed
+11631 -11174

No files matched your search

+17 -10
View File
@@ -157,7 +157,10 @@ 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"`.
`DEL "NAME"`; data files with `OPEN "NAME" FOR INPUT|OUTPUT|APPEND AS #n`,
`PRINT #n`, `INPUT #n`, `LINE INPUT #n`, `EOF(n)`, `CLOSE [#n]`.
- **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`
@@ -179,12 +182,12 @@ edit the line being typed.
- **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),
- 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 22 KB of program space is free.
About 21.5 KB of program space is free.
**Graphics:** the layer is 320×240 pixels in the 16 terminal colours, each
pixel a 2×2 block, with (0,0) at the top left. Colour 0 is transparent. Text is
@@ -194,10 +197,12 @@ 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.
**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.
**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
@@ -229,6 +234,7 @@ tools/get-bas.py myprog.bas --baud 9600 # LIST it
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
@@ -348,9 +354,10 @@ older boards, Macronix `mx25l3273f` on newer ones).
- 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.
- 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
BIN
View File
Binary file not shown.
+420 -81
View File
@@ -141,7 +141,8 @@ static u8 peek(u16 a) { return fake_mem[a]; }
static void poke(u16 a, u8 v) { fake_mem[a] = v; }
static u8 io_in(u8 p) { (void)p; return 0xFF; }
static void io_out(u8 p, u8 v) { (void)p; (void)v; }
static void bye(void) { exit(0); }
static void close_all(void);
static void bye(void) { close_all(); exit(0); }
static u8 gmem[240][320];
static u16 hgx;
static u8 hgy;
@@ -183,15 +184,30 @@ static u8 fl_write_op(u8 cmd, u32 a, const u8 *p, u16 n)
}
#endif
/* ---------------------------------------------------------- file channels */
#define FBLK 8 /* blocks per file: 32 KB */
#define NCHAN 4 /* 0 is SAVE and LOAD's, 1-3 are for OPEN */
struct chan {
u8 mode; /* 0 closed, 'I' reading, 'O' writing */
char name[8];
u16 len, pos, pg; /* reading: length, position, page held in buf */
u16 blk[FBLK];
u8 col; /* PRINT # column */
u8 buf[256];
};
static struct chan ch[NCHAN];
static struct chan *chan_arg(u8 mode);
static u8 chan_line(struct chan *c);
/* ----------------------------------------------------------------- tokens */
enum {
T_LET = 0x80, T_PRINT, T_INPUT, T_IF, T_THEN, T_GOTO, T_GOSUB, T_RETURN, T_FOR,
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_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
T_SAVE, T_LOAD, T_DIR, T_DEL, T_DATE, T_OPEN, T_CLOSE, T_OUTPUT, T_APPEND, 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_EOF,
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_DATES, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_LAST
};
static const char *const kw[] = {
@@ -199,13 +215,13 @@ 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",
"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", "<=", ">=", "<>"
"SAVE", "LOAD", "DIR", "DEL", "DATE", "OPEN", "CLOSE", "OUTPUT", "APPEND", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS",
"SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC", "EOF",
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>"
};
/* ----------------------------------------------------------------- memory */
#define ARENA 23000 /* program text grows up, arrays grow down */
#define ARENA 22100 /* program text grows up, arrays grow down */
#define STRMAX 80
#define NVARS (26 * 11)
#define FORMAX 16
@@ -244,12 +260,22 @@ static u8 running;
static u8 jumped; /* tp was moved to another statement */
/* ----------------------------------------------------------------- output */
static u8 out_ch; /* PRINT # channel, 0 = the screen */
static u8 scr_col; /* the screen's column while out_ch is set */
static void file_putc(u8 c);
static void putch(char c)
{
if (c == '\n') { out_c('\r'); out_c('\n'); col = 0; return; }
if (c == '\n') {
col = 0;
if (out_ch) file_putc('\n');
else { out_c('\r'); out_c('\n'); }
return;
}
if (c == '\b') { if (col) col--; }
else if ((u8)c >= ' ') col++;
out_c(c);
if (out_ch) file_putc(c);
else out_c(c);
}
static void puts_(const char *s) { while (*s) putch(*s++); }
@@ -267,7 +293,7 @@ static void put_u16(u16 v)
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_NOFILE, E_DISKFULL,
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_BREAK, E_STOP
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_OPEN, E_NOTOPEN, E_EOF, E_BREAK, E_STOP
};
static const char *const errmsg[] = {
"SYNTAX ERROR", "UNDEFINED LINE NUMBER", "RETURN WITHOUT GOSUB",
@@ -275,13 +301,15 @@ static const char *const errmsg[] = {
"OUT OF MEMORY", "TYPE MISMATCH", "STRING TOO LONG", "ILLEGAL FUNCTION CALL",
"UNDEFINED FUNCTION", "FOR NESTED TOO DEEPLY", "GOSUB NESTED TOO DEEPLY",
"FILE NOT FOUND", "DISK FULL", "TOO MANY FILES", "BAD FILE NAME", "FLASH ERROR",
"PROGRAM TOO BIG TO SAVE", "BREAK", "STOP"
"FILE TOO BIG", "FILE ALREADY OPEN", "FILE NOT OPEN", "INPUT PAST END",
"BREAK", "STOP"
};
static u16 line_no(u8 *ln) { return ln[1] | (u16)ln[2] << 8; }
static void error(u8 e)
{
if (out_ch) { out_ch = 0; col = scr_col; }
if (col) newline();
if (e < E_BREAK) putch('?');
puts_(errmsg[e]);
@@ -290,6 +318,94 @@ static void error(u8 e)
longjmp(errjmp, 1);
}
/* ------------------------------------------------------------------ clock */
/* The date and time, set by DATE (the PC tools set it when they connect) and
kept from the millisecond counter until the power goes off. Held as seconds
since 2000-01-01 00:00; 0 means not set. */
static u32 clk_sec;
static i32 clk_ms; /* millis() at clk_sec */
static u32 now(void)
{
i32 m;
u32 d;
if (!clk_sec) return 0;
m = millis();
d = (u32)(m - clk_ms) / 1000;
clk_sec += d;
clk_ms += (i32)(d * 1000);
return clk_sec;
}
static const u8 mdays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static u8 leap(u16 y) { return !(y & 3) && (y % 100 || !(y % 400)); }
static u8 month_len(u16 y, u8 m) { return mdays[m - 1] + (m == 2 && leap(y)); }
/* "YYYY-MM-DD HH:MM" (or with ":SS" when sec is set) for t; "" when t is 0. */
static void fmt_date(u32 t, char *out, u8 sec)
{
u16 y = 2000, days = t / 86400UL;
u8 m = 1, i;
u32 r = t % 86400UL;
u16 v[6];
if (!t) { *out = 0; return; }
while (days >= 365 + leap(y)) days -= 365 + leap(y++);
while (days >= month_len(y, m)) days -= month_len(y, m++);
v[0] = y; v[1] = m; v[2] = days + 1;
v[3] = r / 3600; v[4] = r / 60 % 60; v[5] = r % 60;
for (i = 0; i < (sec ? 6 : 5); i++) {
if (i == 0) {
*out++ = '0' + y / 1000; *out++ = '0' + y / 100 % 10;
}
*out++ = '0' + v[i] / 10 % 10;
*out++ = '0' + v[i] % 10;
if (i < 2) *out++ = '-';
else if (i == 2) *out++ = ' ';
else if (i < (sec ? 5 : 4)) *out++ = ':';
}
*out = 0;
}
static u16 date_field(const char **p, u8 n, u16 lo, u16 hi)
{
u16 v = 0;
while (n--) {
if (**p < '0' || **p > '9') error(E_FUNC);
v = v * 10 + (*(*p)++ - '0');
}
if (v < lo || v > hi) error(E_FUNC);
return v;
}
/* Set the clock from "YYYY-MM-DD[ HH:MM[:SS]]". */
static void set_date(const char *s)
{
u16 y, m, d, hh = 0, mm = 0, ss = 0, i;
u32 days;
y = date_field(&s, 4, 2000, 2099);
if (*s++ != '-') error(E_FUNC);
m = date_field(&s, 2, 1, 12);
if (*s++ != '-') error(E_FUNC);
d = date_field(&s, 2, 1, month_len(y, m));
if (*s) {
if (*s++ != ' ') error(E_FUNC);
hh = date_field(&s, 2, 0, 23);
if (*s++ != ':') error(E_FUNC);
mm = date_field(&s, 2, 0, 59);
if (*s) {
if (*s++ != ':') error(E_FUNC);
ss = date_field(&s, 2, 0, 59);
}
if (*s) error(E_FUNC);
}
days = d - 1;
for (i = 2000; i < y; i++) days += 365 + leap(i);
for (i = 1; i < m; i++) days += month_len(y, i);
clk_ms = millis();
clk_sec = days * 86400UL + hh * 3600UL + mm * 60 + ss;
if (!clk_sec) clk_sec = 1;
}
/* ---------------------------------------------------------------- numbers */
static const float p10[] = { 1e1f, 1e2f, 1e4f, 1e8f, 1e16f, 1e32f };
static const float m10[] = { 1e-1f, 1e-2f, 1e-4f, 1e-8f, 1e-16f, 1e-32f };
@@ -555,7 +671,8 @@ static u8 var_name(void)
static u8 is_str_start(void)
{
u8 c = peekc();
if (c == '"' || c == T_CHRS || c == T_STRS || c == T_LEFTS || c == T_RIGHTS || c == T_MIDS)
if (c == '"' || c == T_CHRS || c == T_STRS || c == T_LEFTS || c == T_RIGHTS || c == T_MIDS ||
c == T_DATES)
return 1;
return is_alpha(c) && tp[1] == '$';
}
@@ -651,6 +768,11 @@ static float func(u8 t)
g_at(x, y);
return g_get();
}
if (t == T_EOF) {
struct chan *c = chan_arg('I');
expect(')');
return c->pos >= c->len ? -1 : 0;
}
if (t == T_LEN || t == T_VAL || t == T_ASC) {
u8 *p = (u8 *)s;
sexpr(s);
@@ -840,6 +962,7 @@ static void str_prim(char *out)
return;
}
tp++;
if (c == T_DATES) { fmt_date(now(), out, 1); return; }
expect('(');
switch (c) {
case T_CHRS:
@@ -960,7 +1083,24 @@ static void skip_line(void)
while (*tp) tp++;
}
static void print_items(void);
static void st_print(void)
{
struct chan *c;
if (!accept('#')) { print_items(); return; }
c = chan_arg('O');
if (!at_end()) expect(',');
scr_col = col;
col = c->col;
out_ch = c - ch;
print_items();
out_ch = 0;
c->col = col;
col = scr_col;
}
static void print_items(void)
{
char buf[STRMAX + 2];
u8 sep = 0;
@@ -1036,9 +1176,53 @@ static u8 assign_item(u8 **pp)
return 1;
}
/* INPUT #n, items: values separated by commas, over as many lines as needed */
static void input_file(void)
{
struct chan *c = chan_arg('I');
u8 *p;
expect(',');
if (!chan_line(c)) error(E_EOF);
p = (u8 *)linebuf;
for (;;) {
if (!assign_item(&p)) error(E_TYPE);
if (!accept(',')) break;
if (*p == ',') p++;
else if (!*p) {
if (!chan_line(c)) error(E_EOF);
p = (u8 *)linebuf;
}
}
}
/* LINE INPUT [#n,] ["prompt";] A$: a whole line, commas and quotes included */
static void st_line_input(void)
{
u8 v;
if (accept('#')) {
struct chan *c = chan_arg('I');
expect(',');
if (!chan_line(c)) error(E_EOF);
} else {
if (peekc() == '"') {
char prompt[STRMAX];
str_prim(prompt);
puts_(prompt);
if (!accept(';')) expect(',');
}
if (!read_line()) error(E_BREAK);
}
v = peekc();
if (!is_alpha(v) || tp[1] != '$') error(E_TYPE);
tp += 2;
if (strlen(linebuf) >= STRMAX) linebuf[STRMAX - 1] = 0;
strcpy(svars[v - 'A'], linebuf);
}
static void st_input(void)
{
u8 *p;
if (accept('#')) { input_file(); return; }
if (peekc() == '"') {
char prompt[STRMAX];
str_prim(prompt);
@@ -1383,9 +1567,9 @@ static void graphics(u8 t)
#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]; };
struct dirent { char name[8]; u16 len; u16 blk[FBLK]; u16 date[2]; };
#define OLD_DIRENT 26 /* BFS1 entries had no date */
static struct {
char magic[4];
u16 seq, next;
@@ -1394,20 +1578,19 @@ static struct {
} 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)
static u16 sum_of(u16 n)
{
u8 *p = (u8 *)&dir;
u16 n = sizeof dir - 2, s = 0x5AA5;
u16 s = 0x5AA5;
while (n--) s = (s << 1 | s >> 15) + *p++;
return s;
}
static u16 dir_sum(void) { return sum_of(sizeof dir - 2); }
static u32 e_date(u8 i) { return dir.e[i].date[0] | (u32)dir.e[i].date[1] << 16; }
static void fl_wait(void)
{
@@ -1436,10 +1619,20 @@ static void fl_prog(u32 a, const u8 *p, u16 n)
}
}
/* Read directory block b; a BFS1 directory is widened in memory, with no dates. */
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();
u8 *p = (u8 *)&dir, i;
u16 old = 8 + MAXFILES * OLD_DIRENT;
fl_read(blk_addr(b), p, sizeof dir);
if (!memcmp(dir.magic, "BFS2", 4)) return dir.sum == dir_sum();
if (memcmp(dir.magic, "BFS1", 4) || (p[old] | p[old + 1] << 8) != sum_of(old)) return 0;
for (i = MAXFILES; i--; ) {
memmove(&dir.e[i], p + 8 + i * OLD_DIRENT, OLD_DIRENT);
dir.e[i].date[0] = dir.e[i].date[1] = 0;
}
memcpy(dir.magic, "BFS2", 4);
return 1;
}
/* Read the newest valid directory, or start an empty one. */
@@ -1455,7 +1648,7 @@ static void fs_mount(void)
else if (vb) dir_cur = 1;
else {
memset(&dir, 0, sizeof dir);
memcpy(dir.magic, "BFS1", 4);
memcpy(dir.magic, "BFS2", 4);
dir.next = 2;
dir_cur = 1; /* the first directory goes in block 0 */
}
@@ -1484,6 +1677,10 @@ static void build_bmap(void)
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);
for (i = 0; i < NCHAN; i++)
if (ch[i].mode)
for (j = 0, n = nblk(ch[i].mode == 'O' ? ch[i].pos : ch[i].len); j < n; j++)
bmap[ch[i].blk[j] >> 3] |= 1 << (ch[i].blk[j] & 7);
}
/* next free block after the last one handed out, spreading the wear */
@@ -1502,26 +1699,6 @@ static u16 alloc_blk(void)
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)
{
@@ -1552,31 +1729,187 @@ static void put_name(const char *nm)
for (i = 0; i < 8; i++) putch(nm[i] ? nm[i] : ' ');
}
static void st_save(void)
/* ------------------------------------------------------------- channels */
static void chan_putc(struct chan *c, u8 b)
{
if (!(c->pos & 4095)) {
u8 k = c->pos >> 12;
if (k >= FBLK) error(E_TOOBIG);
c->blk[k] = alloc_blk();
fl_erase(c->blk[k]);
}
c->buf[c->pos & 255] = b;
c->pos++;
if (!(c->pos & 255))
fl_prog(blk_addr(c->blk[(c->pos - 1) >> 12]) + ((c->pos - 256) & 4095), c->buf, 256);
}
static void file_putc(u8 b) { chan_putc(&ch[out_ch], b); }
static void save_putc(char b) { chan_putc(&ch[0], b); }
/* next byte of an input channel, -1 at the end */
static int chan_getc(struct chan *c)
{
if (c->pos >= c->len) return -1;
if ((c->pos >> 8) != c->pg) {
c->pg = c->pos >> 8;
fl_read(blk_addr(c->blk[c->pos >> 12]) + (c->pos & 0xF00), c->buf, 256);
}
return c->buf[c->pos++ & 255];
}
/* Read a line into linebuf (up to 250 characters); 0 if already at the end. */
static u8 chan_line(struct chan *c)
{
u8 n = 0;
int b = chan_getc(c);
if (b < 0) return 0;
while (b >= 0 && b != '\n') {
if (n < 250) linebuf[n++] = b;
b = chan_getc(c);
}
linebuf[n] = 0;
return 1;
}
static void chan_open_in(struct chan *c, const char *nm)
{
char nm[8];
i16 i;
u8 *p;
get_name(nm);
fs_mount();
i = find_file(nm);
if (i < 0) error(E_NOFILE);
memcpy(c->name, nm, 8);
c->len = dir.e[i].len;
memcpy(c->blk, dir.e[i].blk, sizeof c->blk);
c->pos = 0;
c->pg = 0xFFFF;
c->mode = 'I';
}
/* Start writing a new copy of file nm; with append, it starts as the old one.
The directory only changes at chan_close, so until then the old file stays. */
static void chan_open_out(struct chan *c, const char *nm, u8 append)
{
i16 i;
u16 j, len;
u8 b;
fs_mount();
build_bmap();
i = find_file(nm);
if (i < 0) {
for (j = 0; j < MAXFILES && dir.e[j].name[0]; j++);
if (j == MAXFILES) error(E_DIRFULL);
}
memcpy(c->name, nm, 8);
c->pos = 0;
c->col = 0;
c->mode = 'O';
if (append && i >= 0) {
struct dirent e = dir.e[i];
len = e.len;
b = len >> 12; /* whole blocks are shared as they are */
memcpy(c->blk, e.blk, b * 2);
c->pos = (u16)b << 12;
for (j = c->pos; j < len; j++) { /* the part block is copied */
u8 v;
fl_read(blk_addr(e.blk[b]) + (j & 4095), &v, 1);
chan_putc(c, v);
}
}
}
static void chan_close(struct chan *c)
{
u16 n;
i16 i;
u8 m = c->mode;
c->mode = 0;
if (m != 'O') return;
n = c->pos & 255;
if (n) fl_prog(blk_addr(c->blk[(c->pos - 1) >> 12]) + ((c->pos - n) & 4095), c->buf, n);
fs_mount();
i = find_file(c->name);
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');
if (!dir.e[i].name[0] || !e_date(i)) { /* keep the creation date */
u32 t = now();
dir.e[i].date[0] = (u16)t;
dir.e[i].date[1] = t >> 16;
}
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);
memcpy(dir.e[i].name, c->name, 8);
dir.e[i].len = c->pos;
memcpy(dir.e[i].blk, c->blk, sizeof c->blk);
fs_commit();
}
static void close_all(void)
{
u8 i;
for (i = 1; i < NCHAN; i++) chan_close(&ch[i]);
}
/* [#]n of an open channel in the given mode */
static struct chan *chan_arg(u8 mode)
{
i16 n;
accept('#');
n = to_int(expr());
if (n < 1 || n >= NCHAN) error(E_FUNC);
if (ch[n].mode != mode) error(E_NOTOPEN);
return &ch[n];
}
/* OPEN "NAME" FOR INPUT|OUTPUT|APPEND AS #n */
static void st_open(void)
{
char nm[8];
u8 m;
i16 n;
get_name(nm);
expect(T_FOR);
m = peekc();
if (m != T_INPUT && m != T_OUTPUT && m != T_APPEND) error(E_SYNTAX);
tp++;
if (peekc() != 'A' || tp[1] != 'S') error(E_SYNTAX);
tp += 2;
accept('#');
n = to_int(expr());
if (n < 1 || n >= NCHAN) error(E_FUNC);
if (ch[n].mode) error(E_OPEN);
if (m == T_INPUT) chan_open_in(&ch[n], nm);
else chan_open_out(&ch[n], nm, m == T_APPEND);
}
/* CLOSE [#n [, #n ...]], or every file */
static void st_close(void)
{
i16 n;
if (at_end()) { close_all(); return; }
do {
accept('#');
n = to_int(expr());
if (n < 1 || n >= NCHAN) error(E_FUNC);
chan_close(&ch[n]);
} while (accept(','));
}
static void st_save(void)
{
char nm[8];
u8 *p;
struct chan *c = &ch[0];
c->mode = 0;
get_name(nm);
chan_open_out(c, nm, 0);
for (p = arena; *p; p += *p) {
list_to(p, save_putc);
save_putc('\n');
}
chan_close(c);
}
/* Store a typed or loaded line "<number> <text>"; ignores lines without a number. */
static void enter_line(char *s)
{
@@ -1592,29 +1925,13 @@ static void enter_line(char *s)
static void fs_load(void)
{
char nm[8];
struct dirent e;
i16 i;
u16 pos;
u8 n = 0, c;
struct chan *c = &ch[0];
c->mode = 0;
get_name(nm);
fs_mount();
i = find_file(nm);
if (i < 0) error(E_NOFILE);
e = dir.e[i];
chan_open_in(c, nm);
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);
while (chan_line(c)) enter_line(linebuf);
c->mode = 0;
}
static void st_dir(void)
@@ -1627,6 +1944,12 @@ static void st_dir(void)
put_name(dir.e[i].name);
do putch(' '); while (col < 10);
put_u16(dir.e[i].len);
if (e_date(i)) {
char d[20];
fmt_date(e_date(i), d, 0);
do putch(' '); while (col < 17);
puts_(d);
}
newline();
used += nblk(dir.e[i].len);
n++;
@@ -1686,7 +2009,7 @@ static void statement(void)
case T_NEXT: st_next(); break;
case T_DIM: st_dim(); break;
case T_DEF: st_def(); break;
case T_END: running = 0; break;
case T_END: close_all(); running = 0; break;
case T_STOP: error(E_STOP); break;
case T_REM: skip_line(); break;
case T_DATA: skip_line(); break;
@@ -1722,13 +2045,25 @@ static void statement(void)
break;
}
case T_LOAD:
close_all();
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_OPEN: st_open(); break;
case T_CLOSE: st_close(); break;
case T_DATE: {
char d[STRMAX];
if (is_str_start()) { sexpr(d); set_date(d); break; }
fmt_date(now(), d, 1);
puts_(*d ? d : "DATE NOT SET");
newline();
break;
}
case T_RUN:
close_all();
if (is_str_start()) fs_load();
run_prog();
running = 1;
@@ -1736,9 +2071,13 @@ static void statement(void)
break;
case T_LIST: st_list(); break;
case T_NEW:
case T_SCRATCH: new_prog(); running = 0; curln = 0; tp = (u8 *)""; break;
case T_SCRATCH: close_all(); new_prog(); running = 0; curln = 0; tp = (u8 *)""; break;
case T_BYE: bye(); break;
case T_CLS: case T_COLOR: case T_PLOT: case T_LINE: case T_RECT:
case T_LINE:
if (accept(T_INPUT)) { st_line_input(); break; }
graphics(t);
break;
case T_CLS: case T_COLOR: case T_PLOT: case T_RECT:
case T_FILL: case T_CIRCLE: case T_LOCATE: case T_INK:
graphics(t);
break;
@@ -1762,7 +2101,7 @@ static void execute(void)
if (peekc()) error(E_SYNTAX);
if (!curln) break; /* end of a direct statement */
curln += *curln;
if (!*curln) break; /* end of program */
if (!*curln) { close_all(); break; } /* end of program */
tp = curln + 3;
}
running = 0;
+11062 -11062
View File
File diff suppressed because it is too large. Load diff
+97 -15
View File
@@ -70,6 +70,7 @@ case, except inside quotes.
| `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 |
| `DATE "2026-11-28 09:30"` | Set the date and time, which `SAVE` records |
## 2. Program lines
@@ -201,6 +202,11 @@ with `?? `. A string can be typed bare or in quotes; quotes are needed if it
contains a comma. Typing something that isn't a number for a numeric variable
gives `?REDO` and asks again. Ctrl-C stops the program.
`LINE INPUT A$` (or `LINE INPUT "PROMPT"; A$`) takes the whole line into one
string, commas and quotes included, and prints no `? `.
`PRINT #`, `INPUT #` and `LINE INPUT #` do the same with a file (section 10).
### IF … THEN — decisions
```
@@ -344,6 +350,8 @@ A whole number from 1 to 6: `1 + INT(RND * 6)`.
| Function | Result |
|---|---|
| `TIM` | Seconds since the Z-80 was reset, to the millisecond |
| `DATE$` | The date and time as `"2026-11-28 09:30:15"`, or `""` if not set (section 10) |
| `EOF(N)` | -1 (true) when file *N* has been read to the end, else 0 (section 10) |
| `POINT(X, Y)` | Colour of the graphics pixel at *X, Y* (0 off screen) |
| `PEEK(A)` | Byte at memory address *A* |
| `INP(P)` | Byte from I/O port *P* |
@@ -464,8 +472,8 @@ stays where it is.
| Addresses | Contents |
|---|---|
| 0000–7FFF | BASIC itself (writes here are ignored) |
| 8000–EBFF | BASIC's variables, your program and arrays |
| EC00–FFFF | The Z-80 stack |
| 8000–F3FF | BASIC's variables, your program and arrays, file buffers |
| F400–FFFF | The Z-80 stack |
`PEEK` can read anything; `POKE` can change anything from 8000 up, including
BASIC's own data. Poke with care.
@@ -516,12 +524,13 @@ 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. Saving programs
## 10. Files in the flash
### In the board's flash
The board's configuration flash has room for files next to the bitstream it
boots from: saved programs, and data files that programs write and read. They
stay there when the power is off.
The board's configuration flash has room for programs next to the bitstream it
boots from. They stay there when the power is off.
### Saving programs
| Command | Does |
|---|---|
@@ -534,19 +543,88 @@ boots from. They stay there when the power is off.
```
SAVE "SPIRO"
DIR
SPIRO 212
SPIRO 212 2026-11-28 09:30
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).
- Up to 64 files, 1,784 KB in all. A program is saved as its listing, in 4 KB
blocks; a file can use at most 8 blocks (32 KB).
- 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
- If the power goes off while saving, you keep the old version of that file:
the new copy is written to free space first and the list of files is
switched over to it last.
- `DIR` lists programs and data files alike; `LOAD` of a data file keeps only
its lines that start with a number.
### The date
`DIR` shows the date and time each file was created. Saving over a file keeps
its original date.
The board has no clock that runs with the power off, so BASIC only knows the
date once it has been told, and keeps time from then until the Z-80 is
restarted (**BTND**, **BTNC**, power-off or reprogramming).
| | |
|---|---|
| `DATE "2026-11-28 09:30"` | Set the date and time (seconds optional: `"2026-11-28 09:30:15"`; the time is optional too) |
| `DATE` | Print the date and time, or `DATE NOT SET` |
| `DATE$` | The date and time as a string, `""` if not set |
`send-bas.py` and `get-bas.py` set it from the PC's clock each time they
connect (section 11; `--no-date` stops them). A file saved before the date is set has no date in
`DIR`, and gets one when it is next saved after the date is set.
```
PRINT "TODAY IS "; LEFT$(DATE$, 10)
```
### Data files
A program can write text to a file and read it back, with up to three files
open at once, numbered 1 to 3.
| Statement | Does |
|---|---|
| `OPEN "NAME" FOR OUTPUT AS #1` | Start a new file (replacing any file of that name when it is closed) |
| `OPEN "NAME" FOR APPEND AS #1` | Add to the end of a file (or start it if there isn't one) |
| `OPEN "NAME" FOR INPUT AS #1` | Read a file from the start |
| `PRINT #1, items` | Write, just as `PRINT` writes to the screen |
| `INPUT #1, A, B$` | Read values separated by commas or line ends |
| `LINE INPUT #1, A$` | Read a whole line |
| `EOF(1)` | -1 once everything has been read |
| `CLOSE #1` | Finish with a file; `CLOSE` alone closes them all |
The `#` is optional everywhere, and the name can be any string expression.
```
10 OPEN "SCORES" FOR OUTPUT AS #1
20 FOR I = 1 TO 5
30 PRINT #1, "PLAYER"; I; ","; I * 100
40 NEXT I
50 CLOSE #1
60 OPEN "SCORES" FOR INPUT AS #1
70 IF EOF(1) THEN CLOSE #1: END
80 INPUT #1, N$, S
90 PRINT N$, S
100 GOTO 70
```
- A file written with `OUTPUT` or `APPEND` only appears, or changes, when it is
closed. Until then `DIR` and other readers see the old version, and a power
cut leaves the old version. `END`, the end of the program, `RUN`, `NEW`,
`LOAD` and `BYE` close every open file; an error or Ctrl-C doesn't, so the
file can still be closed by hand.
- `PRINT #` writes exactly what `PRINT` would show, so numbers have their
spaces, and the separator for `INPUT #` must be written as `","` as above.
A string that contains a comma needs quotes around it for `INPUT #`, or read
it with `LINE INPUT #`.
- `APPEND` copies the file's last part-filled 4 KB block to a new one; the full
blocks are shared with the old version, so appending to a big file is quick.
- Lines are separated by a single line feed (code 10).
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
@@ -639,7 +717,7 @@ An error stops the program and reports the line, for example
| `OUT OF MEMORY` | The program and arrays don't fit |
| `TYPE MISMATCH` | A string where a number belongs, or the other way round |
| `STRING TOO LONG` | A string over 79 characters, or a program line too long to store |
| `ILLEGAL FUNCTION CALL` | A bad argument: `SQR(-1)`, `LOG(0)`, a colour over 15, `AND` on a number beyond ±32767 |
| `ILLEGAL FUNCTION CALL` | A bad argument: `SQR(-1)`, `LOG(0)`, a colour over 15, `AND` on a number beyond ±32767, a file number other than 1–3, an impossible `DATE` |
| `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 |
@@ -647,7 +725,10 @@ An error stops the program and reports the line, for example
| `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 |
| `FILE TOO BIG` | A program listing or data file over 32 KB |
| `FILE ALREADY OPEN` | `OPEN` with a number that is already in use |
| `FILE NOT OPEN` | `PRINT #`, `INPUT #`, `LINE INPUT #` or `EOF` on a number that isn't open that way |
| `INPUT PAST END` | `INPUT #` or `LINE INPUT #` after the last line |
| `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` |
@@ -700,7 +781,7 @@ bouncing ball and a Mandelbrot set, then prints how long it all took.
| Item | Limit |
|---|---|
| Program and arrays together | about 22 KB |
| Program and arrays together | about 21.5 KB |
| Line numbers | 0 – 65535 |
| Line length | 250 characters typed |
| Numeric variables | A–Z and A0–Z9 |
@@ -710,4 +791,5 @@ 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 |
| Files in flash | 64, 1,784 KB in all, 32 KB each |
| Open data files | 3 |
Binary file not shown.
+25 -3
View File
@@ -147,6 +147,24 @@ module tb_terminal;
end
endtask
// wait (up to 100 ms) for a row to read want, then check it
task wait_row(input integer rr, input [8*40-1:0] want);
integer cc, n;
reg [8*40-1:0] got;
realtime t0;
begin
t0 = $realtime;
n = 0;
for (cc = 0; cc < 40; cc = cc + 1) if (want[cc*8 +: 8] != 0) n = cc + 1;
got = 0;
while (got != want && $realtime - t0 < 100_000_000) begin
#100_000;
for (cc = 0; cc < n; cc = cc + 1) got[(n - 1 - cc) * 8 +: 8] = cellraw(rr, cc);
end
expect_row(rr, want);
end
endtask
// capture one frame
reg [11:0] fb [0:640*480-1];
reg cap = 0, smp = 0;
@@ -286,12 +304,12 @@ module tb_terminal;
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",
uart_str({"CLS:DATE \"2026-11-28 09:30\":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");
wait_row(17, "TEST1 21 2026-11-28 09:30");
wait_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)
@@ -303,6 +321,10 @@ module tb_terminal;
errors = errors + 1;
end
// ---- a data file: write it, read it back
uart_str({"CLS:OPEN \"D\" FOR OUTPUT AS 1:PRINT #1,\"XY\";\",\";7:CLOSE\015",
"OPEN \"D\" FOR INPUT AS 1:INPUT #1,A$,B:PRINT A$;B*6;EOF(1):CLOSE\015"});
wait_row(3, "XY 42 -1");
dump_screen;
if (errors == 0) $display("ALL TESTS PASSED");
else $display("%0d TESTS FAILED", errors);
+5 -1
View File
@@ -4,7 +4,8 @@ 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.
(stop the getty first). The baud rate must match SW1:0. BASIC's clock is set
to the PC's first (unless --no-date), so files saved get today's date.
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
@@ -25,6 +26,7 @@ ap.add_argument("--cmd", action="append", help="send this command instead (repea
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")
ap.add_argument("--no-date", action="store_true", help="don't set BASIC's clock")
a = ap.parse_args()
if not a.file and not a.cmd:
ap.error("give a file name or --cmd")
@@ -60,6 +62,8 @@ def run(cmd):
return "\n".join(l for l in lines if l != "READY").strip("\n")
if not a.no_date:
run(time.strftime('DATE "%Y-%m-%d %H:%M:%S"'))
if a.cmd:
for c in a.cmd:
print(run(c))
+5 -2
View File
@@ -3,8 +3,8 @@
The board needs SW15 and SW14 up (Z-80 mode, PC serial linked), and nothing
else may be using the port (stop the getty first). The baud rate must match
SW1:0. Sends NEW first unless --keep is given, then the program, then RUN
if --run is given.
SW1:0. Sets BASIC's clock to the PC's (unless --no-date), sends NEW unless
--keep is given, then the program, then RUN if --run is given.
tools/send-bas.py basic/examples/graphics-demo.bas --baud 9600 --run
"""
@@ -22,6 +22,7 @@ ap.add_argument("--port", default="/dev/ttyUSB1")
ap.add_argument("--baud", type=int, default=115200, choices=sorted(BAUDS))
ap.add_argument("--keep", action="store_true", help="don't send NEW first")
ap.add_argument("--run", action="store_true", help="send RUN at the end")
ap.add_argument("--no-date", action="store_true", help="don't set BASIC's clock")
a = ap.parse_args()
fd = os.open(a.port, os.O_RDWR | os.O_NOCTTY)
@@ -38,6 +39,8 @@ if not a.keep:
lines.insert(0, "NEW")
if a.run:
lines.append("RUN")
if not a.no_date:
lines.insert(0, time.strftime('DATE "%Y-%m-%d %H:%M:%S"'))
for n, line in enumerate(lines, 1):
os.write(fd, line.encode("ascii") + b"\r")
termios.tcdrain(fd)