# 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 | — | 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: ``` 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** (or **Ctrl-Alt-Del** on the keyboard) restarts the Z-80; that wipes the program but not the files in flash. **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 | | `SAVE "NAME"` | Keep the program in the board's flash (section 11) | | `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 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. `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 11). ### 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, OUT, CALL and MONITOR ``` POKE address, value OUT port, value CALL address MONITOR ``` `CALL` runs machine code at *address* as a subroutine: it must end with `RET` and leave `IX` and `SP` as it found them. `MONITOR` stops BASIC in the machine-code monitor (section 10). See section 9 for memory and ports. ### 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 | | `DATE$` | The date and time as `"2026-11-28 09:30:15"`, or `""` if not set (section 11) | | `EOF(N)` | -1 (true) when file *N* has been read to the end, else 0 (section 11) | | `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:** in 80 columns 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). The graphics cover rows 1–30; rows 31 and 32 are text only. ### 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 ``` ### Sprites Sprites are small pictures that the hardware draws over the graphics wherever you put them. To move one, give it a new position: nothing needs erasing or redrawing, nothing flickers, and the Z-80 does no drawing work. They are what moving things in a game should be made of. - **32 sprites**, numbered 0–31, each 16 × 16 graphics pixels. - **64 shapes**, numbered 0–63, that the sprites show. Several sprites can show the same shape. - **Colours:** each pixel of a shape is one of the 16 colours; colour 0 is see-through. - **Layers:** sprites are in front of the graphics and behind the text. Where sprites overlap, the lower number is in front. - **Collisions:** the hardware notices when a sprite touches another sprite, or touches a graphics pixel that isn't colour 0. BASIC drives them with `OUT` and `INP`: | Port | `OUT` | `INP` | |---|---|---| | 112 | Pick sprite *n* (0–31) for ports 113–117 | — | | 113, 114 | X: `X AND 255`, then `INT(X / 256)` | — | | 115 | Y; the sprite moves to the new X and Y together | — | | 116 | Shape (0–63) | — | | 117 | 1 = show, 0 = hide; add 2 to flip left-right, 4 to flip upside down | — | | 118 | Start defining shape *n* (0–63) | — | | 119 | The next two pixels of the shape: 16 × left colour + right colour | — | | 120 | — | Frame counter: goes up by one 60 times a second, as each picture is finished | | 128–131 | — | Sprites that touched another sprite in the last frame: 128 has a bit for sprites 0–7 (1, 2, 4 … 128), 129 for 8–15, 130 for 16–23, 131 for 24–31 | | 132–135 | — | The same for sprites that touched the graphics | **Defining a shape.** `OUT 118, n` and then 128 `OUT 119`s: the 16 rows from the top, each as 8 bytes of two pixels. A shape stays defined until the power goes off, even through `NEW`, so define it once. **Placing a sprite.** X and Y are its top-left pixel, the same as for `PLOT`. X can go from 0 to 511 and Y from 0 to 255; values past the edge wrap round, so X = 500 puts the sprite 12 pixels off the left edge, half showing. ``` 10 CLS 20 OUT 118, 0: FOR I = 1 TO 128: OUT 119, 204: NEXT I : REM SHAPE 0: COLOUR 12 30 OUT 112, 0: OUT 116, 0: OUT 117, 1 : REM SPRITE 0 SHOWS IT 40 FOR X = 0 TO 304 50 OUT 112, 0: OUT 113, X AND 255: OUT 114, INT(X / 256): OUT 115, 100 60 F = INP(120) 70 IF INP(120) = F THEN 70 : REM WAIT FOR THE NEXT FRAME 80 NEXT X ``` Waiting for the frame counter to change, as in lines 60–70, keeps movement smooth: one step per frame, 60 a second. **Collisions.** `IF INP(128) AND 1 THEN …` asks whether sprite 0 touched another sprite in the last frame; `INP(132) AND 1` whether it touched the graphics, such as a wall drawn with `FILL`. A collision only counts where pixels that aren't colour 0 overlap, so the see-through corners of a round shape don't count. **Turning them off.** `CLS` hides every sprite (the shapes are kept), and so does restarting the Z-80. `OUT 117, 0` hides the picked one. `basic/examples/sprites.bas` is a complete example: a robot steered with W A S D among bouncing balls, with shapes written as rows of hex digits. ### 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 32 rows; `PRINT CHR$(27);"[?3h"` switches to 132 columns by 64 rows in a smaller font (and clears it), `CHR$(27);"[?3l"` back. Two statements place and colour text: | Statement | Does | |---|---| | `LOCATE R, C` | Moves the cursor to row *R* (1–32, or 1–64), column *C* (1–80, or 1–132) | | `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. With **SW8** up the scroll is smooth but held to 7.5 lines a second (15 with SW9 up as well), which slows down long listings; flip SW8 down for full speed. ## 9. The machine ### Memory | Addresses | Contents | |---|---| | 0000–7FFF | BASIC itself (writes here are ignored) | | 8000–EFFF | BASIC's variables, your program and arrays, file buffers (your program starts at 8482h) | | F000–F3F7 | Free for your machine code (1016 bytes); BASIC never uses it | | F3F8–F3FF | The clock set by `DATE` | | F400–FFFF | The Z-80 stack | `PEEK` can read anything; `POKE` can change anything from 8000 up, including BASIC's own data, so put machine code at **F000h (61440) to F3F7h**, which is kept free for it. ### 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; also hides the sprites, unless 128 is added | | 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 | | 96 | why the monitor was entered (used by the monitor) | monitor bank and single step (used by the monitor) | | 97 | — | enter the monitor (what `MONITOR` does) | | 98–105 | memory read and breakpoint registers (used by the monitor) | | | 112–120, 128–135 | sprites (section 7) | sprites (section 7) | | 136 | keys held down, for games (below) | — | | 137 | 1 if the key picked with `OUT 137` is held down, else 0 | pick a key by its scan code | ``` 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) ``` ### Keys held down Typed characters can't tell a game that a key is being *held*: they arrive once, then repeat only after a pause. Ports 136 and 137 read the keyboard directly instead, for as long as a key is down. `INP(136)` adds up these values for the keys held now: | Value | Keys | |---|---| | 1 | up: W, cursor up or keypad 8 | | 2 | down: S, cursor down or keypad 2 | | 4 | left: A, cursor left or keypad 4 | | 8 | right: D, cursor right or keypad 6 | | 16 | fire: Space or either Ctrl | | 32 | Enter | | 64 | either Shift | | 128 | Esc | ``` 10 J = INP(136) 20 IF J AND 4 THEN X = X - 1 30 IF J AND 8 THEN X = X + 1 40 IF J AND 16 THEN PRINT "BANG" ``` For any other key, `OUT 137` its PS/2 scan code (set 2; add 128 for keys whose code starts with E0), then `INP(137)` is 1 while it is held: `OUT 137, 77: IF INP(137) THEN …` checks P. The keys still type characters as well, so a game should throw those away now and then with `IF INP(0) AND 1 THEN K = INP(1)` in a loop. Held keys only work with the board's own keyboard, not with characters sent from the PC. ### 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. The machine-code monitor The monitor stops the Z-80 wherever it is and shows what it is doing: the registers, the instructions at the program counter, the stack and a window of memory. From there you can step through the program one instruction at a time, set a breakpoint, change memory and registers, and carry on. It works on any code, including BASIC itself. ### Getting in and out - Press **Pause/Break** on the keyboard at any time, even when a program has hung, or type `MONITOR` in BASIC. - A breakpoint or a single step also comes back to the monitor. - `X` (or `G`) carries on from where the program stopped. The monitor has a screen of its own: when you leave, BASIC's screen and the graphics come back exactly as they were. ``` Z-80 MONITOR STOPPED BY BREAKPOINT PC F000 SP FF9F AF 0042 BC 0000 DE 8000 HL 8000 IX FFF2 IY FF95 AF'0000 BC'0000 DE'0000 HL'0000 I 00 FLAGS -Z----N- ADDR BYTES INSTRUCTION >*F000 3E 41 LD A,41H STACK F002 D3 01 OUT (01H),A FF9F 5755 F004 C9 RET FFA1 0000 ... MEMORY F000 3E 41 D3 01 C9 00 00 00-00 00 00 00 00 00 00 00 >A.............. ``` - `>` marks the next instruction, which is also highlighted, and `*` the breakpoint. - The flags line shows S Z 5 H 3 P/V N C, with a dash for each flag that is clear. - The stack column shows the words at SP upwards. ### Commands Type a command on the bottom line and press Enter. Numbers are in hex. | Command | Does | |---|---| | Enter (empty line) or `S` | Run one instruction | | `S n` | Run *n* instructions, showing only the last | | `O` | Step over: run a `CALL` or `RST` until it returns, otherwise one step | | `G` or `X` | Carry on (stopping at the breakpoint, if set) | | `G addr` | Carry on from *addr* | | `B addr` | Set the breakpoint; `B` alone clears it | | `D addr` | Show the disassembly from *addr* (`D` alone: from PC) | | `M addr` | Show memory from *addr* | | `E addr bytes…` | Write bytes into memory: `E 8000 3E 41 C9` | | `R reg=value` | Set PC, SP, AF, BC, DE, HL, IX or IY: `R HL=1234` | | `SAVE "NAME" start end` | Save memory *start* to *end* (inclusive) to a file in flash | | `LOAD "NAME"` | Load a memory file back to where it was saved from | | `LOAD "NAME" addr` | Load it at *addr* instead (8000h or above) | | `DIR` | List the files in flash in the memory window (`M` brings the memory back) | | `ASM "NAME"` | Assemble a source file into memory (see the assembler, below) | | `A addr` | Assemble lines as you type them, from *addr*; an empty line ends | | Up / Down | Scroll the disassembly by one instruction | | Page Up / Page Down | Scroll the memory window | | `?` | A short reminder of the commands | | `:` *record* | An Intel HEX record, written into memory (`tools/send-hex.py` sends whole files this way; see section 12) | - **Stepping** runs exactly one instruction (a whole `LDIR`, or a `HALT` and what wakes it). The hardware counts instructions, so it works on code in ROM as well as RAM. - **The breakpoint** is checked by hardware before each instruction, so it also works in ROM and costs no speed. When you carry on from the breakpoint itself, the monitor first steps past it. - **Memory below 8000h** is BASIC's ROM and can be viewed but not changed. `E` says so if you try. - **The disassembler** shows every instruction, including the undocumented ones (`IXH`, `SLL`, `IN (C)`, `RES 0,(IX+5),B` and so on), in Zilog syntax with hex numbers like `3EH` and `0C000H`. ### A machine-code example ``` POKE 61440,62: POKE 61441,65: POKE 61442,211: POKE 61443,1: POKE 61444,201 MONITOR ``` The `POKE`s put `LD A,41H : OUT (1),A : RET` at F000h; it prints an `A`. In the monitor, `B F000` then `X`. Back in BASIC, `CALL 61440` stops at the breakpoint. Press Enter to step through each instruction, or `X` to let it finish. ### The assembler The monitor can assemble Z-80 source code into memory, either a whole file or one line at a time. **Writing source.** Type it into BASIC as numbered lines, just like a program, and save it. BASIC doesn't run it; it just keeps the lines. The assembler ignores the line numbers, and uses them in its error messages. ``` NEW 10 ; PRINT A MESSAGE 20 ORG 0F000H 30 START: LD HL,MSG 40 LOOP: LD A,(HL) 50 OR A 60 RET Z 70 LD C,A 80 WAIT: IN A,(0) ; CAN THE SCREEN TAKE A CHARACTER? 90 AND 2 100 JR Z,WAIT 110 LD A,C 120 OUT (1),A 130 INC HL 140 JR LOOP 150 MSG: DB "HELLO FROM ASSEMBLY",13,10,0 SAVE "HELLO" ``` A text file sent from the PC with `tools/send-bas.py` works the same way, as long as each line starts with a number. **Assembling.** `MONITOR`, then `ASM "HELLO"`. The monitor says `ASSEMBLED F000-F028` and shows the code; errors are listed in the memory window with their line numbers. Back in BASIC (`X`), `CALL 61440` runs it. Or set a breakpoint first and step through it. **One line at a time.** `A F100` starts the line assembler at F100h: type an instruction, press Enter, and it is assembled and shown, then the next address is offered. An empty line ends. Labels from the last `ASM` can be used. **Syntax**: Zilog mnemonics, as the disassembler shows them. | | | |---|---| | Labels | `NAME:` before an instruction, up to 8 letters and digits; `NAME EQU value` for constants | | Numbers | `123`, `0FFH`, `$FF`, `0x1F`, `1010B`, `'A'`; `$` alone is the current address | | Expressions | `+ - * / & |` and brackets: `LD BC,END-START`, `LD A,'Z'-1` | | Memory operands | an operand all in brackets: `LD A,(COUNT)`, `LD (IX+5),A`, `LD A,(IX)` | | `ORG addr` | assemble from *addr* (F000h if there is no `ORG`) | | `DB` / `DEFB` / `DEFM` | bytes and `"strings"`: `DB "HI",13,10,0` | | `DW` / `DEFW` | 16-bit words, low byte first | | `DS n` / `DEFS n` | skip *n* bytes | | `END` | stop here | | `;` | comment to the end of the line | - **Instructions:** every Z-80 instruction is accepted, including the undocumented ones (`IXH`, `SLL`, `IN (C)`). The exception is the three-operand `RES 0,(IX+d),B` forms. `SUB A,n` is accepted for `SUB n`, and likewise for `AND`, `XOR`, `OR` and `CP`. - **Where code can go:** the code must go at 8000h or above. F000h–F3F7h is the safe place, since BASIC doesn't use it. - **Labels:** up to 300. - **Typing source into BASIC:** BASIC turns lower case to upper case (except inside double quotes), so `'a'` becomes `'A'`. Indentation after the line number isn't kept, so labels need their colon. **Errors:** `UNKNOWN INSTRUCTION`, `BAD OPERANDS` (no such form), `UNDEFINED LABEL`, `DUPLICATE LABEL`, `JUMP TOO FAR` (a `JR`/`DJNZ` beyond −128..127), `VALUE OVER 255`, `OFFSET OUT OF RANGE`, `CAN'T WRITE BELOW 8000H`, `BAD NUMBER`, `BAD EXPRESSION`. ### How it works Pause, `MONITOR`, a breakpoint or the step counter raises the Z-80's non-maskable interrupt (NMI). 1. **Entry:** the NMI pushes the program counter and jumps to 0066h. A few bytes there switch in the monitor's own 32 KB memory bank, which replaces 0000–7FFF. 2. **Reading memory:** the monitor reads the program's memory below 8000h through a debug port. 3. **Leaving:** the monitor switches the bank out and returns. To single-step, it also tells the hardware to raise the NMI again after one instruction. The monitor takes no memory from BASIC; its bank also has room for an assembler. ## 11. Files in the 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. ### Saving programs | 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 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 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 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 12; `--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) ``` ### Memory files A memory file holds a block of memory, for machine code or data: its address (2 bytes) followed by the bytes, the same format as a C64 program file. The monitor's `SAVE`/`LOAD` (section 10) and BASIC's statements below read and write the same files. | Statement | Does | |---|---| | `BSAVE "NAME", start, length` | Save *length* bytes from *start* | | `BLOAD "NAME"` | Load them back to the address they came from | | `BLOAD "NAME", address` | Load them at *address* instead | ``` BSAVE "CODE", 61440, 5 BLOAD "CODE", 61952: CALL 61952 ``` Only memory from 8000h up can be loaded into. A memory file is up to 32 KB. Don't `LOAD` one as a program: it isn't text. ### 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 stop the board from starting, even one that sends commands to the flash itself with `OUT` (ports 64 and 65, section 9). ## 12. 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: `00` 115200, `01` 9600, `10` 921600, `11` 3,000,000. The tools take `--baud` with any of these; 3,000,000 is the fastest and works fine, since the board paces the PC with XON/XOFF. The examples below use 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. **Sending machine code compiled on the PC:** ``` tools/send-hex.py prog.ihx --save PROG --baud 3000000 ``` This enters the monitor, sends the Intel HEX file (as SDCC and most assemblers write it) a record at a time, saves the bytes as the memory file `PROG`, and goes back to BASIC. `BLOAD "PROG"` then loads it where it was compiled for. It must be at 8000h or above. That's how The Iron Keep (section 14) gets onto the board. 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. ## 13. 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, 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 | | `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 | | `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` | ## 14. 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. ### The Iron Keep A game in machine code. You are a prisoner in a castle of twelve rooms: steal the king's crown from the throne room and escape down the stairs. Guards patrol, and shoot when they can see you along a row or column of the castle; some come after you. Keys open locked doors, chests hold gold, crates hold ammunition. You have three lives. ``` RUN "KEEP" ``` - **Moving:** the cursor keys or W A S D. **Shooting:** Space or Ctrl, in the direction you face. - **P** pauses; **Esc** gives up the game. Esc on the title or the final screen goes back to BASIC. - **Score:** 100 a chest, 50 a guard, 1,000 for the crown, and 500 plus 200 a remaining life for getting out. `KEEP` is a four-line BASIC program that loads the game, the memory file `KEEPGAME`, at 8600h, just past itself, and `CALL`s it. The game overwrites the rest of BASIC's program area while it runs, so save your own program first. It is written in C (`games/keep/` on the PC, with its build and install steps). ## 15. Limits at a glance | Item | Limit | |---|---| | Program and arrays together | about 20.5 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 | | Sprites | 32 on screen, 64 shapes, 16 × 16 pixels each | | Text | 80 × 32, or 132 × 64 | | Files in flash | 64, 1,784 KB in all, 32 KB each | | Open data files | 3 |