BASIC graphics: 320x240 16-colour layer, manual and demo
- z80_system: dual-clock graphics RAM behind ports 30h-34h (X/Y, plot with auto-increment, read-back, hardware fill); text_display overlays it under the text, colour 0 transparent. - BASIC: CLS COLOR PLOT LINE RECT FILL CIRCLE POINT, LOCATE and INK; faster keyword tokenizing. - docs/basic-manual.md (+ PDF via docs/build-manual.sh). - basic/examples/graphics-demo.bas and tools/send-bas.py to load programs over the serial port. - Simulation checks drawing and saves a frame; the emulator models the graphics and timer ports and can stop when BASIC waits for input. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
59d5e617f2
commit
dc7c7c22c5
14 files changed
+5205
-4141
No files matched your search
@@ -10,8 +10,10 @@ serial terminal with ANSI colour:
|
||||
- **Serial line**: the micro-USB **PROG/UART** port (the FTDI chip), 8N1. Bytes
|
||||
received there are drawn on the screen. Keystrokes are sent out there.
|
||||
|
||||
It also contains a **Z-80 computer running Dartmouth-style BASIC**. Flip SW15 up
|
||||
and the terminal becomes its console (see [Z-80 BASIC](#z-80-basic)).
|
||||
It also contains a **Z-80 computer running Dartmouth-style BASIC with 320×240
|
||||
colour graphics**. Flip SW15 up and the terminal becomes its console (see
|
||||
[Z-80 BASIC](#z-80-basic) and the full manual,
|
||||
[docs/basic-manual.pdf](docs/basic-manual.pdf)).
|
||||
|
||||
Plug the micro-USB into a PC and open the serial port (`/dev/ttyUSB1` is usually
|
||||
the UART; `ttyUSB0` is JTAG). For example:
|
||||
@@ -162,6 +164,9 @@ edit the line being typed.
|
||||
`STOP`
|
||||
- Data: `DIM`, `DEF FNx(v) = expr`, `READ`/`DATA`/`RESTORE`, `REM`
|
||||
- Machine access: `RANDOMIZE`, `POKE addr,v`, `OUT port,v`
|
||||
- Graphics: `CLS`, `COLOR c`, `PLOT x,y[,c]`, `LINE`, `RECT`, `FILL`
|
||||
(`x1,y1,x2,y2[,c]`), `CIRCLE x,y,r[,c]`
|
||||
- Text placement: `LOCATE row,col`, `INK fg[,bg]`
|
||||
- Several statements can share a line, separated by `:`.
|
||||
- **Variables**:
|
||||
- Numbers: a letter or a letter and digit (`X`, `A1`), single-precision
|
||||
@@ -172,13 +177,34 @@ 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),
|
||||
`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. To paste a program from the PC, flip SW14
|
||||
up too (stop the getty first, or it will talk to BASIC), then paste into
|
||||
`picocom`. The terminal holds the PC back with XON/XOFF while BASIC catches up.
|
||||
About 22 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
|
||||
drawn on top, and the graphics show through blank text.
|
||||
|
||||
**Manual:** [docs/basic-manual.md](docs/basic-manual.md) describes every
|
||||
statement and function, with examples, error messages and limits.
|
||||
`docs/build-manual.sh` rebuilds the PDF from it.
|
||||
|
||||
**Loading programs from the PC:**
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
tools/send-bas.py basic/examples/graphics-demo.bas --baud 9600 --run
|
||||
```
|
||||
|
||||
The terminal holds the PC back with XON/XOFF while BASIC catches up.
|
||||
`basic/examples/graphics-demo.bas` shows off the graphics: colour bars,
|
||||
circles, lines, curves, random shapes, a bouncing ball and a Mandelbrot set.
|
||||
|
||||
### The Z-80
|
||||
|
||||
@@ -198,6 +224,11 @@ up too (stop the getty first, or it will talk to BASIC), then paste into
|
||||
forms, `SLL` and the DDCB register copies, with the undocumented X/Y flags.
|
||||
- There are no interrupts and HALT stops it until reset.
|
||||
|
||||
The 320×240×4-bit graphics layer is a separate dual-clock block RAM: the Z-80
|
||||
writes it on its own clock, and the video reads it on the 100 MHz clock.
|
||||
`rtl/text_display.v` overlays it on the text. A hardware fill clears it in
|
||||
76,800 clocks.
|
||||
|
||||
Memory is 64 KB of block RAM loaded with BASIC at configuration. Writes below
|
||||
8000h are ignored, so the interpreter can't be damaged. BASIC's data and the
|
||||
stack fill the top half.
|
||||
@@ -208,6 +239,9 @@ stack fill the top half.
|
||||
| 01h | key | character to the screen |
|
||||
| 10h–13h | millisecond counter (reading 10h latches the rest) | |
|
||||
| 20h / 21h | | 7-segment display, right / left byte |
|
||||
| 30h, 31h, 32h | | graphics X low byte, X bit 8, Y |
|
||||
| 33h | colour at X,Y | plot at X,Y, then X+1 |
|
||||
| 34h | bit 0: fill busy | fill the whole graphics layer with a colour |
|
||||
|
||||
BASIC is C (`basic/basic.c`) compiled with SDCC (`sudo apt install sdcc`):
|
||||
|
||||
|
||||
Binary file not shown.
+182
-6
@@ -8,6 +8,10 @@
|
||||
* MID$, PEEK/POKE, INP/OUT and TIM. Commands: RUN LIST NEW (SCRATCH) and any
|
||||
* statement typed without a line number runs at once. Ctrl-C stops a program.
|
||||
*
|
||||
* Graphics: 320x240 in 16 colours over the text, origin top left, colour 0
|
||||
* transparent. CLS COLOR PLOT LINE RECT FILL CIRCLE and POINT(x,y); LOCATE and
|
||||
* INK place and colour text.
|
||||
*
|
||||
* Builds with SDCC for the Z-80 (console on I/O ports 0/1) or with a host C
|
||||
* compiler for testing (stdin/stdout).
|
||||
*/
|
||||
@@ -66,6 +70,16 @@ static void io_out(u8 p, u8 v)
|
||||
__endasm;
|
||||
}
|
||||
static void bye(void) { }
|
||||
|
||||
__sfr __at 0x30 gx_lo;
|
||||
__sfr __at 0x31 gx_hi;
|
||||
__sfr __at 0x32 gy_p;
|
||||
__sfr __at 0x33 gpix; /* write plots and moves right; read gives the colour */
|
||||
__sfr __at 0x34 gfill;
|
||||
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); }
|
||||
#else
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -87,6 +101,13 @@ 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 u8 gmem[240][320];
|
||||
static u16 hgx;
|
||||
static u8 hgy;
|
||||
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); }
|
||||
#endif
|
||||
|
||||
/* ----------------------------------------------------------------- tokens */
|
||||
@@ -94,18 +115,20 @@ 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_AND, T_OR, T_NOT, T_SIN, T_COS, T_TAN, T_ATN, T_EXP, T_LOG, T_ABS,
|
||||
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_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_LE, T_GE, T_NE, T_LAST
|
||||
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_LAST
|
||||
};
|
||||
|
||||
static const char *const kw[] = {
|
||||
"LET", "PRINT", "INPUT", "IF", "THEN", "GOTO", "GOSUB", "RETURN", "FOR",
|
||||
"TO", "STEP", "NEXT", "DIM", "DEF", "END", "STOP", "REM", "READ", "DATA",
|
||||
"RESTORE", "ON", "RANDOMIZE", "POKE", "OUT", "RUN", "LIST", "NEW", "SCRATCH",
|
||||
"BYE", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS",
|
||||
"BYE", "CLS", "COLOR", "PLOT", "LINE", "RECT", "FILL", "CIRCLE", "LOCATE", "INK",
|
||||
"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", "<=", ">=", "<>"
|
||||
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "TIM", "POINT", "<=", ">=", "<>"
|
||||
};
|
||||
|
||||
/* ----------------------------------------------------------------- memory */
|
||||
@@ -310,7 +333,8 @@ static void tokenize(const char *s, u8 *out)
|
||||
best = 0; blen = 0;
|
||||
for (i = 0; i < T_LAST - T_LET; i++) {
|
||||
k = kw[i];
|
||||
for (len = 0; k[len]; len++) {
|
||||
if ((u8)k[0] != c) continue;
|
||||
for (len = 1; k[len]; len++) {
|
||||
u8 t = s[len];
|
||||
if (t >= 'a' && t <= 'z') t -= 32;
|
||||
if (t != (u8)k[len]) break;
|
||||
@@ -531,6 +555,15 @@ static float func(u8 t)
|
||||
}
|
||||
if (t == T_TIM) return (float)millis() / 1000.0f;
|
||||
expect('(');
|
||||
if (t == T_POINT) {
|
||||
i16 x = to_int(expr()), y;
|
||||
expect(',');
|
||||
y = to_int(expr());
|
||||
expect(')');
|
||||
if ((u16)x >= 320 || (u16)y >= 240) return 0;
|
||||
g_at(x, y);
|
||||
return g_get();
|
||||
}
|
||||
if (t == T_LEN || t == T_VAL || t == T_ASC) {
|
||||
u8 *p = (u8 *)s;
|
||||
sexpr(s);
|
||||
@@ -598,7 +631,7 @@ static float primary(void)
|
||||
}
|
||||
if (is_str_start()) error(E_TYPE);
|
||||
if (c == T_FN) { tp++; return call_fn(); }
|
||||
if (c >= T_SIN && c <= T_TIM && c != T_FN && c != T_TAB) { tp++; return func(c); }
|
||||
if (c >= T_SIN && c <= T_POINT && c != T_FN && c != T_TAB) { tp++; return func(c); }
|
||||
if (is_alpha(c)) return *num_ref();
|
||||
error(E_SYNTAX);
|
||||
return 0;
|
||||
@@ -1116,6 +1149,144 @@ static void run_prog(void)
|
||||
if (!arena[0]) { curln = 0; tp = (u8 *)""; }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- graphics */
|
||||
static u8 gcolor = 15;
|
||||
|
||||
/* Up to n comma-separated integer arguments; returns how many were given. */
|
||||
static u8 int_args(i16 *a, u8 min, u8 n)
|
||||
{
|
||||
u8 i = 0;
|
||||
do a[i++] = to_int(expr()); while (i < n && accept(','));
|
||||
if (i < min) error(E_SYNTAX);
|
||||
return i;
|
||||
}
|
||||
|
||||
static u8 colour_arg(i16 *a, u8 given, u8 need)
|
||||
{
|
||||
if (given > need) {
|
||||
if ((u16)a[need] > 15) error(E_FUNC);
|
||||
return a[need];
|
||||
}
|
||||
return gcolor;
|
||||
}
|
||||
|
||||
static void hline(i16 x1, i16 x2, i16 y, u8 c)
|
||||
{
|
||||
i16 t;
|
||||
if (x1 > x2) { t = x1; x1 = x2; x2 = t; }
|
||||
if ((u16)y >= 240 || x2 < 0 || x1 > 319) return;
|
||||
if (x1 < 0) x1 = 0;
|
||||
if (x2 > 319) x2 = 319;
|
||||
g_at(x1, y);
|
||||
for (; x1 <= x2; x1++) g_put(c);
|
||||
}
|
||||
|
||||
static void pset(i16 x, i16 y, u8 c)
|
||||
{
|
||||
if ((u16)x < 320 && (u16)y < 240) { g_at(x, y); g_put(c); }
|
||||
}
|
||||
|
||||
static void line(i16 x1, i16 y1, i16 x2, i16 y2, u8 c)
|
||||
{
|
||||
i16 dx = x2 > x1 ? x2 - x1 : x1 - x2, sx = x1 < x2 ? 1 : -1;
|
||||
i16 dy = y2 > y1 ? y1 - y2 : y2 - y1, sy = y1 < y2 ? 1 : -1;
|
||||
i16 err = dx + dy, e2;
|
||||
if (y1 == y2) { hline(x1, x2, y1, c); return; }
|
||||
for (;;) {
|
||||
pset(x1, y1, c);
|
||||
if (x1 == x2 && y1 == y2) return;
|
||||
e2 = 2 * err;
|
||||
if (e2 >= dy) { err += dy; x1 += sx; }
|
||||
if (e2 <= dx) { err += dx; y1 += sy; }
|
||||
}
|
||||
}
|
||||
|
||||
static void circle(i16 cx, i16 cy, i16 r, u8 c)
|
||||
{
|
||||
i16 x = r, y = 0, err = 1 - r;
|
||||
if (r < 0) error(E_FUNC);
|
||||
while (x >= y) {
|
||||
pset(cx + x, cy + y, c); pset(cx - x, cy + y, c);
|
||||
pset(cx + x, cy - y, c); pset(cx - x, cy - y, c);
|
||||
pset(cx + y, cy + x, c); pset(cx - y, cy + x, c);
|
||||
pset(cx + y, cy - x, c); pset(cx - y, cy - x, c);
|
||||
y++;
|
||||
if (err < 0) err += 2 * y + 1;
|
||||
else { x--; err += 2 * (y - x) + 1; }
|
||||
}
|
||||
}
|
||||
|
||||
static void esc_num(u8 n)
|
||||
{
|
||||
if (n >= 100) out_c('0' + n / 100);
|
||||
if (n >= 10) out_c('0' + n / 10 % 10);
|
||||
out_c('0' + n % 10);
|
||||
}
|
||||
|
||||
static void graphics(u8 t)
|
||||
{
|
||||
i16 a[5];
|
||||
u8 n, c;
|
||||
switch (t) {
|
||||
case T_CLS:
|
||||
out_c(27); out_c('['); out_c('2'); out_c('J');
|
||||
out_c(27); out_c('['); out_c('H');
|
||||
col = 0;
|
||||
g_clear(0);
|
||||
break;
|
||||
case T_COLOR:
|
||||
int_args(a, 1, 1);
|
||||
if ((u16)a[0] > 15) error(E_FUNC);
|
||||
gcolor = a[0];
|
||||
break;
|
||||
case T_PLOT:
|
||||
n = int_args(a, 2, 3);
|
||||
pset(a[0], a[1], colour_arg(a, n, 2));
|
||||
break;
|
||||
case T_LINE:
|
||||
n = int_args(a, 4, 5);
|
||||
line(a[0], a[1], a[2], a[3], colour_arg(a, n, 4));
|
||||
break;
|
||||
case T_RECT:
|
||||
n = int_args(a, 4, 5);
|
||||
c = colour_arg(a, n, 4);
|
||||
hline(a[0], a[2], a[1], c);
|
||||
hline(a[0], a[2], a[3], c);
|
||||
line(a[0], a[1], a[0], a[3], c);
|
||||
line(a[2], a[1], a[2], a[3], c);
|
||||
break;
|
||||
case T_FILL: {
|
||||
i16 y, y2;
|
||||
n = int_args(a, 4, 5);
|
||||
c = colour_arg(a, n, 4);
|
||||
y = a[1] < a[3] ? a[1] : a[3];
|
||||
y2 = a[1] < a[3] ? a[3] : a[1];
|
||||
if (y < 0) y = 0;
|
||||
if (y2 > 239) y2 = 239;
|
||||
for (; y <= y2; y++) hline(a[0], a[2], y, c);
|
||||
break;
|
||||
}
|
||||
case T_CIRCLE:
|
||||
n = int_args(a, 3, 4);
|
||||
circle(a[0], a[1], a[2], colour_arg(a, n, 3));
|
||||
break;
|
||||
case T_LOCATE: /* LOCATE row, column (from 1) */
|
||||
int_args(a, 2, 2);
|
||||
if (a[0] < 1 || a[0] > 30 || a[1] < 1 || a[1] > 80) error(E_FUNC);
|
||||
out_c(27); out_c('['); esc_num(a[0]); out_c(';'); esc_num(a[1]); out_c('H');
|
||||
col = a[1] - 1;
|
||||
break;
|
||||
case T_INK: /* INK foreground [, background] */
|
||||
n = int_args(a, 1, 2);
|
||||
if ((u16)a[0] > 15 || (n > 1 && (u16)a[1] > 15)) error(E_FUNC);
|
||||
out_c(27); out_c('[');
|
||||
esc_num(a[0] < 8 ? 30 + a[0] : 82 + a[0]);
|
||||
if (n > 1) { out_c(';'); esc_num(a[1] < 8 ? 40 + a[1] : 92 + a[1]); }
|
||||
out_c('m');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void statement(void);
|
||||
|
||||
static void st_if(void)
|
||||
@@ -1195,6 +1366,10 @@ static void statement(void)
|
||||
case T_NEW:
|
||||
case T_SCRATCH: 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_FILL: case T_CIRCLE: case T_LOCATE: case T_INK:
|
||||
graphics(t);
|
||||
break;
|
||||
default:
|
||||
tp--;
|
||||
st_let();
|
||||
@@ -1230,6 +1405,7 @@ int main(void)
|
||||
u16 n;
|
||||
u8 *p;
|
||||
new_prog();
|
||||
g_clear(0);
|
||||
newline();
|
||||
puts_("DARTMOUTH-STYLE BASIC Z-80 ON A BASYS 3");
|
||||
newline();
|
||||
|
||||
+4123
-4123
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,69 @@
|
||||
10 REM GRAPHICS DEMO FOR THE BASYS 3 Z-80
|
||||
20 REM COLOUR BARS, CIRCLES, LINES, CURVES, SHAPES, ANIMATION, MANDELBROT
|
||||
30 S=TIM
|
||||
100 CLS
|
||||
110 INK 15: LOCATE 3,30: PRINT "BASYS 3 Z-80 GRAPHICS"
|
||||
120 INK 7: LOCATE 5,26: PRINT "320 X 240 PIXELS IN 16 COLOURS"
|
||||
130 FOR C=1 TO 15
|
||||
140 FILL C*20-10,100,C*20+7,180,C
|
||||
150 INK C: LOCATE 25,C*5-1: PRINT C;
|
||||
160 NEXT C
|
||||
170 GOSUB 9000
|
||||
200 CLS: INK 15: PRINT "CIRCLE"
|
||||
210 C=0
|
||||
220 FOR R=3 TO 117 STEP 3
|
||||
230 GOSUB 8000: CIRCLE 160,120,R,C
|
||||
240 NEXT R
|
||||
250 GOSUB 9000
|
||||
300 CLS: INK 15: PRINT "LINE"
|
||||
310 C=0
|
||||
320 FOR X=0 TO 319 STEP 8: GOSUB 8000: LINE 160,120,X,0,C: NEXT X
|
||||
330 FOR Y=0 TO 239 STEP 8: GOSUB 8000: LINE 160,120,319,Y,C: NEXT Y
|
||||
340 FOR X=319 TO 0 STEP -8: GOSUB 8000: LINE 160,120,X,239,C: NEXT X
|
||||
350 FOR Y=239 TO 0 STEP -8: GOSUB 8000: LINE 160,120,0,Y,C: NEXT Y
|
||||
360 GOSUB 9000
|
||||
400 CLS: INK 10: PRINT "Y = SIN(X)": INK 12: PRINT "Y = COS(X)"
|
||||
410 LINE 0,120,319,120,8: LINE 160,0,160,239,8
|
||||
420 FOR X=0 TO 319
|
||||
430 PLOT X,120-90*SIN((X-160)/25),10
|
||||
440 PLOT X,120-90*COS((X-160)/25),12
|
||||
450 NEXT X
|
||||
460 GOSUB 9000
|
||||
500 CLS: INK 15: PRINT "FILL AND RECT": RANDOMIZE
|
||||
510 FOR I=1 TO 120
|
||||
520 X=INT(RND*290): Y=16+INT(RND*200): C=1+INT(RND*15)
|
||||
530 IF RND<.5 THEN FILL X,Y,X+5+INT(RND*30),Y+5+INT(RND*20),C: GOTO 550
|
||||
540 RECT X,Y,X+5+INT(RND*30),Y+5+INT(RND*20),C
|
||||
550 NEXT I
|
||||
560 GOSUB 9000
|
||||
600 CLS: INK 15: PRINT "ANIMATION"
|
||||
610 RECT 0,16,319,239,7
|
||||
620 X=40: Y=60: U=3: V=2
|
||||
630 FOR I=1 TO 500
|
||||
640 CIRCLE X,Y,6,0
|
||||
650 X=X+U: Y=Y+V
|
||||
660 IF X<8 OR X>311 THEN U=-U
|
||||
670 IF Y<24 OR Y>231 THEN V=-V
|
||||
680 CIRCLE X,Y,6,11: PLOT X,Y,14
|
||||
690 T=TIM
|
||||
700 IF TIM-T<.01 THEN 700
|
||||
710 NEXT I
|
||||
720 GOSUB 9000
|
||||
800 CLS: INK 15: PRINT "MANDELBROT SET": M=TIM
|
||||
810 FOR J=0 TO 59: FOR I=0 TO 79
|
||||
820 A=I*.04-2.2: B=J*.04-1.2: X=0: Y=0
|
||||
830 FOR K=1 TO 15
|
||||
840 Z=X*X-Y*Y+A: Y=2*X*Y+B: X=Z
|
||||
850 IF X*X+Y*Y>4 THEN 870
|
||||
860 NEXT K
|
||||
870 IF K>15 THEN K=0
|
||||
880 FILL I*4,J*4,I*4+3,J*4+3,K
|
||||
890 NEXT I: NEXT J
|
||||
900 INK 7: LOCATE 30,1: PRINT "MANDELBROT TOOK";INT(TIM-M);"SECONDS.";
|
||||
910 PRINT " WHOLE DEMO";INT(TIM-S);"SECONDS."
|
||||
920 END
|
||||
8000 C=C+1: IF C>15 THEN C=1
|
||||
8010 RETURN
|
||||
9000 T=TIM
|
||||
9010 IF TIM-T<3 THEN 9010
|
||||
9020 RETURN
|
||||
@@ -0,0 +1,620 @@
|
||||
# Basys 3 Z-80 BASIC
|
||||
|
||||
*A Dartmouth-style BASIC with colour graphics, for the Z-80 inside the Basys 3
|
||||
VT220 terminal.*
|
||||
|
||||
## 1. Getting started
|
||||
|
||||
The Z-80 shares the board with the terminal. Two switches decide who the screen
|
||||
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) |
|
||||
|
||||
Flip **SW15 up**. The first time, BASIC greets you:
|
||||
|
||||
```
|
||||
DARTMOUTH-STYLE BASIC Z-80 ON A BASYS 3
|
||||
|
||||
READY
|
||||
```
|
||||
|
||||
The Z-80 keeps running while SW15 is down. It just waits until it can print
|
||||
again, so you can flip back and forth without losing your program. **BTND**
|
||||
restarts the Z-80; that wipes the program. **BTNC** restarts the whole board.
|
||||
|
||||
### Talking to BASIC
|
||||
|
||||
Anything typed without a line number runs at once:
|
||||
|
||||
```
|
||||
PRINT 2+2
|
||||
4
|
||||
```
|
||||
|
||||
A line that starts with a number is stored as part of the program instead:
|
||||
|
||||
```
|
||||
10 PRINT "HELLO"
|
||||
20 GOTO 10
|
||||
RUN
|
||||
```
|
||||
|
||||
- **Ctrl-C** stops a running program.
|
||||
- **Backspace** (or Delete) rubs out the last character.
|
||||
- **Ctrl-U** erases the whole line.
|
||||
- Cursor keys are ignored.
|
||||
|
||||
Lines can be up to 250 characters. Lower case is accepted and turned into upper
|
||||
case, except inside quotes.
|
||||
|
||||
### Editing a program
|
||||
|
||||
- To replace a line, type it again with the same number.
|
||||
- To delete a line, type its number alone.
|
||||
- Lines are kept in number order whatever order you type them in. Number in
|
||||
tens (10, 20, 30…) to leave room for later additions.
|
||||
- Changing the program clears all variables.
|
||||
|
||||
| Command | Does |
|
||||
|---|---|
|
||||
| `RUN` | Clear variables and run from the first line |
|
||||
| `RUN 100` | Clear variables and run from line 100 |
|
||||
| `LIST` | List the whole program (Ctrl-C stops a long listing) |
|
||||
| `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.
|
||||
|
||||
## 2. Program lines
|
||||
|
||||
A program line is a number from 0 to 65535 followed by one or more statements
|
||||
separated by colons:
|
||||
|
||||
```
|
||||
10 FOR I=1 TO 3: PRINT I: NEXT I
|
||||
```
|
||||
|
||||
Spaces don't matter outside quotes, as at Dartmouth. `FORI=1TO3` is the same as
|
||||
`FOR I = 1 TO 3`. `LIST` shows lines as you typed them.
|
||||
|
||||
The program runs in line-number order until it reaches `END`, `STOP`, the last
|
||||
line, or an error.
|
||||
|
||||
## 3. Numbers, variables and strings
|
||||
|
||||
### Numbers
|
||||
|
||||
All numbers are single-precision floating point: about 7 significant digits,
|
||||
magnitudes from about 1E-38 to 3E+38. Constants may be written `12`, `-3.5`,
|
||||
`.25`, `6.02E23` or `1E-6`.
|
||||
|
||||
`PRINT` shows numbers like this:
|
||||
|
||||
- At most 6 significant digits.
|
||||
- A leading space instead of a plus sign, and a trailing space.
|
||||
- Whole numbers below a million print without a point.
|
||||
- Values from .001 to 999999 print as decimals. Anything else uses E
|
||||
notation, such as `1.23457E+08` or `1E-05`.
|
||||
|
||||
### Numeric variables
|
||||
|
||||
A numeric variable is a letter, or a letter followed by one digit: `X`, `N`,
|
||||
`A1`, `Z9`. That gives 286 of them. All start at zero when the program is run.
|
||||
|
||||
### Arrays
|
||||
|
||||
An array has a one-letter name and one or two subscripts, both counting from 0.
|
||||
`DIM` declares its size:
|
||||
|
||||
```
|
||||
10 DIM A(100), M(8,8)
|
||||
```
|
||||
|
||||
An array used without `DIM` is given room for subscripts 0 to 10. An array and
|
||||
a plain variable of the same letter are separate: `A` and `A(3)` don't interfere.
|
||||
|
||||
### Strings
|
||||
|
||||
String variables are `A$` to `Z$`. Each holds up to 79 characters and starts
|
||||
empty. String constants are written in double quotes. `+` joins strings:
|
||||
|
||||
```
|
||||
10 A$ = "BASYS"
|
||||
20 B$ = A$ + " 3"
|
||||
30 PRINT B$
|
||||
```
|
||||
|
||||
## 4. Expressions
|
||||
|
||||
From highest precedence to lowest:
|
||||
|
||||
| Operators | Meaning |
|
||||
|---|---|
|
||||
| `( )` | Grouping |
|
||||
| `^` | Power: `2^10` is 1024 |
|
||||
| `-` `+` (unary) | Negation: `-2^2` is -4 |
|
||||
| `*` `/` | Multiply, divide |
|
||||
| `+` `-` | Add, subtract |
|
||||
| `=` `<>` `<` `>` `<=` `>=` | Comparisons (also work on strings) |
|
||||
| `NOT` | Bitwise not |
|
||||
| `AND` | Bitwise and |
|
||||
| `OR` | Bitwise or |
|
||||
|
||||
A comparison gives -1 when true and 0 when false. `AND`, `OR` and `NOT` work
|
||||
on whole numbers from -32768 to 32767, so they combine comparisons the expected
|
||||
way:
|
||||
|
||||
```
|
||||
IF X > 0 AND X < 10 THEN PRINT "SINGLE DIGIT"
|
||||
```
|
||||
|
||||
Strings compare in character order: `"APPLE" < "BANANA"` is true.
|
||||
|
||||
## 5. Statements
|
||||
|
||||
In the descriptions below, square brackets mark something you may leave out.
|
||||
|
||||
### LET — assignment
|
||||
|
||||
```
|
||||
LET X = 5
|
||||
X = 5
|
||||
A$ = "TEXT"
|
||||
M(I,J) = 0
|
||||
```
|
||||
|
||||
The word `LET` is optional.
|
||||
|
||||
### PRINT — output
|
||||
|
||||
```
|
||||
PRINT "X IS"; X
|
||||
PRINT A, B, C
|
||||
PRINT "NO NEW LINE";
|
||||
PRINT TAB(20); "INDENTED"
|
||||
PRINT
|
||||
```
|
||||
|
||||
- A **comma** moves to the next 15-column zone.
|
||||
- A **semicolon** prints the next item straight after.
|
||||
- A **comma or semicolon at the end** keeps the cursor on the same line.
|
||||
- **`TAB(n)`** moves to column *n*, counting from 0.
|
||||
- `PRINT` on its own prints an empty line.
|
||||
|
||||
### INPUT — read from the keyboard
|
||||
|
||||
```
|
||||
INPUT X
|
||||
INPUT A, B, C
|
||||
INPUT "YOUR NAME"; N$
|
||||
```
|
||||
|
||||
`INPUT` prints `? ` (after the prompt, if there is one) and waits for a line.
|
||||
Separate several values with commas. If you give too few, it asks for the rest
|
||||
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.
|
||||
|
||||
### IF … THEN — decisions
|
||||
|
||||
```
|
||||
IF X > 100 THEN 500
|
||||
IF X > 100 GOTO 500
|
||||
IF A$ = "YES" THEN PRINT "OK": GOTO 20
|
||||
```
|
||||
|
||||
When the condition is true, `THEN` is followed by a line number to jump to, or
|
||||
by statements to run. When it is false, the rest of the line is skipped, so
|
||||
statements after the colon run only when the condition is true. Any non-zero
|
||||
value counts as true.
|
||||
|
||||
### GOTO, GOSUB, RETURN, ON
|
||||
|
||||
```
|
||||
GOTO 100
|
||||
GOSUB 1000
|
||||
RETURN
|
||||
ON N GOTO 100, 200, 300
|
||||
ON N GOSUB 100, 200, 300
|
||||
```
|
||||
|
||||
- `GOSUB` jumps to a subroutine; `RETURN` comes back to the statement after the
|
||||
`GOSUB`. Subroutines can nest 32 deep.
|
||||
- `ON` picks the first line when *N* is 1, the second when it is 2, and so on.
|
||||
If *N* is out of range, the program carries on with the next statement.
|
||||
|
||||
### FOR … NEXT — loops
|
||||
|
||||
```
|
||||
FOR I = 1 TO 10
|
||||
FOR X = 0 TO 1 STEP .1
|
||||
FOR C = 10 TO 1 STEP -1
|
||||
NEXT I
|
||||
NEXT
|
||||
NEXT J, I
|
||||
```
|
||||
|
||||
- The loop runs while the variable has not passed the limit. `STEP` defaults
|
||||
to 1 and may be negative or fractional.
|
||||
- If the starting value is already past the limit, the loop body is skipped
|
||||
altogether.
|
||||
- `NEXT` without a name closes the innermost loop.
|
||||
- Loops nest 16 deep.
|
||||
- Jumping out of a loop with `GOTO` is allowed. Starting a new `FOR` with the
|
||||
same variable discards the old loop.
|
||||
|
||||
### DIM — arrays
|
||||
|
||||
```
|
||||
DIM A(50), B(10,20)
|
||||
```
|
||||
|
||||
See section 3. An array can hold at most 6000 elements.
|
||||
|
||||
### DEF FN — your own functions
|
||||
|
||||
```
|
||||
10 DEF FNA(X) = X*X + 1
|
||||
20 DEF FNR(D) = D * 3.14159 / 180
|
||||
30 PRINT FNA(3), SIN(FNR(30))
|
||||
```
|
||||
|
||||
A function has a one-letter name and one numeric argument. Other variables used
|
||||
in its formula are the program's ordinary variables.
|
||||
|
||||
### READ, DATA, RESTORE
|
||||
|
||||
```
|
||||
10 READ N, A$
|
||||
20 PRINT A$; N
|
||||
30 DATA 42, "ANSWER"
|
||||
40 RESTORE
|
||||
```
|
||||
|
||||
`READ` takes values from `DATA` statements in line order, wherever they are in
|
||||
the program. A `DATA` statement takes up the rest of its line. `RESTORE` starts
|
||||
again from the first item.
|
||||
|
||||
### END, STOP, REM
|
||||
|
||||
- `END` stops the program quietly.
|
||||
- `STOP` stops it with the message `STOP IN line`.
|
||||
- `REM` starts a comment that runs to the end of the line.
|
||||
|
||||
### RANDOMIZE
|
||||
|
||||
`RANDOMIZE` mixes the timer into the random number generator, so each run gives
|
||||
different numbers. Without it, `RND` produces the same sequence every time the
|
||||
Z-80 is reset.
|
||||
|
||||
### POKE and OUT
|
||||
|
||||
```
|
||||
POKE address, value
|
||||
OUT port, value
|
||||
```
|
||||
|
||||
See section 9.
|
||||
|
||||
### Graphics and text placement
|
||||
|
||||
`CLS`, `COLOR`, `PLOT`, `LINE`, `RECT`, `FILL`, `CIRCLE`, `LOCATE` and `INK`
|
||||
are described in sections 7 and 8.
|
||||
|
||||
## 6. Functions
|
||||
|
||||
### Arithmetic
|
||||
|
||||
| Function | Result |
|
||||
|---|---|
|
||||
| `ABS(X)` | Absolute value |
|
||||
| `SGN(X)` | -1, 0 or 1 |
|
||||
| `INT(X)` | Largest whole number not above *X*: `INT(-2.5)` is -3 |
|
||||
| `SQR(X)` | Square root |
|
||||
| `EXP(X)` | e to the power *X* |
|
||||
| `LOG(X)` | Natural logarithm |
|
||||
| `SIN(X)`, `COS(X)`, `TAN(X)` | Trigonometry, in radians |
|
||||
| `ATN(X)` | Arctangent, in radians; `4*ATN(1)` is pi |
|
||||
| `RND` or `RND(X)` | Random number from 0 up to (not including) 1; *X* is ignored |
|
||||
| `FNx(X)` | A function made with `DEF` |
|
||||
|
||||
A whole number from 1 to 6: `1 + INT(RND * 6)`.
|
||||
|
||||
### Strings
|
||||
|
||||
| Function | Result |
|
||||
|---|---|
|
||||
| `LEN(A$)` | Number of characters |
|
||||
| `VAL(A$)` | The number written in the string (0 if none) |
|
||||
| `ASC(A$)` | Code of the first character |
|
||||
| `CHR$(N)` | The character with code *N* |
|
||||
| `STR$(X)` | The number as text, with a leading space if positive |
|
||||
| `LEFT$(A$, N)` | First *N* characters |
|
||||
| `RIGHT$(A$, N)` | Last *N* characters |
|
||||
| `MID$(A$, S [, N])` | *N* characters (or the rest) starting at position *S* (from 1) |
|
||||
|
||||
### Machine and screen
|
||||
|
||||
| Function | Result |
|
||||
|---|---|
|
||||
| `TIM` | Seconds since the Z-80 was reset, to the millisecond |
|
||||
| `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* |
|
||||
|
||||
`TIM` is handy for delays and for timing:
|
||||
|
||||
```
|
||||
10 T = TIM
|
||||
20 IF TIM - T < 2 THEN 20
|
||||
```
|
||||
|
||||
## 7. Graphics
|
||||
|
||||
The screen has a graphics layer **320 pixels wide and 240 high in 16 colours**.
|
||||
It is mixed with the 80×30 text:
|
||||
|
||||
- **Coordinates:** *X* runs from 0 at the left to 319, and *Y* from 0 at the
|
||||
top to 239. Each graphics pixel is a 2×2 block on the monitor.
|
||||
- **Mixing with text:** text characters are drawn on top of the graphics. The
|
||||
graphics show through wherever the text screen is blank.
|
||||
- **Colour 0** is "no graphics": it shows the text background, normally black.
|
||||
Drawing in colour 0 erases.
|
||||
- **Clipping:** anything that falls off the edge is simply not drawn, so a
|
||||
circle may hang off the screen.
|
||||
- **Text cells:** a text character covers 4×8 graphics pixels. The character at
|
||||
row *r*, column *c* (as used by `LOCATE`) starts at
|
||||
*X* = 4(*c*−1), *Y* = 8(*r*−1).
|
||||
|
||||
### Colours
|
||||
|
||||
| Number | Colour | Number | Colour |
|
||||
|---|---|---|---|
|
||||
| 0 | None / black | 8 | Dark grey |
|
||||
| 1 | Red | 9 | Bright red |
|
||||
| 2 | Green | 10 | Bright green |
|
||||
| 3 | Brown | 11 | Yellow |
|
||||
| 4 | Blue | 12 | Bright blue |
|
||||
| 5 | Magenta | 13 | Bright magenta |
|
||||
| 6 | Cyan | 14 | Bright cyan |
|
||||
| 7 | Light grey | 15 | White |
|
||||
|
||||
### Graphics statements
|
||||
|
||||
In every drawing statement the colour is optional. Without it, the colour set
|
||||
by `COLOR` is used, initially 15 (white).
|
||||
|
||||
| Statement | Draws |
|
||||
|---|---|
|
||||
| `CLS` | Clears the text screen and the graphics, cursor to the top left |
|
||||
| `COLOR C` | Sets the drawing colour for later statements |
|
||||
| `PLOT X, Y [, C]` | One pixel |
|
||||
| `LINE X1, Y1, X2, Y2 [, C]` | A straight line between two points |
|
||||
| `RECT X1, Y1, X2, Y2 [, C]` | The outline of a rectangle with those corners |
|
||||
| `FILL X1, Y1, X2, Y2 [, C]` | A solid rectangle |
|
||||
| `CIRCLE X, Y, R [, C]` | A circle centred on *X, Y* with radius *R* |
|
||||
|
||||
`POINT(X, Y)` reads a pixel back (section 6).
|
||||
|
||||
```
|
||||
10 CLS
|
||||
20 FILL 0, 200, 319, 239, 2
|
||||
30 CIRCLE 260, 40, 25, 11
|
||||
40 FOR I = 0 TO 6
|
||||
50 LINE 60 + I*30, 200, 75 + I*30, 140, 3
|
||||
60 NEXT I
|
||||
70 RECT 20, 120, 300, 230, 7
|
||||
```
|
||||
|
||||
### Animation
|
||||
|
||||
Erase something by drawing it again in colour 0, then draw it in its new
|
||||
place. Use `TIM` to set the pace:
|
||||
|
||||
```
|
||||
10 CLS: X = 0
|
||||
20 CIRCLE X, 120, 10, 0
|
||||
30 X = X + 2: IF X > 319 THEN X = 0
|
||||
40 CIRCLE X, 120, 10, 14
|
||||
50 T = TIM
|
||||
60 IF TIM - T < .02 THEN 60
|
||||
70 GOTO 20
|
||||
```
|
||||
|
||||
### Speed
|
||||
|
||||
`CLS` clears the graphics in under a millisecond, and a line right across the
|
||||
screen takes about 2 milliseconds. `FILL` is the fastest way to cover a large
|
||||
area. Most of the time in a graphics program goes on BASIC itself working out
|
||||
the numbers (see section 9).
|
||||
|
||||
## 8. The text screen
|
||||
|
||||
The text screen is 80 columns by 30 rows. Two statements place and colour text:
|
||||
|
||||
| Statement | Does |
|
||||
|---|---|
|
||||
| `LOCATE R, C` | Moves the cursor to row *R* (1–30), column *C* (1–80) |
|
||||
| `INK F [, B]` | Sets the text colour *F* and, optionally, background *B*, using the colour numbers above |
|
||||
|
||||
```
|
||||
10 CLS
|
||||
20 INK 14: LOCATE 15, 35: PRINT "CENTRED"
|
||||
30 INK 0, 11: LOCATE 16, 35: PRINT " BLACK ON YELLOW "
|
||||
```
|
||||
|
||||
The terminal is a full VT220 with ANSI colour, so anything it understands can be
|
||||
printed with `CHR$(27)`. For example, `PRINT CHR$(27);"[0m"` returns to normal
|
||||
colours, `PRINT CHR$(27);"[4m"` turns on underlining, and
|
||||
`PRINT CHR$(27);"[2K"` erases the current line.
|
||||
|
||||
When the cursor passes the bottom row the text scrolls. The graphics layer
|
||||
stays where it is.
|
||||
|
||||
## 9. The machine
|
||||
|
||||
### Memory
|
||||
|
||||
| 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 |
|
||||
|
||||
`PEEK` can read anything; `POKE` can change anything from 8000 up, including
|
||||
BASIC's own data. Poke with care.
|
||||
|
||||
### I/O ports
|
||||
|
||||
| Port | `INP` | `OUT` |
|
||||
|---|---|---|
|
||||
| 0 | bit 0: a key is waiting; bit 1: the screen can take a character | — |
|
||||
| 1 | the waiting key | a character to the screen |
|
||||
| 16–19 | the millisecond counter, low byte first (reading 16 freezes the other three) | — |
|
||||
| 32 | — | right two digits of the 7-segment display (hex) |
|
||||
| 33 | — | left two digits of the 7-segment display |
|
||||
| 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 |
|
||||
|
||||
```
|
||||
10 FOR I = 0 TO 255
|
||||
20 OUT 32, I: OUT 33, 255 - I
|
||||
30 T = TIM
|
||||
40 IF TIM - T < .05 THEN 40
|
||||
50 NEXT I
|
||||
```
|
||||
|
||||
A key check that doesn't wait (the key is used up):
|
||||
|
||||
```
|
||||
100 IF INP(0) AND 1 THEN K = INP(1): PRINT "YOU PRESSED "; CHR$(K)
|
||||
```
|
||||
|
||||
### Speed
|
||||
|
||||
The Z-80 runs at 90 MHz and needs about 2.7 clocks per instruction, roughly 50
|
||||
times the speed of a classic 4 MHz Z-80. BASIC does its arithmetic in software,
|
||||
so in round numbers:
|
||||
|
||||
| Operation | Time |
|
||||
|---|---|
|
||||
| One pass of an empty `FOR … NEXT` loop | 30 µs (about 30,000 a second) |
|
||||
| `X = I * 1.5` | 0.12 ms |
|
||||
| `Y = SIN(X)` | 0.4 ms |
|
||||
| `LINE` right across the screen | 2 ms |
|
||||
|
||||
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
|
||||
|
||||
Keep programs as plain text files with one numbered line per line. To type one
|
||||
into the board:
|
||||
|
||||
1. Flip **SW15** and **SW14** up.
|
||||
2. Make sure nothing else is using the serial port. If a login getty is running
|
||||
on it, stop it:
|
||||
```
|
||||
sudo systemctl stop serial-getty@ttyUSB1
|
||||
```
|
||||
3. Send the file at the baud rate set by SW1:0 (SW0 up is 9600):
|
||||
```
|
||||
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.
|
||||
4. Flip SW14 back down when you're done. Restart the getty with
|
||||
`sudo systemctl start serial-getty@ttyUSB1` if you want the PC login back.
|
||||
|
||||
Pasting into a terminal program such as `picocom` works too.
|
||||
|
||||
## 11. Error messages
|
||||
|
||||
An error stops the program and reports the line, for example
|
||||
`?DIVISION BY ZERO IN 120`.
|
||||
|
||||
| Message | Cause |
|
||||
|---|---|
|
||||
| `SYNTAX ERROR` | A statement BASIC can't make sense of |
|
||||
| `UNDEFINED LINE NUMBER` | `GOTO`, `GOSUB`, `THEN` or `RUN` to a line that doesn't exist |
|
||||
| `RETURN WITHOUT GOSUB` | `RETURN` with no `GOSUB` to go back to |
|
||||
| `NEXT WITHOUT FOR` | `NEXT` with no loop open (or the wrong variable) |
|
||||
| `OUT OF DATA` | `READ` after the last `DATA` item |
|
||||
| `SUBSCRIPT OUT OF RANGE` | An array subscript below 0 or beyond its `DIM` |
|
||||
| `DIVISION BY ZERO` | Dividing by 0 |
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `BREAK IN n` | You pressed Ctrl-C |
|
||||
| `STOP IN n` | The program ran `STOP` |
|
||||
|
||||
## 12. Example programs
|
||||
|
||||
### Times table
|
||||
|
||||
```
|
||||
10 FOR I = 1 TO 9
|
||||
20 FOR J = 1 TO 9
|
||||
30 PRINT TAB(J*5); I*J;
|
||||
40 NEXT J
|
||||
50 PRINT
|
||||
60 NEXT I
|
||||
```
|
||||
|
||||
### Guess the number
|
||||
|
||||
```
|
||||
10 RANDOMIZE
|
||||
20 N = 1 + INT(RND * 100): G = 0
|
||||
30 PRINT "I'M THINKING OF A NUMBER FROM 1 TO 100."
|
||||
40 INPUT "YOUR GUESS"; X
|
||||
50 G = G + 1
|
||||
60 IF X < N THEN PRINT "HIGHER": GOTO 40
|
||||
70 IF X > N THEN PRINT "LOWER": GOTO 40
|
||||
80 PRINT "RIGHT IN"; G; "GUESSES!"
|
||||
```
|
||||
|
||||
### Spirograph
|
||||
|
||||
```
|
||||
10 CLS: C = 1
|
||||
20 FOR A = 0 TO 6.283 STEP .0628
|
||||
30 X = 160 + 100*COS(A) + 15*COS(A*7)
|
||||
40 Y = 120 + 100*SIN(A) - 15*SIN(A*7)
|
||||
50 IF A > 0 THEN LINE U, V, X, Y, C
|
||||
60 U = X: V = Y: C = C + 1: IF C > 15 THEN C = 1
|
||||
70 NEXT A
|
||||
```
|
||||
|
||||
### The graphics demo
|
||||
|
||||
`basic/examples/graphics-demo.bas` shows everything in turn. It draws colour
|
||||
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
|
||||
|
||||
| Item | Limit |
|
||||
|---|---|
|
||||
| Program and arrays together | about 22 KB |
|
||||
| Line numbers | 0 – 65535 |
|
||||
| Line length | 250 characters typed |
|
||||
| Numeric variables | A–Z and A0–Z9 |
|
||||
| String variables | A$–Z$, 79 characters each |
|
||||
| Arrays | A–Z, 1 or 2 subscripts, up to 6000 elements each |
|
||||
| User functions | FNA–FNZ, one argument each |
|
||||
| FOR nesting / GOSUB nesting | 16 / 32 |
|
||||
| Graphics | 320 × 240, 16 colours |
|
||||
| Text | 80 × 30 |
|
||||
Binary file not shown.
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# Turn docs/basic-manual.md into docs/basic-manual.pdf (needs python3-markdown and Chrome).
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
python3 - <<'PY'
|
||||
import markdown
|
||||
body = markdown.markdown(open("basic-manual.md").read(), extensions=["tables", "fenced_code"])
|
||||
css = """
|
||||
@page { size: A4; margin: 18mm 16mm; }
|
||||
body { font-family: "DejaVu Serif", Georgia, serif; font-size: 10.5pt; line-height: 1.45; color: #111; }
|
||||
h1 { font-size: 24pt; margin: 0 0 4pt; }
|
||||
h1 + p { font-size: 12pt; color: #444; margin-bottom: 18pt; }
|
||||
h2 { font-size: 15pt; border-bottom: 1px solid #999; padding-bottom: 2pt; margin-top: 22pt;
|
||||
page-break-after: avoid; }
|
||||
h3 { font-size: 12pt; margin-top: 14pt; page-break-after: avoid; }
|
||||
code, pre { font-family: "DejaVu Sans Mono", monospace; font-size: 9pt; }
|
||||
pre { background: #f2f2f2; border-left: 3px solid #4a7; padding: 6pt 8pt; page-break-inside: avoid; }
|
||||
table { border-collapse: collapse; margin: 6pt 0; page-break-inside: avoid; }
|
||||
th, td { border: 1px solid #bbb; padding: 3pt 6pt; vertical-align: top; text-align: left; }
|
||||
th { background: #e8e8e8; }
|
||||
"""
|
||||
open("basic-manual.html", "w").write(
|
||||
"<!doctype html><html><head><meta charset='utf-8'><title>Basys 3 Z-80 BASIC</title>"
|
||||
"<style>%s</style></head><body>%s</body></html>" % (css, body))
|
||||
PY
|
||||
google-chrome --headless --disable-gpu --no-pdf-header-footer \
|
||||
--print-to-pdf="$PWD/basic-manual.pdf" "file://$PWD/basic-manual.html" 2>/dev/null
|
||||
rm basic-manual.html
|
||||
echo "wrote docs/basic-manual.pdf"
|
||||
@@ -268,12 +268,15 @@ module basys3_terminal #(
|
||||
always @(posedge clk) ztx_req_s <= {ztx_req_s[0], ztx_req};
|
||||
|
||||
wire [15:0] z80_seg;
|
||||
wire [16:0] gfx_addr;
|
||||
wire [3:0] gfx_pix;
|
||||
|
||||
z80_system #(.MEM_FILE(MEM_FILE), .CPU_HZ(CPU_HZ)) z80 (
|
||||
.clk(cpu_clk), .rst(cpu_rst_s[2]),
|
||||
.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()
|
||||
.seg_val(z80_seg), .halted(),
|
||||
.vclk(clk), .gfx_vaddr(gfx_addr), .gfx_vpix(gfx_pix)
|
||||
);
|
||||
|
||||
// terminal input: Z-80 output or received bytes, local echo, banner
|
||||
@@ -358,7 +361,7 @@ module basys3_terminal #(
|
||||
text_display #(.FONT_FILE(FONT_FILE)) video (
|
||||
.clk(clk), .rst(rst), .cur_row(cur_row), .cur_col(cur_col), .cur_vis(cur_vis),
|
||||
.stop(stop), .sbot(sbot), .sm_on(sm_on), .sm_dir(sm_dir), .sm_off(sm_off),
|
||||
.ram_addr(v_addr), .ram_data(v_data),
|
||||
.ram_addr(v_addr), .ram_data(v_data), .gfx_addr(gfx_addr), .gfx_pix(gfx_pix),
|
||||
.red(vgaRed), .green(vgaGreen), .blue(vgaBlue), .hsync(Hsync), .vsync(Vsync),
|
||||
.frame_tick(frame_tick)
|
||||
);
|
||||
|
||||
+8
-1
@@ -2,6 +2,8 @@
|
||||
|
||||
// 640x480 @ 60 Hz VGA text display: 80x30 cells of 8x16 pixels, 16 colours,
|
||||
// underline, blink, block cursor and smooth-scroll offset for the scroll region.
|
||||
// A 320x240 graphics layer (each pixel 2x2) shows through wherever the text is
|
||||
// background; graphics colour 0 is transparent.
|
||||
// Runs on the 100 MHz clock with a 25 MHz pixel enable. After each pixel tick:
|
||||
// clock 1 scanline values registered (row base address, glyph line)
|
||||
// clock 2 character RAM read
|
||||
@@ -23,6 +25,8 @@ module text_display #(
|
||||
input [4:0] sm_off, // pixels the region has moved
|
||||
output [11:0] ram_addr,
|
||||
input [17:0] ram_data, // {blink, underline, bg, fg, code}
|
||||
output [16:0] gfx_addr, // graphics pixel, read a clock later
|
||||
input [3:0] gfx_pix,
|
||||
output reg [3:0] red,
|
||||
output reg [3:0] green,
|
||||
output reg [3:0] blue,
|
||||
@@ -75,6 +79,7 @@ module text_display #(
|
||||
|
||||
wire [6:0] tcol = h[9:3];
|
||||
assign ram_addr = row_base + {5'b0, tcol};
|
||||
assign gfx_addr = {v[8:1], 8'd0} + {2'd0, v[8:1], 6'd0} + {8'd0, h[9:1]};
|
||||
|
||||
reg [7:0] font [0:4095];
|
||||
reg [7:0] glyph;
|
||||
@@ -97,7 +102,9 @@ module text_display #(
|
||||
wire visible = h < H_VIS && v < V_VIS;
|
||||
wire cursor = cur_vis && frame[5] && tcol == cur_col && srow == cur_row;
|
||||
wire ink = (glyph[~h[2:0]] | (ram_data[16] && line == 4'd15)) && !(ram_data[17] && frame[5]);
|
||||
wire [3:0] idx = blank_line ? 4'd0 : (ink ^ cursor) ? ram_data[11:8] : ram_data[15:12];
|
||||
wire fg = !blank_line && (ink ^ cursor);
|
||||
wire [3:0] idx = fg ? ram_data[11:8] : gfx_pix != 4'd0 ? gfx_pix :
|
||||
blank_line ? 4'd0 : ram_data[15:12];
|
||||
|
||||
always @(posedge clk) begin
|
||||
if (tick) begin
|
||||
|
||||
+51
-1
@@ -9,7 +9,11 @@
|
||||
// 01 in key (clears bit 0) out byte to the terminal
|
||||
// 10 in millisecond counter bits 7:0; reading it latches bits 31:8 for 11-13
|
||||
// 20 out 7-segment display, right two digits 21 out left two digits
|
||||
// 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
|
||||
//
|
||||
// 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.
|
||||
module z80_system #(
|
||||
parameter MEM_FILE = "basic.mem",
|
||||
@@ -27,7 +31,11 @@ module z80_system #(
|
||||
output reg [7:0] tx_data,
|
||||
input tx_ack,
|
||||
output reg [15:0] seg_val,
|
||||
output halted
|
||||
output halted,
|
||||
// graphics layer read port, on the video clock
|
||||
input vclk,
|
||||
input [16:0] gfx_vaddr,
|
||||
output reg [3:0] gfx_vpix
|
||||
);
|
||||
wire [15:0] ma, io_addr;
|
||||
wire we, io_rd, io_wr;
|
||||
@@ -57,6 +65,46 @@ module z80_system #(
|
||||
wire rx_avail = rx_req_s[1] != rx_ack;
|
||||
wire tx_ready = tx_ack_s[1] == tx_req;
|
||||
|
||||
// ------------------------------------------------------------ graphics
|
||||
localparam GFX_PIXELS = 320 * 240;
|
||||
(* ram_style = "block" *) reg [3:0] gfx [0:GFX_PIXELS - 1];
|
||||
integer gi;
|
||||
initial for (gi = 0; gi < GFX_PIXELS; gi = gi + 1) gfx[gi] = 4'd0;
|
||||
|
||||
reg [8:0] gx;
|
||||
reg [7:0] gy;
|
||||
reg [3:0] gfx_q, fill_c;
|
||||
reg [16:0] fill_a;
|
||||
reg fill_busy;
|
||||
wire [16:0] gxy = {gy, 8'd0} + {2'd0, gy, 6'd0} + {8'd0, gx};
|
||||
wire plot = io_wr && io_addr[7:0] == 8'h33 && gx < 9'd320 && gy < 8'd240;
|
||||
wire [16:0] g_addr = fill_busy ? fill_a : gxy;
|
||||
|
||||
always @(posedge clk) begin
|
||||
if (fill_busy || plot) gfx[g_addr] <= fill_busy ? fill_c : io_wd[3:0];
|
||||
gfx_q <= gfx[g_addr];
|
||||
end
|
||||
always @(posedge vclk) gfx_vpix <= gfx[gfx_vaddr];
|
||||
|
||||
always @(posedge clk)
|
||||
if (rst) begin
|
||||
fill_busy <= 1'b0;
|
||||
gx <= 9'd0; gy <= 8'd0;
|
||||
end else begin
|
||||
if (io_wr) case (io_addr[7:0])
|
||||
8'h30: gx[7:0] <= io_wd;
|
||||
8'h31: gx[8] <= io_wd[0];
|
||||
8'h32: gy <= io_wd;
|
||||
8'h33: gx <= gx + 1'b1;
|
||||
8'h34: begin fill_busy <= 1'b1; fill_a <= 17'd0; fill_c <= io_wd[3:0]; end
|
||||
default: ;
|
||||
endcase
|
||||
if (fill_busy) begin
|
||||
fill_a <= fill_a + 1'b1;
|
||||
if (fill_a == GFX_PIXELS - 1) fill_busy <= 1'b0;
|
||||
end
|
||||
end
|
||||
|
||||
// millisecond timer
|
||||
localparam MS_DIV = CPU_HZ / 1000;
|
||||
reg [31:0] ms, ms_latch;
|
||||
@@ -76,6 +124,8 @@ module z80_system #(
|
||||
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};
|
||||
default: io_din = 8'hFF;
|
||||
endcase
|
||||
|
||||
|
||||
+17
-1
@@ -169,7 +169,7 @@ module tb_terminal;
|
||||
endtask
|
||||
|
||||
// check VGA timing on the outputs
|
||||
realtime t_hs = 0, t_vs = 0;
|
||||
realtime t_hs = 0, t_vs = 0, t_cmd;
|
||||
always @(negedge hs) begin
|
||||
if (t_hs != 0 && ($realtime - t_hs) != 32000) $display("HSYNC period %0t", $realtime - t_hs);
|
||||
t_hs = $realtime;
|
||||
@@ -264,6 +264,22 @@ module tb_terminal;
|
||||
expect_row(10, " 1 4 9");
|
||||
expect_row(11, "READY");
|
||||
|
||||
// ---- graphics
|
||||
uart_str({"CLS:INK 11:CIRCLE 160,120,50,12:FILL 10,10,40,30,4:",
|
||||
"LINE 0,0,319,239,14:PRINT POINT(160,70)\015"});
|
||||
t_cmd = $realtime;
|
||||
while (cellraw(0, 2) != "2" && $realtime - t_cmd < 20_000_000) #10_000;
|
||||
$display("graphics line ran in %0.2f ms", ($realtime - t_cmd) / 1e6);
|
||||
expect_row(0, " 12");
|
||||
if (dut.z80.gfx[70 * 320 + 160] == 12 && dut.z80.gfx[20 * 320 + 20] == 4 &&
|
||||
dut.z80.gfx[120 * 320 + 160] == 14 && dut.z80.gfx[5 * 320 + 100] == 0)
|
||||
$display("PASS graphics memory");
|
||||
else begin
|
||||
$display("FAIL graphics memory");
|
||||
errors = errors + 1;
|
||||
end
|
||||
capture_frame("frame_3.ppm");
|
||||
|
||||
dump_screen;
|
||||
if (errors == 0) $display("ALL TESTS PASSED");
|
||||
else $display("%0d TESTS FAILED", errors);
|
||||
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Type a BASIC program into the Basys 3 Z-80 over the serial port.
|
||||
|
||||
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.
|
||||
|
||||
tools/send-bas.py basic/examples/graphics-demo.bas --baud 9600 --run
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import termios
|
||||
import time
|
||||
|
||||
BAUDS = {9600: termios.B9600, 19200: termios.B19200, 57600: termios.B57600,
|
||||
115200: termios.B115200}
|
||||
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("file")
|
||||
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")
|
||||
a = ap.parse_args()
|
||||
|
||||
fd = os.open(a.port, os.O_RDWR | os.O_NOCTTY)
|
||||
t = termios.tcgetattr(fd)
|
||||
t[0] = termios.IXON # honour XON/XOFF
|
||||
t[1] = 0
|
||||
t[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
|
||||
t[3] = 0
|
||||
t[4] = t[5] = BAUDS[a.baud]
|
||||
termios.tcsetattr(fd, termios.TCSANOW, t)
|
||||
|
||||
lines = [l.rstrip() for l in open(a.file) if l.strip()]
|
||||
if not a.keep:
|
||||
lines.insert(0, "NEW")
|
||||
if a.run:
|
||||
lines.append("RUN")
|
||||
for n, line in enumerate(lines, 1):
|
||||
os.write(fd, line.encode("ascii") + b"\r")
|
||||
termios.tcdrain(fd)
|
||||
time.sleep(0.02) # let BASIC store the line
|
||||
print("\r%d/%d lines" % (n, len(lines)), end="", flush=True)
|
||||
print()
|
||||
os.close(fd)
|
||||
+14
-1
@@ -35,6 +35,9 @@ class Z80:
|
||||
self.inp = bytearray(inp)
|
||||
self.out = out if out is not None else bytearray()
|
||||
self.rom_top = 0
|
||||
self.count = 0
|
||||
self.idle = 0
|
||||
self.last_poll = 0
|
||||
|
||||
# ------------------------------------------------------------- helpers
|
||||
def rd(self, a):
|
||||
@@ -78,9 +81,16 @@ class Z80:
|
||||
def io_in(self, port):
|
||||
p = port & 0xFF
|
||||
if p == 0:
|
||||
if not self.inp: # back-to-back polls: waiting for a key
|
||||
self.idle = self.idle + 1 if self.count - self.last_poll < 30 else 0
|
||||
self.last_poll = self.count
|
||||
return (1 if self.inp else 0) | 2
|
||||
if p == 1:
|
||||
return self.inp.pop(0) if self.inp else 0
|
||||
if 0x10 <= p <= 0x13: # ~3 clocks per instruction at 90 MHz
|
||||
return (self.count * 3 // 90000) >> (8 * (p - 0x10)) & 0xFF
|
||||
if p in (0x33, 0x34): # graphics: nothing drawn, never busy
|
||||
return 0
|
||||
return 0xFF
|
||||
|
||||
def io_out(self, port, v):
|
||||
@@ -525,16 +535,19 @@ def main():
|
||||
ap.add_argument("--trace", help="write a register trace here")
|
||||
ap.add_argument("--max", type=int, default=10_000_000, help="instruction limit")
|
||||
ap.add_argument("--rom-top", type=lambda s: int(s, 0), default=0)
|
||||
ap.add_argument("--stop-idle", action="store_true",
|
||||
help="stop once the input is used up and the program waits for a key")
|
||||
a = ap.parse_args()
|
||||
inp = open(a.input, "rb").read() if a.input else b""
|
||||
cpu = Z80(open(a.image, "rb").read(), inp)
|
||||
cpu.rom_top = a.rom_top
|
||||
tr = open(a.trace, "w") if a.trace else None
|
||||
n = 0
|
||||
while not cpu.halted and n < a.max:
|
||||
while not cpu.halted and n < a.max and not (a.stop_idle and cpu.idle > 100):
|
||||
if tr: tr.write(fmt(cpu.state()) + "\n")
|
||||
cpu.step()
|
||||
n += 1
|
||||
cpu.count = n
|
||||
sys.stdout.write(cpu.out.decode("latin-1"))
|
||||
if tr:
|
||||
open(a.trace.replace("trace", "mem"), "w").write("".join("%02x\n" % v for v in cpu.m[32768:]))
|
||||
|
||||
Reference in new issue
Block a user