Files
Basys3RiscV/docs/basic-manual.md
T
brad ArantandClaude Opus 5.5 bda9bb67b6 Add a 640x480 two-colour graphics mode; start in white
The graphics memory doubles as 640x480 at a bit a pixel (port 38), four
pixels to an entry, plotted by read-modify-write, in two colours from
port 39 (0 transparent). BASIC gets SCREEN 0 / SCREEN 1 [,set[,clear]];
a plain fill (as every game does) returns to 320x240 and BASIC follows.
The text now starts in white (SW5:4 = 00; 10 is green). The README is
rewritten to stand on its own.

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

1446 lines
56 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Basys 3 RISC-V BASIC
*A Dartmouth-style BASIC with colour graphics, for the RISC-V computer inside
the Basys 3 VT220 terminal.*
## 1. Getting started
The computer 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 computer |
| SW14 | — | Link the PC's serial port to the computer 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 RISC-V ON A BASYS 3
READY
```
The computer 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 computer; 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.
- **Left** and **Right** move the cursor along the line; **Home** and **End**
(or Ctrl-A and Ctrl-E) jump to its start and end. What you type goes in at
the cursor.
- **Up** brings back the last line you entered, with the cursor at its end.
- **Backspace** rubs out the character before the cursor, **Delete** the one
under it.
- **Ctrl-U** erases the whole line.
- **Enter** takes the whole line, wherever the cursor is.
Lines can be up to 250 characters. Lower case is accepted and turned into upper
case, except inside quotes.
### Editing a program
- To change a line, type its number and press **Right**: each press copies
one more character of the old line, as if you were retyping it. **End**
copies the rest of it at once. While copying, anything you type goes in
as new text, and **Delete** skips a character of the old line, so to
change a word, copy up to it, press Delete once for each old letter, and
type the new one. Enter takes the line as it now stands: whatever has not
been copied yet is left off, so press End first to keep it. If there is no
such line, Right and End do nothing.
- To copy a line to a new number, type the old number, press End, then Home,
Delete the old number and type the new one.
- To replace a line, you can also type it again with the same number.
- To delete a line, type its number alone.
```
10 PRINT "HELO"
10→→→→→→→→→→→ copies 10 PRINT "HEL
L End Enter now it is 10 PRINT "HELLO"
```
- 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) |
| `RENUM` | Renumber the program 10, 20, 30… (see below) |
| `RENUM 100, 5` | Renumber it 100, 105, 110… |
| `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 |
`RENUM` gives the lines new numbers, starting at 10 (or the first number
given) and going up in tens (or the second). It also changes the line numbers
after `GOTO`, `GOSUB`, `THEN`, `RUN` and `ON … GOTO`/`GOSUB` so the program
runs as before. A number that isn't a line in the program is left alone.
Numbers inside quotes, `REM` and `DATA` are left as they are, and so is a
line number worked out at run time. If the new numbers would pass 65535, or
a line would grow too long or the program run out of memory, `RENUM` stops
with an error and changes nothing. Like any change to the program, it clears
the variables.
## 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$
```
String arrays work like numeric ones, with a `$` after the letter. Each element
holds up to 79 characters and starts empty:
```
10 DIM N$(4)
20 FOR I = 0 TO 4: READ N$(I): NEXT I
30 PRINT N$(2)
40 DATA RED, GREEN, BLUE, YELLOW, WHITE
```
`N$`, `N$( )` and `N( )` are all separate. A string array used without `DIM`
gets subscripts 0 to 10. Every element takes 80 bytes whether it is used or
not, so a string array can have at most 255 elements, and `DIM A$(200)` uses
about 16 KB of the program space.
## 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), N$(30)
```
See section 3. A numeric array can hold at most 6000 elements, a string array
255.
### 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
computer 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, called the standard
RISC-V way: it must end with `RET` and leave `SP`, `GP`, `TP`, `S0`–`S11` and
the float registers `FS0`–`FS11` as it found them (`A0`–`A7`, `T0`–`T6` and the
other float registers are free to use). `MONITOR` stops BASIC in the
machine-code monitor (section 10). See section 9 for memory and ports.
### Graphics and text placement
`CLS`, `SCREEN`, `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 computer 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; 0 or 1 in `SCREEN 1`) |
| `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**,
or, after `SCREEN 1`, **640 by 480 in two** (see below). It is mixed with the
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 4×4 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
```
### 640 × 480 in two colours
The same graphics memory holds 640 × 480 pixels at one bit each, twice the
detail across and down in two colours:
| Statement | |
|---|---|
| `SCREEN 1 [, S [, C]]` | 640 × 480: *X* 0–639, *Y* 0–479, each pixel a 2×2 block on the monitor. Set pixels show in colour *S* (15, white, if left out), clear ones in *C* (0, transparent, if left out) |
| `SCREEN 0` | Back to 320 × 240 in 16 colours (the mode at power-up) |
Both clear the graphics. In `SCREEN 1` every drawing statement sets pixels
in any colour but 0 and clears them in colour 0, so `COLOR`, `PLOT`, `LINE`,
`RECT`, `FILL` and `CIRCLE` work unchanged; `POINT` gives 1 or 0. `CLS` clears
the graphics and stays in the mode. With a clear colour other than 0 the whole
picture area is that colour, under the text.
```
10 SCREEN 1, 10
20 FOR A = 0 TO 6.28 STEP .02
30 LINE 320, 240, 320 + 300*COS(A), 240 + 230*SIN(3*A)
40 NEXT A
```
The mode doesn't scroll (the scroll registers and the border are ignored).
Sprites still work, on the 320 × 240 grid, and a sprite counts as touching
the graphics where a set pixel is within the 4 × 1 group of pixels under it. A
game started with `CALL` goes back to 320 × 240; BASIC notices.
### 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 computer 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 computer. `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.
### Scrolling
The hardware can scroll the graphics: it shows them starting from any point of
the 320 × 240 picture, wrapping round at the edges, so the whole picture moves
without anything being redrawn. Sprites and text don't move with it.
| Port | `OUT` |
|---|---|
| 53 | X of the picture to show at the left edge, `X AND 255` |
| 54 | `INT(X / 256)`, plus 2 to hide the edges (below) |
| 55 | Y of the picture to show at the top, 0–239 |
```
10 CLS: FOR I = 0 TO 15: FILL I * 20, 0, I * 20 + 19, 239, I: NEXT I
20 FOR X = 0 TO 319
30 OUT 53, X AND 255: OUT 54, INT(X / 256)
40 F = INP(120)
50 IF INP(120) = F THEN 50
60 NEXT X
```
A program that scrolls a long scene has to draw the strip that comes into view
at one edge each time. To do that unseen, add 2 to the value sent to port 54:
the graphics are then hidden in a border, 4 pixels wide at the sides and 2 at
the top and bottom, and the new strip can be drawn there while it is hidden.
Bastion Raid (section 14) works this way. `PLOT`, `LINE` and the rest still use
the picture's own coordinates. `CLS` puts the scroll back to 0 and turns the
border off.
### 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 starts at 132 columns by 64 rows in the 8×16 font.
`PRINT CHR$(27);"[?3l"` switches to 80 columns by 32 rows in a font twice the
size (and clears it), `CHR$(27);"[?3h"` back to 132; `INP(0) AND 4` is 4 at
132 columns. The line editor follows the change, and the games play at 80
columns and put the screen back as they found it. 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 |
|---|---|
| 00000–09FFF | BASIC itself (writes here are ignored) |
| 0A000–0F0B7 | Your program and arrays (machine-code games load at 0A200h, 41472) |
| 0F0B8–11FFF | BASIC's variables and file buffers |
| 12000–12FFF | Free for your machine code (4 KB); BASIC never uses it |
| 13000–13FF7 | The stack |
| 13FF8–13FFF | The clock set by `DATE` |
| 20000–27FFF | The monitor (section 10); writes are ignored |
| 28000–29FFF | The monitor's variables |
| FFFFFE00–FFFFFEFF | 32-bit hardware registers (below) |
| FFFFFF00–FFFFFFFF | The I/O ports: port *N* is at FFFFFF00h + *N* |
`PEEK` can read anything; `POKE` can change RAM from 0A000h up, including
BASIC's own data, so put machine code at **12000h (73728) to 12FFFh**, which is
kept free for it. Memory is byte-addressed and instructions are 4 bytes, low
byte first.
The I/O ports below are also memory: `INP(P)` is `PEEK(-256 + P)` and `OUT P, V`
is `POKE -256 + P, V`. Machine code reaches a port in one instruction, relative
to register `ZERO`: `LBU A0,-256(ZERO)` reads port 0 and `SB A0,-255(ZERO)`
writes port 1. The 32-bit registers at FFFFFE00h + *N* (machine code only) are:
0 milliseconds since reset, 4 microseconds since reset, 8 the timer interrupt's
compare value, 10h and 14h the monitor's breakpoint addresses.
### I/O ports
| Port | `INP` | `OUT` |
|---|---|---|
| 0 | bit 0: a key is waiting; bit 1: the screen can take a character; bit 2: the screen is 132 columns wide | — |
| 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; X bits 8–9 (1, 2) and Y bit 8 (4); Y low byte |
| 51 | colour at X, Y (0 or 1 in 640 × 480) | plot a pixel at X, Y and move right (in 640 × 480 any colour but 0 sets it) |
| 52 | bit 0: screen fill in progress | fill the whole graphics layer with a colour; also hides the sprites, resets the scroll and goes back to 320 × 240, unless 128 is added |
| 53, 54, 55 | — | graphics scroll and border (section 7) |
| 56 | bit 0: 640 × 480 mode | 1: 640 × 480 in two colours, 0: 320 × 240 in 16 |
| 57 | — | 640 × 480 colours: set pixels' colour + 16 × clear pixels' colour |
| 64 | bit 0: flash byte in progress; bit 1: last flash command refused | 1 selects the flash and starts a command, 0 ends it |
| 65 | the byte the flash sent back during the last `OUT 65` | a byte to the flash |
| 96 | why the monitor was entered (used by the monitor) | single step (used by the monitor) |
| 97 | — | enter the monitor (what `MONITOR` does) |
| 103 | — | breakpoints on and off (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 |
| 144–157 | voice volumes now (152–154) | sound (below) |
```
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.
### Sound
The board has no speaker of its own. Plug a Digilent **PmodAMP2** into the
top row of Pmod header **JA** (pin 1 at the end marked 1) and headphones or a
powered speaker into its jack. The FPGA has a little sound chip in the style
of the 8-bit computers: three voices that play square-wave tones, a noise
source they can use instead or as well, sixteen volumes and an envelope for
each voice, so a note or a bang fades away by itself.
| Port | `OUT` |
|---|---|
| 144, 145 | voice 0 pitch: low byte, then high byte (0–15) |
| 146, 147 | voice 1 pitch |
| 148, 149 | voice 2 pitch |
| 150 | noise pitch, 0–31 (higher is lower and rougher) |
| 151 | mixer: add 1, 2, 4 for the tone of voice 0, 1, 2 and 8, 16, 32 for noise on voice 0, 1, 2 |
| 152, 153, 154 | voice 0, 1, 2 volume, 0 (off) to 15, which starts its envelope; `INP` gives the volume it has got to |
| 155, 156, 157 | voice 0, 1, 2 envelope: attack × 16 + decay, each 0–15 |
- **Pitch** = 125000 ÷ frequency: 284 is the A above middle C (440 Hz),
477 middle C. Each voice goes from about 30 Hz up beyond hearing.
- **Envelope:** with an attack, the volume climbs from 0 to the volume set,
one step every attack × 4 ms; then, with a decay, it falls back to 0 one step
every decay × 4 ms. 0 means no climb, or hold the volume until it is
changed. An envelope of 3 plays a short note; 8 with noise is an explosion.
- **Waiting for a sound to end:** `IF INP(152) > 0 THEN …` loops until voice
0 has faded out.
- A voice that has neither its tone nor noise on in the mixer gives a steady
level, so changing its volume clicks; that is how the old chips played
samples.
- `CLS` silences everything (as does restarting the computer).
```
10 OUT 151, 1: OUT 155, 3 : REM TONE ON VOICE 0, A SHORT NOTE
20 OUT 144, 28: OUT 145, 1: OUT 152, 15 : REM PITCH 284 = 440 HZ
```
`basic/examples/sound.bas` plays a scale, a laser, an explosion and a chord.
### Speed
The processor is a 32-bit RISC-V (RV32IMF: the base instructions, multiply
and divide, and single-precision floating point) running at 90 MHz. Most
instructions take 2 clocks; loads, stores, jumps and taken branches 3, a
multiply 4 and a divide 35, which comes to about 2.5 clocks per instruction in
BASIC, some 36 million instructions a second. Its floating-point unit adds,
subtracts and multiplies in 12 clocks and divides or takes a square root in 36,
correctly rounded. In round numbers:
| Operation | Time |
|---|---|
| One pass of an empty `FOR … NEXT` loop | 8 µs (about 120,000 a second) |
| `X = I * 1.5` | 26 µs |
| `Y = SIN(X)` | 37 µs |
| `LINE` right across the screen | 0.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 processor 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.
- So does a program that goes wrong: an illegal instruction, a misaligned load,
store or jump, an `EBREAK` or `ECALL`, or an interrupt with no handler. The
title line says which (`STOPPED BY ILLEGAL INSTRUCTION`). After `EBREAK` and
`ECALL` the PC is already past them, so `X` carries on.
- `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.
```
RISC-V MONITOR STOPPED BY BREAKPOINT
PC 00012000 RA 000058B4 SP 00013F70 GP 0001189C TP 00000000 T0 00000000
T1 00000000 T2 00000000 S0 00013FB0 S1 0000A01E A0 00000000 A1 00012000
...
ADDR WORD INSTRUCTION STACK
>*12000 04100513 LI A0,65 13F70 00000000
12004 F0A000A3 SB A0,-255(ZERO) 13F74 0000A01E
12008 00008067 RET ...
MEMORY
12000 13 05 10 04 A3 00 A0 F0-67 80 00 00 00 00 00 00 ....g...........
```
- The registers are the PC and X1–X31 by their usual names (RA, SP, GP, TP,
T0–T6, S0–S11, A0–A7); X0 (ZERO) is always 0.
- `>` marks the next instruction, which is also highlighted, and `*` the
breakpoint.
- 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 (`JAL` or `JALR` that saves its return address in RA) 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 12000 13 05 10 04` |
| `R reg=value` | Set PC or a register, by name or number: `R A0=1234`, `R X10=1234`; a float register as its bit pattern: `R F1=3FC00000` (1.5), or `R FCSR=0` |
| `F` | Show the float registers F0–F31 and FCSR, as bit patterns, in the memory window (`M` brings the memory back) |
| `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 (0A000h 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 of the program. The hardware
counts it, so stepping works on code in ROM as well as RAM.
- **The breakpoint** is checked by hardware as each instruction starts, 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 0A000h** is BASIC's ROM and can be viewed but not changed. `E`
says so if you try.
- **The float registers** are saved and put back like the others, while the
FPU is on (`mstatus.FS`, which BASIC turns on); `F` says when it is off.
- **The disassembler** shows every RV32IMF instruction and the CSR and system
instructions, using the usual short forms where they apply (`LI`, `MV`, `J`,
`RET`, `BEQZ`, `CSRR` and so on), with hex numbers like `1F0H` and `0A200H`;
anything else is shown as `DW` and its value.
### A machine-code example
```
10 FOR I = 0 TO 11: READ B: POKE 73728 + I, B: NEXT I
20 DATA 19,5,16,4, 163,0,160,240, 103,128,0,0
RUN
MONITOR
```
The `POKE`s put `LI A0,65 : SB A0,-255(ZERO) : RET` at 12000h; it prints an
`A` (port 1 is at -255 from address 0). In the monitor, `B 12000` then `X`.
Back in BASIC, `CALL 73728` stops at the breakpoint. Press Enter to step
through each instruction, or `X` to let it finish.
### The assembler
The monitor can assemble RISC-V 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 12000H
30 START: LA A1,MSG
40 LOOP: LBU A0,0(A1)
50 BEQZ A0,DONE
60 WAIT: LBU T0,-256(ZERO) ; CAN THE SCREEN TAKE A CHARACTER?
70 ANDI T0,T0,2
80 BEQZ T0,WAIT
90 SB A0,-255(ZERO)
100 ADDI A1,A1,1
110 J LOOP
120 DONE: RET
130 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 12000-12041` and shows the code; errors are listed in the memory
window with their line numbers. Back in BASIC (`X`), `CALL 73728` runs it.
Or set a breakpoint first and step through it.
**One line at a time.** `A 12100` starts the line assembler at 12100h: 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**: as the disassembler shows it.
| | |
|---|---|
| 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: `LI A0,END-START`, `LI A1,'Z'-1` |
| Registers | `X0`–`X31` or `ZERO RA SP GP TP T0`–`T6 S0`–`S11 FP A0`–`A7` |
| Memory operands | *offset*`(`*register*`)`: `LW A0,8(SP)`, `SB A0,-255(ZERO)`, `LBU T0,(A1)` |
| CSRs | by name (`MSTATUS`, `MEPC`, `MCAUSE`, `CYCLE`, `TIME`, `INSTRET`, …) or number |
| `ORG addr` | assemble from *addr* (12000h if there is no `ORG`) |
| `DB` / `DEFB` / `DEFM` | bytes and `"strings"`: `DB "HI",13,10,0` |
| `DH` | 16-bit halfwords, low byte first |
| `DW` / `DEFW` | 32-bit words, low byte first |
| `DS n` / `DEFS n` | skip *n* bytes |
| `ALIGN n` | skip to a multiple of *n* (instructions must be on a multiple of 4) |
| `END` | stop here |
| `;` | comment to the end of the line |
- **Instructions:** all of RV32I and M, `CSRRW`…`CSRRCI`, `ECALL`, `EBREAK`,
`MRET`, `MNRET`, `WFI`, `FENCE`, `FENCE.I`, and the short forms `NOP`, `LI`,
`LA`, `MV`, `NOT`, `NEG`, `SEQZ`, `SNEZ`, `SLTZ`, `SGTZ`, `J`, `JR`, `JAL`
*target* (saving RA), `JALR` *register*, `RET`, `CALL`, `BEQZ`, `BNEZ`,
`BLEZ`, `BGEZ`, `BLTZ`, `BGTZ`, `BGT`, `BLE`, `BGTU`, `BLEU`, `CSRR`, `CSRW`,
`CSRS`, `CSRC`, `CSRWI`, `CSRSI`, `CSRCI`.
- **Floating point:** `FLW`, `FSW`, `FADD.S`, `FSUB.S`, `FMUL.S`, `FDIV.S`,
`FSQRT.S`, `FMADD.S`, `FMSUB.S`, `FNMSUB.S`, `FNMADD.S`, `FMIN.S`, `FMAX.S`,
`FSGNJ.S`, `FSGNJN.S`, `FSGNJX.S` (and `FMV.S`, `FNEG.S`, `FABS.S`), `FEQ.S`,
`FLT.S`, `FLE.S`, `FCVT.W.S`, `FCVT.WU.S`, `FCVT.S.W`, `FCVT.S.WU`, `FMV.X.W`,
`FMV.W.X`, `FCLASS.S`. Float registers are `F0`–`F31` or `FT0`–`FT11`,
`FS0`–`FS11`, `FA0`–`FA7`; a rounding mode (`RNE`, `RTZ`, `RDN`, `RUP`, `RMM`)
may follow the operands, `FADD.S FA0,FA1,FA2,RTZ`, and without one the
instruction uses FCSR's (round to nearest unless changed). CSRs `FFLAGS`,
`FRM` and `FCSR`.
- **`LI`** is one instruction (`ADDI`) for a value from −2048 to 2047 that is
known by then, otherwise two (`LUI`, `ADDI`); **`LA`** is always two
(`AUIPC`, `ADDI`); **`CALL`** is `JAL RA`, which reaches 1 MB either way.
- **Where code can go:** RAM from 0A000h up. 12000h–12FFFh is the safe place,
since BASIC doesn't use it.
- **Labels:** up to 200.
- **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 REGISTER`, `MISSING OPERAND`, `TOO
MANY OPERANDS`, `OFFSET(REGISTER)`, `UNDEFINED LABEL`, `DUPLICATE LABEL`,
`VALUE OUT OF RANGE` (an immediate, offset or `LUI` value that doesn't fit),
`BRANCH TOO FAR` (beyond ±4 KB), `JUMP TOO FAR` (beyond ±1 MB), `NOT ON A
WORD: USE ALIGN 4`, `CAN'T WRITE THERE`, `BAD NUMBER`, `BAD EXPRESSION`.
### How it works
Pause, `MONITOR`, a breakpoint or a single step raises the processor's
non-maskable interrupt (NMI); a trap with nowhere else to go comes to the same
place, because BASIC points the trap vector (`mtvec`) at the monitor.
1. **Entry:** the NMI saves the program counter in `mnepc` and jumps to the
monitor at 20000h, which saves every register and shows them. NMIs are
switched off while the monitor runs.
2. **Memory:** the monitor runs from its own 32 KB of ROM at 20000h, with its
variables at 28000h, so it reads the program's memory directly and takes
none of BASIC's.
3. **Leaving:** the monitor puts the registers back and returns with `MNRET`.
To single-step, it first tells the hardware to raise the NMI again after
one instruction of the program has run.
## 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 computer 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
(4 bytes, low first) followed by the bytes. 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", 73728, 12
BLOAD "CODE", 74240: CALL 74240
```
Only RAM from 0A000h 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 computer: 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 `objcopy -O ihex` 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 0A000h 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 (also from `RENUM`) |
| `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`, a `RENUM` past 65535 or with a step of 0 |
| `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 0A200h, 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).
### Bastion Raid
An isometric scrolling shooter, also in machine code. Fly over a fortress that
scrolls towards you and destroy the reactor core at its far end.
```
RUN "RAID"
```
- **Up and down** climb and dive; **left and right** steer across the
fortress; **Space** or **Ctrl** fires straight ahead.
- **Walls:** climb over the low ones. The tall ones are too high: fly low
through the doorway, the gap with the bright lintel.
- **Height:** your shadow on the floor and the ALT bar show how high you are.
Shots only hit things on the ground when you fly low.
- **Fuel** runs down; shoot the red fuel tanks to fill up. Turrets fire at you
when you are in front of them, and between the two fortresses fighters come
at you at all heights.
- **Score:** 100 a turret, 150 a fuel tank, 300 a radar dish, 200 a fighter,
2,000 for the reactor and 500 for each level. At each level the turrets fire
sooner and the fighters come more often.
- **P** pauses; **Esc** gives up, and Esc at the title goes back to BASIC.
`RAID` loads the memory file `RAIDGAME` at 0A200h, like `KEEP`. The game draws
the fortress pixel by pixel into the scrolled graphics, two new columns and a
row each frame, and everything that moves is a sprite (`games/raid/` on the
PC).
### Star Warden
A planet defence game in machine code, scrolling left and right round a
planet. Landers come down to snatch the humanoids walking on the ground and
carry them up; one that gets a humanoid to the top turns into a mutant that
hunts you. Shoot the landers, and catch the humanoids they drop before they
hit the ground.
```
RUN "WARDEN"
```
- **Left and right** fly that way, with momentum, and turn the ship round;
**up and down** climb and dive; **Space** or **Ctrl** fires the laser.
- **Shift** sets off a smart bomb, which destroys everything on the screen
(three to start with); **Enter** jumps into hyperspace, somewhere at random.
- **The scanner** across the top shows the whole planet with your ship in the
middle: landers green, mutants magenta, bombers blue, humanoids as dots.
- **Bombers** drift across and leave mines. A humanoid dropped from high up
dies when it lands; catch it on the way down for 500.
- **Waves** end when every enemy is gone, with a bonus for each humanoid
still alive. If they are all lost, every lander becomes a mutant; the
humanoids come back every fifth wave.
- **Score:** 150 a lander or mutant, 250 a bomber, 50 a mine, 500 a humanoid
caught, 250 for one landing safely. A new ship and smart bomb every 10,000.
- **P** pauses; **Esc** gives up, and Esc at the title goes back to BASIC.
`WARDEN` loads the memory file `WARDGAME` at 0A200h. The planet is 1,280 pixels
round, four times the graphics' width, so the game scrolls the graphics and
draws each column of mountains and stars as it comes into view
(`games/warden/` on the PC).
### Star Swarm
An alien swarm sways in formation across the top of the screen, and its
members peel off in looping dives at your ship, firing as they come. Those
that miss loop round and fly back into their places.
```
RUN "SWARM"
```
- **Left and right** move the ship; **Space** or **Ctrl** fires. You have one
shot in the air at a time, so make it count.
- **The swarm:** blue drones, purple warriors, red escorts and two yellow
flagships at the top. A flagship dives with up to two escorts; shoot both
escorts before the flagship for 800.
- **Score:** each alien is worth twice as much diving as in formation:
drones 30 / 60, warriors 40 / 80, escorts 50 / 100, flagships 60 / 150
(300 with an escort still flying). A new ship every 7,000.
- **Waves:** clear the swarm and a new one arrives, diving more often and
more of them at once.
- **P** pauses; **Esc** gives up, and Esc at the title goes back to BASIC.
`SWARM` loads the memory file `SWARMGAM` at 0A200h. The 46 aliens are more than
the 32 sprites, so the formation is drawn into the graphics, and its sway is
the hardware scroll; a diving alien is wiped from the graphics and flies as a
sprite until it is back in its place (`games/swarm/` on the PC).
### Crystal Cavern
A maze chase. You are a miner gathering the crystals in a cave, chased by four
bats; gather every crystal to reach the next, faster cave.
```
RUN "CAVERN"
```
- **The cursor keys** or **W A S D** steer the miner. Hold a direction before
a junction and it turns there; it can turn back at any time.
- **The bats** each hunt their own way: the red one comes straight for you,
the magenta one heads you off, the green one works with the red, and the
orange one keeps its distance. Now and then they all break off and go to
their corners for a while.
- **Lanterns** (the four yellow lights) scare the bats blue for a few seconds:
catch them then, and their eyes fly back to the roost in the middle. They
flash white just before they recover.
- **The side tunnels** wrap round to the other side; bats are slow in them.
- **Score:** 10 a crystal, 50 a lantern, 200, 400, 800 and 1,600 for bats
caught on one lantern, and a gold nugget (500 a cave) that appears twice a
cave where you started. An extra life every 10,000.
- **P** pauses; **Esc** gives up, and Esc at the title goes back to BASIC.
`CAVERN` loads the memory file `CAVEGAME` at 0A200h. The maze was made by
`gen.py`, which joins up a grid of junctions and takes links away at random
while keeping the cave connected, mirrored and free of dead ends
(`games/cavern/` on the PC).
## 15. Limits at a glance
| Item | Limit |
|---|---|
| Program and arrays together | about 20.2 KB |
| Line numbers | 0 – 65535 |
| Line length | 250 characters typed |
| Numeric variables | A–Z and A0–Z9 |
| String variables | A$–Z$, 79 characters each; string arrays A$( )–Z$( ), up to 255 elements |
| 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 in 16 colours, or 640 × 480 in 2 |
| 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 |