CB2 micro
BASIC programming language reference manual
Go back to the main site
About this manual

This manual is a reference to the BASIC programming language for the CB2 micro. It covers everything you will beed to know when you want to write your own BASIC programs.


Quick index reference


Click on a word in the table below to navigate to the relevant section of the manual. Then use "back" on your browser to return to this table.


BASIC reference (1) - Basics

BASIC reference (2) - Graphics and Sound

BASIC reference (3) - Input/Output and files

1 General

2 Numbers, variables and functions

3 Value assignment
3.1 ASHIFT v,n
3.2 LIMIT v,min,max [LIM]
3.3 SCALE Variable,Y0,Y1,X0,X,X1
3.4 DATA offset,value1,value2... [DA]
3.5 ACOPY source,dest,num... [AC]
3.6 TLEN var,ptr
3.7 TFIND var,ptr1,ptr2
3.8 DBIT(N)


4 Program control
4.1 BREAK
4.2 END
4.3 GOTO n [GO]
4.4 IF - THEN
4.5 FOR - NEXT
4.6 REPEAT - UNTIL [REP - UNT]
4.7 GOSUB [GOS]
4.8 RETURN [RET]
4.9 CALL
4.10 LFIND V,n
4.11 VID n
4.12 The system variables
4.13 Extensions


5 Screen output
5.1 COLOR F(,B) [COL]
5.2 CLS
5.3 BORDER B [BO]
5.4 POS Y,X
5.5 WRAP n
5.6 PRINT [?]
5.7 CBOX Y1,X1,Y2,X2
5.8 FRAME Y1,X1,Y2,X2
5.9 HFRAME Y1,X1,Y2,X2
5.10 IBOX Y1,X1,Y2,X2
5.11 SCROLL n
5.12 GETCHAR variable,Y,X [GCH]
5.13 GETATTR variable,Y,X [GAT]


6 keyboard
6.1 INPUT [INP]
6.2 CTEXT adr,anz
6.3 The Keycodes
6.4 The function KEY


7 Time
7.1 WAIT n
7.2 SYNC n
7.3 TSET n
7.4 TGET V
7.5 ONSYNC L,N


8 Error messages and error handling
8.1 ONERR N
8.2 ERR(n)
8.3 Error messages
1 Graphic
1.1 Pseudographic in text mode
1.2 Video mode 1
1.3 Video mode 2
1.4 Video mode 3
1.5 video mode 5
1.6 VMODE n [VM]
1.7 PALETTE start,c1(,c2,c3,c4,c5,c6) [PAL]
1.8 PLOT Y,X(,C) [PL]
1.9 DRAWTO Y2,X2(,C) [DTO]
1.10 DRAW Y1,X1,Y2,X2(,C) [DR]
1.11 BOX Y1,X1,Y2,X2(,C)
1.12 FBOX Y1,X1,Y2,X2(,C)
1.13 CIRCLE Y,X,RY,RX(,C) [CI]
1.14 FCIRCLE Y,X,RY,RX(,C) [FCI]
1.15 ARC Y,X,RY,RX,W1,W2(,C)
1.16 PIE Y,X,RY,RX,W1,W2(,C)
1.17 GETPIX variable,Y,X [GPX]
1.18 BCOPY [BC]
1.19 PRINT [?]
1.20 FONT n

2 Sprites
2.1 Defining sprites
2.2 SPRITE n,y,x [SPR]


3 Audio
3.1 NOTE n [NO]
3.2 NOTE n,v [NO]
3.3 VOL n

3.4 PLAY start,stop,speed,loops

3.5 PSTAT(mode)

1 Input and output via the parallel port
1.1 DIR n
1.2 OUT n,b
1.3 The function IN(n)
1.4 The function ADC(n)
1.5 The function SPI(n)
1.6 SPISEL n


2 Communication
2.1 SPUT a,b...
2.2 SGET V
2.3 BAUD n
2.4 ESPUT a,b...
2.5 ESGET V
2.6 EBAUD n
2.7 PUMP n
2.8 XSEND n,a
2.9 XREC(a)
2.10 ICOMM adr,start,num [IC]


3 Memory
3.1 EPOKE adr,dat [EP]
3.2 EPEEK(adr)
3.3 XPOKE adr,dat [XP]
3.4 XPEEK(adr)
3.5 VPOKE adr,dat [VP]
3.6 VPOKE adr,arrayadr,num [VP]
3.7 VPEEK(adr)
3.8 PAGE num
3.9 CCHAR src-char,dest-char
3.10 CCHAR src-char,dest-char,color


4 Filesystem functions
4.1 FTYPE(n)
4.2 FSIZE(n)
4.3 FCREATE f,p [FCR]
4.4 FWRITE f,p,a [FWR]
4.5 FREAD f,p,a [FRD]
4.6 FDELETE f [FDEL]
4.7 FSELECT v,a [FSEL]
4.8 FFIND(a)


5 Direct access to the Dataflash module
5.1 RREAD p,a [RRD]
5.2 RWRITE p,a [RWR]


6 Loading and saving programs
6.1 LOADP f,p
6.2 SAVEP f,p


7 Messages and questions in the box
7.1 ALERT n
7.2 ASK V,n


8 Menu functions
8.1 MENU(n)




BASIC reference (1)
Basics

1 General

Each program consists of a maximum of 95 program lines (1-95). A larger programs can be written by calling code from other programs. For longer keywords there are some abbreviations, these are in rectangular brackets next to the advertised version. Each keyword must have a space. Many commands hide unused bits in the parameters (eg COLOR) or limit to the valid value range (eg PLOT). Unfortunately, not all errors are intercepted in the current version, in such a case (usually the whole screen is filled with zeros or nonsensical characters) you should restart the computer with CTRL+ALT+DEL and look at the BASIC program text again.


2 numbers, variables and functions

AVR-ChipBASIC only knows one data type, which is 16 bit integer numbers. There are 26 variables (A-Z) and an array with 768 or 1024 elements AR (), but more on that later. Constants can be entered in both decimal and hexadecimal form, with no negative values ​​allowed for the latter. Hexadecimal numbers start with $ . The following operations are allowed:
There are also opening and closing brackets and functions. The operators are divided into different priority groups. If the priority of an operator is to be increased, the associated operands must be bracketed.


priority operators
highest * , / , % , # , ^
... << , >>
... + , - , &
lowest = , <> , < , <= , > , >=


Functions can not be abbreviated, unlike keywords. Since the opening parenthesis is part of the function name, there must be no space between the function name and parenthesis.


ABS( Calculates the absolute value of the bracketed expression
SGN( Computes the sign (-1,0,1) of the parenthesized expression
NOT( inverts the parenthetical expression
SQR( pulls the square root out of the bracketed expression
RND( generates a random number between 0 and the parenthesized expression
IN( returns the level value of the specified port pin (0-7) at the parallel interface, if the parameter value is 255, the port pins are read in as byte,
SPI( outputs a byte via the SPI interface and returns the read-in value
TEMP( returns the temperature value of the specified LM75 sensor (0-7)
ADC( provides the analog value of the voltage of the specified port pin (0-7) at the parallel interface
XPEEK( reads a byte of data from the optional data EEPROM, the parenthetical expression determines the address
EPEEK( reads a data byte from the internal EEPROM, address 0 ... 999
VPEEK( reads a byte of data from the frame buffer
LO( returns the low byte of the bracketed expression
HI( returns the high byte of the bracketed expression
KEY( provides various keyboard queries, see section Keyboard
AR( Array value (see below)
SIN( returns the sine of the angle (in 1/10 degrees) by 255
COS( returns the cosine of the angle (in 1/10 degrees) by 255
FTYPE( see section File Functions
FSIZE( see section File Functions
ERR( Error information, see section Error handling
XREC( reads in a data block via XModem protocol
DBIT( converts font data
PSTAT( Sequencer status, see section Audio


In addition to the normal variables, there is also the array variable AR() .
For byte accesses, the LOW-byte is at the even address and the HIGH-byte at the subsequent odd address. If an array cell is accessed which does not exist, an error message is aborted. About AR() note that it can only read from the array, write accesses must be done with DATA.
In order to access the external array, the PAGE nn command can be used to set the active page in the external memory. Some things like file I/O work only with the internal array memory, in order to use the external memory, the data must be copied using ACOPY. The prerequisite for this is that a driver with support for XMEM was loaded on program location 8.

3 value assignment

Value assignments do not begin with a keyword, but with a variable name followed by an equal sign and an expression.
01 A=-4
02 B=SQR(8*2)

3.1 ASHIFT v,n

The absolute value of the variable v is shifted by n bits. N>0 shift bitwise to the left, and N<0 shift to the right. Sensible values ​​for N are between -15 and +15. In contrast to the shift operators, only the absolute amount is shifted, so that this command delivers a correct result even with negative values.
01 A=-39
02 ASHIFT A,-1
03 PRINT A
Since A is shifted 1 bit to the right, the value -19 is output. In contrast:
01 A=-39 >> 1
02 PRINT A
the result is 32749, because a 0 was pushed into the sign position.

3.2 LIMIT v,min,max [LIM]

The value of the variable v is limited to the value range min...max. The function is only allowed on variables, not on array elements.
01 LIMIT A,1,6
02 LI B,C,C+4
in the first example the variable A is limited to the range 1...6, in the second example the variable B is limited to the value range, which is limited by the content of the variable C and the 4 following numbers.

3.3 SCALE Variable,Y0,Y1,X0,X,X1

This command is used to transform values ​​from one area to another. X is the "INPUT" area, Y returns the result. An example:
01 V=180
02 SCALE A,0,100,0,V,256
03 ? V
returns the value 70 for example. In this case, this means that the value of V (180) corresponds to 70 percent of the maximum value 256. One can imagine that the result lies between Y0 and Y1, as the value X lies between the limits X0 and X1. The formula for this is:
  Y = Y0 + ((Y1-Y0) * (X-X0) / (X1-X0))
So that the whole thing is also sufficiently accurate, it is calculated internally with 32 bits. Due to the limited internal program memory capacities, however, not all conditions for the occurrence of a valid result are checked. For example, Y1 should always be larger than Y0, X1 should be greater than X0, and X should be between X0 and X1.

3.4 DATA offset,value1,value2... [DA]

The array elements are initialized from byte (offset). Values ​​include constants, numeric expressions and strings. In the word area of ​​the array (from offset 1024), 16 bits are always written, this applies in particular to character strings where the HIGH byte is always 0. Conversely, only the low byte of the values ​​is written in the byte area of ​​the array.
01 DATA 0,"Hello",0
The array is occupied from element 0 with the null-terminated string "Hello".

3.5 ACOPY source,dest,num... [AC]

A number (num) of array elements is copied from byte (source) to byte (dest). The copying is done element by element, eg it can be extended from 8 to 16 bit. Conversely, when copying from the word to the byte area of ​​the array, only the low byte of the values ​​is written.
 02 ACOPY 0,1029,10
The array is copied from byte element 0 into the word elements 1029...1038 (byte elements 10...29).
It is important that the array cells are copied only in ascending order. If the source and destination range overlap and the source address is smaller than the destination address, the result will not be what you want it to overwrite parts of the source area before copying to the destination area.

3.6 TLEN var,ptr

This command determines the "text length" in the array as of cell ptr . The first non-text cell (everything smaller than 0x20) is searched for. The result is entered in the variable var.
01 DA 0,"Test",0
02 TLEN A,0
03 ? A
This short program should return the value 4 because the text "Test" is 4 characters long. If the end of the array is reached when searching for the end of the text, the command terminates with an error (OUT OF ARRAY).

3.7 TFIND var,ptr1,ptr2

This command can be used to search for text in the array. Here, ptr points to the text to be searched and ptr2 to the text pattern to be searched. Both strings must be terminated with a character less than 0x20. The result is entered in the variable var.
01 DA 100," north east  south west"
02 DA 120," end",0
03 INPUT "Direction:";A
04 DA 0,32:CTEXT 1,20
05 TFIND A,100,0:A=A-100
06 IF A = 20 THEN END
07 IF A < 0 THEN ? "???":GO 3
08 PRINT "R=";A/5: GOTO 3
If the search reaches the end of the array, the command aborts with an error (OUT OF ARRAY). If the text pattern could not be found, the command writes -1 to the variable.

3.8 DBIT(N)

This function simplifies the creation of self-defined characters in video mode 4. The argument N considers only the 6 lower bits and converts them into a bit pattern, which corresponds to the expected value in the display. The reason for this is the organization of the character memory: here bits 0 + 1 are not used, bit 7 corresponds to the pixel on the far left and the following bits (6 ... 2) correspond in each case to the difference to the previous pixel. For example, if you want to set all 6 pixels in a row, 0x80 must be in the byte. Bit 7 is "1" and all subsequent "0", which means "no change". In order to save this conversion, the function DBIT() converts the bit pattern to be displayed system-appropriatelly. Parameter N only uses the lower 6 bits.
01 VM 4:? @0,0;%0;:BORDER 4
02 DA 0,"88GG88GG88"
03 WAIT 10
04 FOR K=0 TO 9:C=DBIT(AR(K))
05 VPOKE 1448+K*128,C:NEXT
The program changes after 1 second the appearance of character 0 which is displayed on the top left, in a kind of "checkerboard pattern".

4 program control



4.1 BREAK

Sets a breakpoint, calls the monitor.

4.2 END

The END command terminates the program at the current location. The same happens when the last program line has been processed.

4.3 GOTO n [GO]

With the GOTO command the program execution can be continued with another line. Argument is an arbitrary expression.
01 B=0:GOTO 2
02 GO B+1
This is an infinite loop that can only be aborted with CTRL + C.

4.4 IF - THEN

The conditional statement consists of IF followed by an expression. If the result of the expression is zero, it jumps to the beginning of the next line, otherwise the line is processed further. The THEN can also be omitted. But for the clarity and readability of the code, this should only be done if there is no more space in the line. If a value assignment first follows, if there is no THEN, a colon must be set between the two statements.
01 IF A>5 THEN A=5
02 IF A>5:A=5
Both expressions do exactly the same thing.

4.5 FOR - NEXT

In the case of counting loop processing, there is only the basic form FOR A=B TO C without the specification of the step size, which is constant at 1. In any event, the loop will loop at least once, if C is none of B, overflow occurs and the number of loop passes is N = C-B+65536.
01 CLS
02 FOR A=0 TO 9
03 FOR B=0 TO 9
04 PLOT A,B,3
05 NEXT :NEXT
This program draws a rectangle in the upper left corner of the screen.

4.6 REPEAT - UNTIL [REP - UNT]

This is another loop design, called a foot control or non-reject loop. This means that the program part between REPEAT and UNTIL is run at least once.
01 A=0
02 REPEAT
03 ? A
04 A=A+3
05 UNTIL A<10
Write the numbers 0,3,6 and 9 on the screen.
Due to the system, there is no EXIT to cancel a loop. A simple GOTO out of the loop is also not a good solution as it blocks a stack entry. A practicable solution would be:
01 REPEAT
02 ? "Hello! ";
03 IF KEY(0)>0 UNT 0: GO 5
04 UNTIL 1
write "Hello!" on the screen until a key is pressed. In this case, UNTIL 0 causes the reserved stack entry to be released again.

4.7 GOSUB [GOS]

GOSUB Expr calls the subprogram in the line defined by the expression; the line number can be followed by up to 5 parameters. Since the stack is limited to 10 entries, only a total of 10 loops or subroutine calls can be nested.
01 GOSUB 4,2,3
02 ? ~R
03 END
04 RETURN ~(1)+~(2)
The subroutine in line 4 adds the two parameters, in this case 2 + 3 = 5. The result is output in the second line.

4.8 RETURN [RET]

RETURN jumps back from a subroutine, RETURN return value can be used to return a 16-bit value, which is then available with the system variable ~R in the calling program.

4.9 CALL

Another statement is CALL prognr, line which can call subprograms in one of the 7 other program positions. This makes it possible to use the entire program memory area for a single application. The program and line number can be followed by up to 5 parameters; the return is as usual with RETURN . Since the stack is limited to 10 entries, only 10 loops or subroutine calls can be nested. Furthermore, leaving loops or subroutines leads to blocked stack entries, which can then no longer be used. If the called program is binary type, there are two possibilities:


4.10 LFIND V,n

This statement can be used to determine if a particular binary library is loaded. Each of these libraries has a (hopefully) unique identifier in bytes 14 and 15. If the LOW byte of the search value equals 0, the LOW byte of the library ID is ignored. The variable is set to 1...8 if a corresponding library was found.
01 LFIND L,$1200
02 IF L>0 GOTO 4
03 ?"MATLIB1 NOT FOUND":END
04 ?"MATLIB1 ON SPACE";L:


4.11 VID n

This command replaces the SLOW and FAST commands since version 1.00 to switch the image output on and off. With VID 0, the picture output is switched off, sync signals continue to be generated. VID 1 switches the picture output back on. With off-picture output, the speed is higher because much of the processing power is typically used for image display. It should be noted that this also shuts off the loaded video driver, which may have undesirable consequences, for example, in a PWM or LED multiplex driver.

4.12 The system variables

The system variables (defined by leading tilde "~", ie the "snake line") provide information about the system state and can only be read. There must be NO SPACE between the tilde character ~ and the system variable letter.

4.12.1 The Array ~(1) ... ~(5) (Function Parameters)

This array contains the parameters that were passed at the last GOSUB or CALL. If the argument is outside the range 1...5, 0 is returned.

4.12.2 ~M (microcontroller)

This variable states whether it is a Mega644 (1) or Mega644P (2). Here a Mega644P is treated with input pin of the first serial interface PD3 like the Mega644, since the second serial interface of the Mega644 is not present (in the Mega644P it is available).

4.12.3 ~L (current program line)

This variable returns as value the currently executed program line. This can be used, for example, to implement relative jumps. The value is between 1 and 95. The following program line generates an infinite loop in each line, which generates a "colored" border:
 xx A=(A+1)&15:BORDER A: GOTO ~L


4.12.4 ~N (parameter count)

This variable shows how many parameters were passed at the last GOSUB or CALL .

4.12.5 ~P (current program)

This variable returns as value the currently executed program. The value is between 1 and 8. If a subroutine was called in another program via CALL P,N the calling program is not returned, but the one currently active.

4.12.6 ~R (return value)

This variable contains the last value specified for RETURN

4.12.7 ~S (Scanline)

This variable returns as value the current screen line currently being displayed. For NTSC the value is between 0 and 262, for PAL between 0 and 312. Areas of application are, for example, more accurate time measurements, where TGET dissolves too coarse. However, the video output should be switched off.
01 REPEAT :UNTIL ~S<230:BO 4
02 REPEAT :UNTIL ~S>100:BO 0:GO 1
On the screen, a green border should now be seen above and below, in between the screen is black. However, a strong tremor of the edges is observed, which is simply because the processing of the commands takes longer than a screen line.

4.12.8 ~V (video system)

this variable returns as value the number of screen lines per field. A current screen line determined with ~S will always be between 0 and ~V-1. For NTSC, ~V = 263, for PAL the value is 313.

4.12.9 ~X (X-expansion)

This variable returns as a value the number of pixels in the horizontal direction. The current resolution is taken into account. In video mode 0, for example, the variable has the value 60 and in mode 1 the value 168.

4.12.10 ~Y (Y-expansion)

This variable returns as value the number of pixels in the vertical direction. The current resolution is taken into account. For example, in video mode 0 the variable has the value 46 and in mode 1 the value 116.

4.13 Extensions

If there is a library with library code 0x70...0x7f at program location 6, additional commands can be evaluated and executed there. These commands begin with an underscore. If the command is not known there or no suitable library is loaded, a UNKNOWN KEYWORD error is aborted. As with the built-in commands, variables or parameters may follow.

5 Screen output


5.1 COLOR F(,B) [COL]

The COLOR command sets the foreground and background colors. In contrast to previous versions, this is taken into account in all editions, as the foreground and background colors can now be set individually for each character. If only one parameter is specified, only the foreground color is set. Values ​​from 0 to 15 are accepted, without the "16-color extension" the colors 0...7 and 8...15 are identical:


value 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15
colour black blue red magenta green cyan yellow White


When the "16-color extension" has been added (default in the CB2 micro), there are 8 additional colors available, with the first 8 colors becoming slightly darker overall.
value 0 1 2 3 4 5 6 7
colour black blue red magenta green cyan yellow light gray
value 8 9 10 11 12 13 14 15
colour dark gray light blue light red light magenta lime light cyan light yellow white


 01 COLOR 4,2
Here, the character-color "green on a red background" is set, which is not very easy to read.

Creating more than 16 colors is possible in special cases, by using the dithering technique. Some specific block characters (16, 138, 139, 140) allow the creation of blocks with composite colors outside of the standard 16-colors palette,
when you set different foreground and background colors on them.

5.2 CLS

The CLS command clears the screen. At program start this happens automatically. The set background color (black at program start) is used.

5.3 BORDER B [BO]

With this command, the border color can be set, valid values ​​are 0...15

5.4 POS Y,X

The POS command sets the write cursor to position Y,X. Each time the screen is cleared, the cursor is moved to position 0,0 (top left).

5.5 WRAP n

The WRAP command can be used to set the behavior at the end of the screen in text mode. With WRAP 0, the screen is scrolled up one line when it reaches the end of the screen. This is also the default at startup. With WRAP 1, the cursor is reset to the beginning of the screen when the screen is reached. At the start of the program the value is pre-assigned with 0.

5.6 PRINT [?]

The PRINT command is used to output to the screen or to the serial/parallel interface, into the array or to the I2C interface. In addition, the output can still be formatted. Instead of the PRINT command, a question mark can also be used (BASIC customary).


"TEXT" the text TEXT is output
#Expr Determining the output channel (see below)
!Expr Sets the format (see below)
@Expr1,Expr2 Cursor positioning (Y=Expr1, X=Expr2)
%Expr Direct output of a character with character code=Expr
&Expr returns array elements as characters. Stopping at a zero byte or when the end of the array is reached. Works only in byte access to the array.
Expr outputs the result of the printout with the set format
; Separator between expressions
, Separator between expressions, spaces up to the next position divisible by 8


If one of the two separators is at the end of the PRINT command, no line feed is executed. The output channel determines where the characters are to be output. For output channel >3, the I2C interface with the channel number is output as the device number. The least significant bit is set to 0 (write mode).


#0 Output to the screen, default setting
#1 Output to the serial system interface
#2 Output to the parallel interface
#3 Output to the array
#4 Output to the second serial interface (ATMega644P only)
#5... Output via the I2C interface


The format is a value between 0 and 255, where the bits have the following meaning:


Bit 7 0=decimal output, 1=hexadecimal output
Bit 6 1 switches to large display
Bit 4/5 Comma position (0-3 decimal places), only for decimal output
Bit 2/3 Number of digits issued (2-5), only for decimal output
Bit 0/1 0=compact, 1=leading spaces 2=leading zeros 3=leading zeros with sign
Bit 0 2/4 characters in hexadecimal output


When outputting to the screen, the cursor is set to the corresponding position; when output to the serial or parallel interface, positioning is ignored. When output to the array, the first value is array byte position*256 and the second value of the array byte position, without @ is the byte position at the beginning of each PRINT command 0x0000. If output via the I2C interface, then 0xff is sent first, followed by xxxxxxxx and yyyyyyyy. The change would be necessary in order to be able to position characters more finely, for example on externally connected GLCDs.

5.7 CBOX Y1,X1,Y2,X2

The CBOX command deletes a rectangle (with the current background color).
01 CBOX 3,3,5,5
deletes a square of 3x3 characters at the top left.

5.8 FRAME Y1,X1,Y2,X2

Draws a text frame with a border.
01 COLOR 7,3:FRAME 0,0,22,29
Draw a text frame with full screen size, purple background, and white paint.

5.9 HFRAME Y1,X1,Y2,X2

Draws a text frame with a border and a "header", just as the main menu is built up.
01 COLOR 7,3:HFRAME 0,0,22,29
02 COLOR 3,7:?@1,1;"HFRAME"
Draw a text frame as in the previous example, but now with a header and text inside.

5.10 IBOX Y1,X1,Y2,X2

The IBOX command swaps foreground and background colors in a rectangle. The characters themselves are not changed.
01 IBOX 0,0,0,0
inverts the character in the upper left corner.

5.11 SCROLL n

In the video modes 0, 4 and 6, there is a scroll window, in which all 4 directions can be scrolled. The window starts at character 2 in line 2 and goes to character 27 in line 20. Thus, there is a 2-character border around the scroll window in which, for example, information is displayed that should not be scrolled.
The released line is filled with blanks in the current color setting.


n direction
0 up
1 to the right
2 downward
3 to the left


10 SCROLL 2
moves the scroll window down 1 character.

5.12 GETCHAR variable,Y,X [GCH]

Finds the character at position y,x and writes it to variable v.
11 GCH F,0,0
Writes the character value from position 0,0 to variable F.

5.13 GETATTR variable,Y,X [GAT]

Determines the attribute byte at the position y,x and writes it into the variable v.
12 GAT F,0,0
Writes the attribute value from position 0,0 to variable F. Here the attribute is composed as follows:


bit function
0 Background color bit 0
1 Background color bit 1
2 Background color bit 2
3 Background color bit 3
4 Foreground color Bit 0
5 Foreground color bit 1
6 Foreground color bit 2
7 Foreground color bit 3


It should be noted that the bits are physically different in image memory because of compatibility with previous versions and 8-color hardware:


bit function
0 Background color bit 3
1 Background color bit 0
2 Background color bit 1
3 Background color bit 2
4 Foreground color bit 3
5 Foreground color Bit 0
6 Foreground color bit 1
7 Foreground color bit 2




6 keyboard



6.1 INPUT [INP]

You can specify strings and variables separated by commas. The strings are output, the variables cause an input cursor. Incorrectly entered characters can be corrected with the backspace key. It is also possible to enter expressions that will be calculated. The following example shows a small calculator, the last result is stored in the variable M.
01 INPUT "TASK: ",M
02 PRINT "RESULT:";M
03 GOTO 1
If you enter "1+2" first, you get "3". If you enter "M*5" after that, you get "15".

6.2 CTEXT adr,anz

Copies the last text entered in Input into the array bytewise from element adr. The end mark is appended with a null byte. The number of bytes to be read in, is limited with the 2nd parameter indicator (anz). It should be noted that due to the attached null byte, effectively +1 bytes are copied.
01 INPUT "Text: ",M
02 CTEXT 0,4
03 X=0
04 C=AR(X):IF C=0 THEN END
05 PRINT %C;:X=X+1:GOTO 4
The text entered after the prompt is repeated one line down, with only the first 4 characters being output.

6.3 The Keycodes

In addition to the "normal" ASCII values ​​for numbers, numbers and punctuation marks, RKEY and WKEY also provide codes for function keys etc.


Code Hexadecimal Code decimal Button
$C0 192 Power
$C1 193 Sleep
$C2 194 Wake
$E0 224 Pos1
$E1 225 End
$E2 226 Arrow key to the left
$E3 227 Arrow key to the right
$E4 228 Arrow key up
$E5 229 Arrow key down
$E6 230 Picture up
$E7 231 Picture down
$E8 232 Ins
$E9 233 Del 
$EA 234 Enter
$EB 235 Tab
$EC 236 Backspace
$ED 237 Esc
$F1...$FC 241...252 F1...F12


6.4 The function KEY

This function provides different keyboard queries. The type of query is entered as parameter. With KEY(0) to KEY(2), Shift, CTRL, and ALT not to count as pressed keys.


KEY(0) The pressed key or 0x00 is returned
KEY(1) It waits for a keystroke, result is the code of the pressed key.
KEY(2) It waits until no key is pressed, the code of the last pressed key is returned.
KEY(3) The status of the Shift and CTRL keys is returned. See below
KEY(4) left shift key returns 1, left control key returns -1, both together 0
KEY(5) right shift key returns 1, right control key returns -1, both together 0
KEY(6) Cursor left key returns -1, cursor right key returns 1
KEY(7) Cursor down key returns -1 Cursor up key returns 1
KEY(8) The last scancode read is returned
KEY(9...255) Waiting until the key with the corresponding key code is pressed


Assignment of the bits at the return value of KEY(3):


bit function
0 Left shift key
1 Right shift key
2 Left CTRL key
3 Right CTRL key
4 ALT key
5-7 Internal Use




7 Time


7.1 WAIT n

The WAIT command waits N*0.1 seconds. N can again be an arbitrary expression. In video mode 7, it may well be that the driver does not continue the time and the function does not return. But that depends on the specific driver implementation.
10 WAIT 10
Wait 1 second for the program to continue.

7.2 SYNC n

The SYNC command waits for N frame sync pulses. N can again be an arbitrary expression. In video mode 7, it may well be that the driver does not continue the time and the function does not return. But that depends on the specific driver implementation.
10 SYNC 300
Wait 6 seconds for the program to continue. This only applies to PAL, with NTSC only about 5 seconds is waited.

7.3 TSET n

The internal timer (10Hz) is set to the value n.
10 TSET 0
sets the timer to 0.

7.4 TGET V

The internal timer (10Hz) is read out and stored in the varaiable V. In video mode 7, it may well be that the driver does not continue counting the time and the function returns the time set at TSET. But that depends on the specific driver implementation.
10 TGET Z
Thus, for example, the runtime of programs can be determined.

7.5 ONSYNC L,N

Similar to the timer interrupt on a microcontroller, ONSYNC can be used to set timed subroutine calls. Where L is the row number and N is the number of frame sync pulses between two calls. The value N for the waiting time can not exceed 255, L should be a valid line number, at L=0 the automatic calls are stopped. The called subroutine must end with RETURN and must not last longer than the time between two calls. Internally, a counter with the value N is compared with each frame sync pulse and a flag is set if equal. In the BASIC interpreter, this flag is then checked before the execution of each statement, and if it is set, a GOSUB is "inserted" to the specified line number. In video mode 7, it may well be that the driver does not continue counting the time and the specified line is never called. But that depends on the specific driver implementation.
01 ONSYNC 5,50
02 ? "Border:";A,
03 GOTO 2
04
05 A=A+1:IF A=8 THEN A=0
06 BORDER A:RETURN
This program changes the border color every second while the current border value is constantly output as text.

8 Error messages and error handling


8.1 ONERR N

If N is in the range of the valid lines (1...95), an error will be entered in this line. Otherwise it will be aborted (as usual) with an error message. If there are no more commands at and behind the specified line, the program is exited without an error message.
If GOSUB calls a subroutine in another program, it jumps to the specified line in case of an error.
01 ONERR 10
02 A=SQR(-1)
10 DATA 512,7,1,"Error!",0
11 ALERT 512
12 END
Since an attempt is made to extract the root from a negative number, the program jumps to line 10 and displays an alert box there.

8.2 ERR(n)

This function can be used to read out information about the error that has occurred. Of course, this only works if an own error routine has been started with ONERR. For n=1, returns the line in which the error occurred, for n=2 the statement. For all other values ​​of n, the error number is returned.
01 ONERR 10
02 A=SQR(-1)
10 DATA 512,7,1,"Error ",0
11 ? #3@2,8;ERR(0);
12 ALERT 512
13 END
Since an attempt is made to pull the root from a negative number, there is again an alert box. In line 11, the error number is written to the array and displayed with.

8.3 Error messages

There are 37 different error messages altogether. In the editor these are displayed at the top of the second line with program, line and statement numbers. In general, the error can be found quite quickly, sometimes it can be at the end of the previous line.


01 BREAK The program was aborted with the key combination Ctrl+C.
02 OVERFLOW For an arithmetic operation, the result is outside the limits of -32767...32767
03 DIVIDE/0 An attempt was made to divide by zero
04 SQR FROM <0 An attempt was made to draw the square root from a negative number
05 CONSTANT TOO BIG The specified number is outside the limits of -32767...32767
06 WRONG EXPRESSION The formula contains syntactical errors
07 SYNTAX ERROR Missing parameters, invalid characters
08 UNKNOWN KEYWORD Unknown keyword, the program code contains invalid bytes
09 WRONG FORMAT Number formatting is invalid (more decimal places than visible)
10 BAD LINENUMBER The line with the specified line number does not exist
11 NEXT W/O FOR There is no corresponding FOR for this NEXT statement
12 RETURN W/O GOSUB There is no corresponding GOSUB for this RETURN statement
13 STACK OVERFLOW All in all, only 16 FOR/GOSUB/REPEAT may be "open" at the same time. The cause may be, for example, a recursive subroutine call.
14 UNTIL W/O REPEAT There is no corresponding REPEAT for this UNTIL statement
15 I2C ERROR No device reports at the specified address or not ready, for example, serial EEPROMs can be busy writing data.
16 UNKNOWN ERROR unknown error. Unfortunately, all sorts of combinations of commands, functions, and parameters are not that easy to fully test, and it would be nice if you reported the error.
17 DFLASH ERROR No data flash connected or the device is not responding.
18 OUT OF ARRAY An attempt was made to access an array element that does not exist. The error also occurs if the space in the array is insufficient with BCOPY.
19 INCOMPLETE PAR Too few parameters were specified for the command
20 KEYWORD IS MISSING The specified statement does not start with a keyword, but rather with a number
21 WRONG BCOPY The copy mode is not in the range (1...6)
22 OUT OF SCREEN Attempt to draw outside the screen area (not implemented)
23 CAN NOT CREATE FILE The file already exists or the file number is outside the valid range
24 DFLASH FULL The file can not be created because the space on the dataflash is insufficient.
25 FILE NOT FOUND The file does not exist (is free)
26 PAGE NOT IN FILE The page to read/write does not exist in this file
27 PAGES NOT IN RANGE Only files with 1...128 pages can be created
28 NOT IN GRAPHICS FASHION The specified command can not be executed in graphics mode (VMODE 1...3/5)
29 NOT IN TEXT MODE The specified command can not be executed in text mode (VMODE 0)
30 NO USR FILE Only files of type USR can be read/written (obsolete)
31 SRC OUT OF SCREEN The source block at BCOPY is not completely in the image area
32 DEST OUT OF SCREEN The target block at BCOPY is not completely in the image area
33 WRONG SPRITE The sprite definition has an error (eg greater than 8x8 characters)
34 WRONG EEPROM ADR An attempt was made to access an internal EEPROM cell >1999
35 NO PRG FILE An attempt was made to load a non-program file with LOADP
36 XMODEM ERROR A (checksum) error occurred during X-modem reception
37 CANT LOAD THIS An attempt was made to overwrite the currently running program with LOADP
38 IO DISABLED Output to the parallel port was deactivated by a driver on program location 8
39 SERIAL1 NOT AVAILABLE An attempt was made to access the second serial interface, but the controller type is a Mega644 or input pin of the serial system interface is connected to PD3
40 NO IO DRIVER An attempt was made to access a non-existent address from 0x0800 using IN/OUT







BASIC reference (2)
Graphics and sound


1 Graphic


1.1 Pseudographic in text mode

For the pseudographic, each character is divided into 4 "pixels". With 23 lines of 30 characters this results in a working area of ​​60x46 points. The 4 pixels of a character always have the same background and foreground color.
If the character color is the same as the background color of the character to be changed, the pixels are only deleted, color information is not changed. If the character color is the same as the foreground color, pixels are only set, color information is not changed here. If there is no match between the character color and the foreground and background color of the character in question, the foreground color is reset, with previously set pixels inevitably having to be recolored.
In addition to the pseudographic in text mode, there are 4 graphics modes that differ in resolution and number of colors that can be displayed. However, the available memory of the controller does not allow very high resolutions. Also for space reasons, it is not possible to call the monitor in the graphics modes.
If foreground and background colors are set in modes 2,3 and 5, they point to the palette index and do not indicate the color directly.

1.2 Video mode 1

The pixel resolution is 168x116 pixels, whereby for each 8x8 (at the bottom only 4x8) pixels, foreground and background color can be adjusted. If the character color is the same as the background color at the character position, the pixels are only deleted, color information is not changed. If the character color is the same as the foreground color, pixels are only set, color information is not changed here. If there is no match between the color of the drawing and the foreground and background color of the corresponding area, the foreground color is reset, with previously set pixels inevitably having to be recolored.

1.3 Video mode 2

The pixel resolution is 120x76 pixels, each pixel can accept one of 4 colors that can be adjusted via the palette.

1.4 Video mode 3

The pixel resolution is 84x58 pixels, each pixel can have one of 16 colors that can be adjusted via the palette.

1.5 video mode 5

The pixel resolution is 128x64 pixels, each pixel can have one of 2 colors that can be set via the palette. This mode is mainly used to emulate graphics LCD with the appropriate resolution.

1.6 VMODE n [VM]

Switches the video mode. The screen will be deleted and the text coordinates will be set to the upper left corner.


Mode Resolution X Resolution Y Representable colors
0 Text 30 Text 23 16 foreground and 16 background
1 168 116 2 out of 16
2 120 76 4 out of 16
3 84 58 16 out of 16
4 (User symbols) 30 (User symbols) 23 16 foreground and 16 background
5 128 64 2 out of 16
6 (User symbols) 30 (User symbols) 23 16 for each pixel
7 Text 30 Text 2 16 foreground and 16 background


In addition, the palette entries used in the respective mode are preassigned.

1.7 PALETTE start,c1(,c2,c3,c4,c5,c6) [PAL]

This command sets the color palette for video modes 2 through 3 and 5. For mode 5 only the entries 0 and 1 are used, for mode 2 the entries 0 to 3. The number of the pallete entries to be set is limited to 6, otherwise an error message is generated. As color values ​​must be specified in the range (0...15). After switching the video mode, the palette entries are pre-assigned as follows:


index Mode 1 Mode 2 Mode 3
0 black (0) black (0) black (0)
1 white (7) red (2) blue (1)
2 --- cyan (5) red (2)
3 --- light gray (7) magenta (3)
4 --- --- green (4)
5 --- --- cyan (5)
6 --- --- yellow (6)
7 --- --- light gray (7)
8 --- --- dark gray (8)
9 --- --- light blue (9)
10 --- --- light red (10)
11 --- --- light magenta (11)
12 --- --- light green (12)
13 --- --- light cyan (13)
14 --- --- pale yellow (14)
15 --- --- white (15)



1.8 PLOT Y,X(,C) [PL]

With the PLOT command we set a point at the position Y, X. If necessary, the character color can also be specified.
01 CLS:VMODE 1
02 FOR X=1 TO 167
03 V=SIN(3*X)/6
04 PLOT 55-V,X
05 NEXT
#
Draws a sine wave (video mode 1). Since only individual points are set, the line is not continuous.

1.9 DRAWTO Y2,X2(,C) [DTO]

Draws a line from the last drawn pixel to Y2, X2 in the current foreground color. If necessary, the character color can also be specified. At program start, the last drawn pixel is defined as Y=0, X=0.
01 CLS:VMODE 1,PLOT 55,0
02 FOR X=1 TO 167
03 V=SIN(3*X)/6
04 DRAWTO 55-V,X
05 NEXT
#
Draws a sine wave (video mode 1). Since this time instead of individual points short line pieces are drawn, the line is continuous. The plot command in the first row sets the starting coordinate for the first line piece; if it is missing, drawing is started at 0,0.

1.10 DRAW Y1,X1,Y2,X2(,C) [DR]

Draw a line from Y1, X1 to Y2, X2 in the current foreground color. If necessary, the character color can also be specified.
01 CLS:VMODE 1,PLOT 55,0
02 FOR X=1 TO 167
03 V=SIN(3*X)/6
04 DRAWTO 55-V,X
05 NEXT
06 DRAW 55,0,55,167
#
Here, the zero line is drawn through the sine curve just drawn.

1.11 BOX Y1,X1,Y2,X2(,C)

The BOX command draws a rectangle in the current foreground color. If necessary, the character color can also be specified.
11 BOX 0,0,115,167


1.12 FBOX Y1,X1,Y2,X2(,C)

The FBOX command draws a filled rectangle. If Y1=Y2 or X1=X2, horizontal or vertical lines are drawn. If necessary, the character color can also be specified.
10 FBOX 0,0,0,100
draws a horizontal line at the top of the screen, the value 100 is limited to the screen area at runtime if it is outside the screen.

1.13 CIRCLE Y,X,RY,RX(,C) [CI]

Draws a circle (an ellipse) centered at Y, X and radii RY and RX in the current foreground color. For circles, RX must be equal to RY. If necessary, the character color can also be specified.
10 CIRCLE 50,50,20,20
Draw a circle with center coordinates 50,50 and radius 20.

1.14 FCIRCLE Y,X,RY,RX(,C) [FCI]

Draw a filled circle (a filled ellipse) centered at Y, X and radii RY and RX in the current foreground color. For circles, RX must be equal to RY. If necessary, the character color can also be specified.
10 FC 50,50,20,10
Draw a filled ellipse with center coordinates 50,50, Y radius 10, and X radius 20.

1.15 ARC Y,X,RY,RX,W1,W2(,C)

Draws a circle or ellipse, centered on Y, X and with radii RY and RX in the current foreground color, starting at angle W1 to angle W2. The two angles are given in degrees, the initial angle should be smaller than the end angle, otherwise the function takes a long time. For circular sections, RX must be equal to RY; if necessary, the character color can also be specified.
01 VM 1
02 ARC 50,50,20,20,0,270
Draws a three-quarter circle segment with center coordinates 50,50 and radius 20

1.16 PIE Y,X,RY,RX,W1,W2(,C)

Draw a closed circle or ellipse cutout (a "pie slice") centered at Y, X, with radii RY and RX in the current foreground color, starting at angle W1 to angle W2. The two angles are given in degrees and the initial angle should be smaller than the end angle, otherwise the function takes a long time. In contrast to ARC, additional lines are drawn from the two endpoints to the center. For circular sections, RX must be equal to RY. If necessary, the character color can also be specified.
01 VM 1
02 ARC 50,50,20,20,0,270,6
Draws a closed yellow three-quarter circle segment with center coordinates 50,50 and radius 20

1.17 GETPIX variable,Y,X [GPX]

Retrieves the color of the pixel at location Y, X and stores the palette index (not the color!) In the specified variable.
10 GPIX P,0,0
Determines the palette index of the pixel in the upper left corner.

1.18 BCOPY [BC]

The BCOPY command makes it possible to copy rectangular blocks or memory areas within the screen or into/from the array. This can be used, for example, to implement sprites in graphics mode or scrolling. Blocks can be copied in modes 1...3 from and to (almost) any coordinates, only the size is subject to restrictions. Only whole subblocks can be copied.


Video mode Pixels per subblock
1 8x8
2 4x4
3 2x2


In video mode 1, a subblock is 8x8 pixels in size to copy a 16(V)x24(H) pixel block, DX=2 and DY=3. Ιn video mode 2, DX=4 and DY=6 and in video mode 3, DX=8 and DY=12.
The first value indicates the copy mode, from which the number of remaining parameters depends.


Mode Source Aim Additional parameter
1 image memory image memory Y1,X1,DY,DX,Y2,X2
2 image memory array Y,X,DY,DX,ARRAYPOS
3 ARRAY image memory ARRAYPOS,Y,X


In mode 2, it is checked whether the limits of the array are exceeded, in which case it is immediately aborted. The following formulas can be used to calculate the required memory requirements:


Video mode 1 (8 * DX * DY) +2
Video mode 2 (4 * DX * DY) +2
Video mode 3 (2 * DX * DY) +2



DX and DY is the number of subblocks. Copy Mode 3 should only be applied to Array positions, which also contain useful information. These can be created either by copying in mode 2 or by "DATA".
The pixel information is organized such that 8, 4 or 2 pixels are coded in one byte depending on the video mode, where the least significant bit is leftmost.
01 DATA 0,1,1,$FF,$81,$81,$81
02 DATA 6,$81,$81,$81,$FF
03 VMODE 1
04 BCOPY 3,0,0,0
05 WAIT 10
The program draws a small square in the upper left corner of the screen. First the array is filled. The first two bytes contain the number of subblocks in the Y and X direction, followed by the pixel data.
In addition, there are the modes 4-6, which do not take into account the orgaisation of image memory and are intended for quick copying.


mode source aim zus.Parameter
4 image memory image memory Source address, destination address, number of bytes
5 image memory array Source address, destination address, number of bytes
6 ARRAY image memory Source address, destination address, number of bytes


These 3 modes are particularly interesting in the video modes 4 and 6 with the user-defined characters. The organization of the image memory in the various video modes is described in more details in the section of the image memory .

1.19 PRINT [?]

The PRINT command largely corresponds to its counterpart in text mode. The different thing are the coordinates given here instead of characters in pixels. And the format attribute "Large font" corresponds to double character height and width. In addition, the line break does not work as expected, it just jumps to the beginning of the next pixel line.

1.20 FONT n

In graphics modes 1...3 and 5, a smaller font with 4x6 pixels is available in addition to the standard font with 6x10 pixels. Switches with FONT 0 for the standard font and FONT 1 for the mini-font.

2 Sprites

Sprites are single characters or simple groups of characters that can be easily displayed anywhere on the screen. The original screen content is "remembered" at this point and restored when moving or deleting the sprite. In the current version (theoretically) up to 85 sprites can be defined, the actual number depends on the size and available space in the array. Sprites only work in text mode and not in graphics modes.

2.1 Defining sprites

There is no stand-alone command because the data is simply in the array (byte range). Each sprite consists of a header of 5 bytes, the actual data and the backup area. The assignment of the bytes is as follows:


Header byte Address Function
1 N the collision flag (0/2)
2 N+1 Y position (at the beginning $ff or -1)
3 N+2 X position (at the beginning $ff or -1)
4 N+3 Y extension in characters (dy)
5 N+4 extension in characters (dx)


If the collision flag is preset to 0, the sprite is not drawn in a collision. If it is set to 2, the sprite is drawn in a collision. This is followed by dx*dy bytes for the characters to be represented, followed by dx*dy bytes for the attributes. The attribute bytes are foreground color + 16 * background color; adding 128 preserves the original background color when drawing. This is followed by 2 * dx * dy bytes in which the original screen content is automatically saved when drawing.
A minimal sprite (1 character) needs 5+4=9 bytes, one with 2x2 characters 5+16=21 bytes. The values ​​for the X and Y coordinates should be outside the screen area, otherwise the sprite's backup area will be copied there the first time the sprite is called up.

2.2 SPRITE n,y,x [SPR]

Draws the sprite from array address n to position Y,X. If it was already drawn elsewhere, it will be deleted beforehand. If another character, whose position in the character table is not a multiple of 16, is already at the position where the sprite is drawn, the collision flag is set. If bit 1 of the collision flag is not set, the sprite is not drawn. The collision flag is not reset automatically. Sprites must not be drawn beyond the edge of the screen, otherwise an error message is displayed and aborted. If X and/or Y coordinates are specified outside the screen (X>29, Y>22), the sprite will disappear from the screen.
01 DA 0,0,-1,-1,1,1,"*",$86
02 ?@10,10;"#"
03 X=RND(29): Y=RND(22)
04 SPRITE 0,Y,X
05 IF (AR(0)
05 WAIT 1
06 GOTO 2
First, the sprite data is written into the array (in this case a yellow asterisk), then another obstacle is drawn at position (10,10).
Afterwards, the little star hops back and forth until it meets the obstacle. This stops, the asterisk is "gone". If the first line is changed to:
01 DA 0,2,-1,-1,1,1,"*",$86
then the star stops and the obstacle is no longer visible.

3 Audio


3.1 NOTE n [NO]

A tone with the pitch n (halftone steps from 220 Hz upwards) is output. For n=0 to 62, notes are output in a "dark" tone, for n=64 to 126 notes are output with a "bright" tone. With n=63 and n=127 no note but noise is output. If 128 is added to the note value, the tone is output with a slower envelope.
01 FOR N=0 to 255:NOTE N
02 WAIT 5:NEXT
plays all playable notes in succession. The following table is an overview of the different options:


value meaning
0...62 Notes in a "dark" tone with fast envelope
63 Noise with fast envelope
64...126 Notes in a "bright" tone with fast envelope
127 Noise with fast envelope
128...190 Notes in a "dark" tone with a slow envelope
191 Noise with a slow envelope
192...254 Notes in a "light" tone with a slow envelope
255 Noise with a slow envelope


3.2 NOTE n,v [NO]

With the NOTE command, the second parameter is the volume in the range 0...15. The specified volume value then only applies to this one note.

3.3 VOL n

This command is used to control the volume, values ​​between 0 and 15 are possible. If the value is 0, the sound output is not completely switched off, but should be barely audible. If set to 15, the maximum volume will be reached. The adjusted volume value applies to notes and to the sequencer as long as the volume is not explicitly specified for the individual notes.

3.4 PLAY start,stop,speed,loops

AVR-Chipbasic2 has a simple sequencer built-in. This uses the array as a note memory and runs in the background. The parameters are the number of the array cell (byte range) with the first note to be played, the number of notes to be played and the number of fields (1/50s for PAL, 1/60s for NTSC) for a "Tick". Grades between the start and end array cells are played cyclically, the number of cycles is determined by the value of loops (byte variable). If this value is greater than 127, the cycle counter will not be decremented by 1 after each pass, so the notes will play in an infinite loop. Each note consists of 2 bytes in the array, in the first byte is the note value corresponding to the NOTE command, in the second byte is the number of ticks to the next note in the lower nibble and the volume in the upper nibble. If the upper nibble is 0, the current volume is maintained.

The following example continuously plays 3 notes up and down...
01 DA 0,39,8,44,4,49,8,44,4
02 PLAY 0,4,10,128
03 GOTO 3
If the last line is omitted, you will hear nothing or at most a single tone, because at the end of the program the sequencer is stopped immediately. This command should only be used if there are valid note values ​​in the array.

3.5 PSTAT(mode)

This function provides information about what the sequencer is doing. If the byte parameter mode is <255, then the cycle counter is set to the value of mode , mode=255 returns only the current cycle counter.


value meaning
0 Sequencer is stopped
1 Sequencer will run until the end of the current cycle and will stop
2...127 Sequencer runs, notes are played, after each cycle the cycle counter is reduced by 1
128...255 Sequencer is running, notes are played, cycle counter does not change








BASIC reference (3)
Input/output, files


1 Input and output via the parallel port


1.1 DIR n

Sets the I/O direction of the 8 port pins at the parallel port. A 0 means input, a 1 means output.
10 DIR $F0
Pin D0-D3 are configured as input, D4-D7 as output.
The function can be deactivated by the driver at program location 8, in this case the program is aborted with the message "IO disabled".

1.2 OUT n,b

There are several functions here, n=0..7 sets individual bits, n=$100 to $1ff makes it possible to set or delete several bits at the same time. The lower 8 bits of n serve as a mask.
Examples:
10 OUT 7,0
Sets D0 to 0 level.
10 OUT $1F0,$F0
Sets D3-D7 to 1 level.
The function can be deactivated by the driver at program location 8, in this case the program is aborted with the message "IO disabled". n=512 ($200) configures the SPI interface. If b=255 ($ff), the SPI interface is reset to default values. For other values, the SPI interface is configured according to the following scheme: Bits 0-5 are written in the SPCR register of the microcontroller, bit 6 in the SPSR register.


Bit Bit=0 Bit=1
0 see SCK clock divider see SCK clock divider
1 see SCK clock divider see SCK clock divider
2 Data transfer with leading edge of the clock Data transfer with trailing edge of the clock
3 Clock in rest LOW Clock in rest HIGH
4 SPI slave SPI master
5 Bit 7 is sent first Bit 0 is sent first
6 Bit rate x 1 Bit rate x 2


The SCK clock divider can be used to set the SPI clock frequency in master mode. The following values ​​are possible:


Bit 6 Bit 1 Bit 0 Frequency
0 0 0 5 MHz
0 0 1 1.25 MHz
0 1 0 312.5 KHz
0 1 1 156.25 KHz
1 0 0 10 MHz
1 0 1 2.5 MHz
1 1 0 625 KHz
1 1 1 312.5 KHz


The clock frequency of 10 MHz can only be used in master mode, whereby the slave mode can only be used to a limited extent since the CPU can not operate the SPI interface during picture output (about 70% of the time). Direct access to the I/O registers of the ATMega644 is available in the range n=$400 to $4ff. Here you should use caution, it is possible to bring the system to a halt.
01 OUT $4B9,92
Sets the TWBR register (I2C bit rate) to 92 (100KHz for prescaler 1).
For addresses in the range n=$0800 to $ffff, a function in the driver (program location 8) is accessed. If no corresponding driver is loaded, this is just a dummy function that sets the error register.

1.3 The function IN(n)

There are several possibilities, n=0...7 reads individual bits of the I/O port, n=$1xx allows multiple bits to be read simultaneously, where xx is the bitmask.
An extended functionality is available in the range n=$400 to $4ff. Here you can directly access the I/O registers of the ATMega644.
01 D=IN($426)
reads the PIN register (port input) from port C into variable D.
For addresses in the range n=$0800 to $ffff, a function in the driver (program location 8) is accessed. If no corresponding driver is loaded or if it does not use the specified address, an error (NO IO DRIVER) is generated.

1.4 The function ADC(n)

This function is used to read in analog values ​​via the integrated analog-to-digital converter. Here also, there are several possibilities, n=0...7, the I/O lines D0...D7 are read with the internal reference voltage of 2.56 volts. In the parameter range n=$1xx it is possible to control the ADMUX register directly. In addition to different references, it is also possible to use the differential modes.

1.5 The function SPI(n)

With this function, a byte is output via the SPI interface and the read value is returned.
10 IF SPI(67)<>67 PRINT "ERROR"
When MOSI is connected to MISO and the SPI interface is enabled, no "ERROR" should be displayed.

1.6 SPISEL n

This signal can be used to switch the SPI-SS port pin. As of version 1.44, the evaluation of the parameter has changed so that the SPI Multiselect extension can be used. For values ​​<255, the byte is output with the SS signal deactivated and only then the SS signal is activated.
01 SPISEL $F7
02 A=SPI($FF)
03 SPISEL $FF
This command activates the select line, outputs 0xFF via the SPI interface and then deactivates the select line again. With SPI Multiselect extension, the SS output is activated on bit 3.
When accessing the DataFlash block, the fixed SPISEL value of 254 (Bit0=0) is always used.

2 Communication


2.1 SPUT a,b...

one or more bytes are output to the serial interface.
01 SPUT 65,10
returns a capital "A" and a line feed to the serial port.

2.2 SGET V

A character from the serial interface is read in and stored in the variable V. This function can only be used with the ATMega644P, and it is useful to connect the input pin of the serial system interface at PD1, otherwise the second UART is not usable. The function only returns when the character has been read in, alternatively it can be aborted with the ESC key. In this case, the value -1 is returned.
01 SGET C
waits for a character from the serial port and stores it in variable C

2.3 BAUD n

Here the bitrate of the serial interface can be adjusted. However, this setting only applies to the runtime of the program and will be overwritten by the system setting after the end of the program. The following bit rates are possible:


n Bit rate (bps)
0 1200
1 2400
01 BAUD 1
sets the bitrate to 2400bps.

2.4 ESPUT a,b...

one or more bytes are output to the second serial interface. However, this function can only be used with the ATMega644P, and only if the input pin of the serial system interface is at PD1. Otherwise it is aborted with an error message.
01 ESPUT 65,66,10
outputs a line feed to the second serial interface.

2.5 ESGET V

A character from the second serial interface is read in and stored in the variable V. However, this function can only be used with the ATMega644P, and only if the input pin of the serial system interface is at PD1. Otherwise it is aborted with an error message. The function only returns when the character has been read in, alternatively it can be aborted with the ESC key. In this case, the value -1 is returned.
01 ESGET C
waits for a character from the second serial port and stores it in variable C

2.6 EBAUD n

This sets the bitrate and other parameters of the second serial interface of the ATMega644P. However, this function can only be used if the input pin of the serial system interface is at PD1. Otherwise it is aborted with an error message.
The bits 0...2 are responsible for the bit rate, the following bit rates are possible:


bbb Bit rate (bps)
000 1200
001 2400
010 4800
011 9600 (default)
100 19200
101 31250 (MIDI)
110 38400
111 57600


Bit 4 sets the number of stop bits:


b Stop Bits
0 1 stop bit
1 2 stop bits


With bits 5...7 one of 8 different data formats can be selected:


bbb format
000 8 bits, no parity bit
001 8 bits, even parity
010 6 bits, no parity bit
011 8 bits, odd parity
100 7 bits, no parity bit
101 7 bits, even parity
110 5 bits, no parity bit
111 7 bits, odd parity


The modes 0x00...0x07 are compatible with earlier versions. Further setting possibilities arise, of course, if OUT commands are accessed directly on the registers of the USART.
01 EBAUD 5
sets the bitrate of the second serial interface to 31250Bps (MIDI), format 8/N/1.

2.7 PUMP n

Disables the charge pump for the serial interface (n=0) or on (n=1).
01 PU 1
turns on the charge pump. The charge pump is also switched on by default after the start.

2.8 XSEND n,a

outputs a data block from the array via the XMODEM protocol. N is the block number and a is the array position (0...640). But you have to take care of the ACK/NAK handling yourself.
01 SGET C:IF C<>21 THEN GOTO 1
02 FOR Z=0 TO 5:A=Z*128
03 XSEND Z,A
04 SGET C:IF C=21 THEN GOTO 3
05 NEXT:SPUT 4
This program sends the complete array content via X-Modem to another device.

2.9 XREC(a)

reads a data block into the array via the XMODEM protocol. A is the array position (0...640). However, you have to take care of the ACK/NAK and Error Handling yourself.
01 SPUT 21
02 FOR Z=0 TO 5:A=Z*128
03 C=XREC(A):SPUT 6:NEXT
04 SGET C: SPUT 6
This program reads the entire array content via X-modem from another device. A reception error is simply aborted. But this could be intercepted with ONERR .

2.10 ICOMM adr,start,num [IC]

Generic I2C routine. The first parameter adr specifies the slave address. At the same time, it is determined with bit 0 whether to write (0) or read (1). The other two parameters indicate the start address in the array and the number of bytes to be transferred.
01 DATA HI(B),LO(B),LO(A),HI(A):ICOMM $a0,0,4
02 SYNC 1
Writes the value of variable A to address B of an I2C-EEPROM (>24C16) with the address 0. It is important to pay attention to the order of the bytes, since with I2C EEPROM the high byte of the address and then the low byte the address must be transmitted. You have to take care of any waiting times after the action. A write to the EEPROM followed by a read will most certainly give an I2C error, SYNC 2 will take a break of at least 20ms. If the number of bytes to be written is set to 0, bytes are output from the array until 0x00 is detected. In read mode, a 0 means that the number of bytes to be read is read in first. An I2C slave that does not want to send anything has to send back only a 0x00 which is answered with an ACK . A dummy byte as in previous versions is no longer necessary.

3 Memory


3.1 EPOKE adr,dat [EP]

Stores a byte of data in the internal EEPROM. The addresses are 0...1999.
02 EPOKE V,$12
stores the value 18 to the address V in the internal EEPROM.

3.2 EPEEK(adr)

The function reads a byte from the internal EEPROM. The addresses are 0...1999.
02 W=EPEEK(V)
reads the value of EEPROM address V (internal EEPROM) and stores it in variable W.
An additional EEPROM (currently only 24C64...24C512) can be connected to the I2C interface. For other types, the same functionality (a little more complicated) can be realized via ICOMM .

3.3 XPOKE adr,dat [XP]

Stores a byte in the external EEPROM, the block address is defined in the configuration menu and can only be set there. The block addresses 6 and 7 are reserved for SRAM/FRAM, as they do not wait until the write process is completed.
01 XPOKE 100,C
stores the value of the variable C to the address 100.

3.4 XPEEK(adr)

The function reads a byte from the external EEPROM. The addresses are 0...$FFFF.
02 W=XPEEK(100)
reads the value of EEPROM address 100 (external EEPROM) and stores it in variable W.

3.5 VPOKE adr,dat [VP]

This command writes a byte to the image memory. The addresses 0...2759 are possible.
01 VPOKE 0,66:VPOKE 690,$08
Write a black "B" on a green background in the upper left corner of the screen.

3.6 VPOKE adr,arrayadr,num [VP]

If three parameters are specified in VPOKE, it is possible to write whole byte sequences to the image memory at once. As address again 0...2759 is possible. The second parameter is an array position in the byte area, starting from which the data to be written is. The third parameter specifies how often the sequence is written to the image memory.
In the array itself, the data is in pairs as bytes. The first byte indicates the value to be written and the second byte indicates the bytes to be skipped thereafter. The second value can be between 0 and 127, bit 7 is set (value >127), 128 is subtracted, the offset is executed normally and then the sequence is ended.
01 DA 0,65,0,66,0,67,27+128
02 VP 0,0,10
writes 10x among each other "ABC".

3.7 VPEEK(adr)

The function reads a byte from the image memory. The addresses 0...2759 are possible.
01 ? "A"
02 ? VPEEK(0)
should output an "A" in the first line and 65 in the second line (this is the ASCII value of "A").

3.8 PAGE num

With this function, the position of the array area 768...1023 can be set in the external memory. The values ​​are 0...255, which gives a theoretically usable memory area of ​​64 kilobytes.
01 PAGE 0
sets the window to the first 256 bytes in the external RAM.

3.9 CCHAR src-char,dest-char

Copies 4 individual characters from the built-in ROM font to the custom character set in Video mode. Src-char is the character number in the ROM character set (0...255) and dest-char is the character number in the RAM character set (0...127). If several characters are to be copied, this must be done in a loop.

3.10 CCHAR src-char,dest-char,color

Copies 6 individual characters from the built-in ROM font to the custom character set in Video mode. Src-char is the character number in the ROM character set (0...255) and dest-char is the character number in the RAM character set (0...63). The value color results from foreground color + 16 * background color for the copy. If several characters are to be copied, this must be done in a loop.

4 Filesystem functions

If you are already familiar with personal computers, you will have to rethink now, because the file system of the AVR-ChipBasic2 is a bit different. Prerequisite for working with files is a Dataflash module, which is plugged into the programming port. Depending on the type, up to 0.5 or 1 megabyte of data can be stored. Of course, it is always a little less, because the data also wants to be organized, which in turn takes up space on the medium. In order to work with the Dataflash module, it must be "formatted". This happens in the DFLASH menu, which can be reached via the main menu. In contrast to volatile memories (RAM) or hard disks, write accesses to flash or EEPROM memory are only possible in limited numbers. In most cases, this number ranges between 10,000 and 1 million, depending on the type of storage and the manufacturer. In order to "wear out" the memory blocks as evenly as possible, they contain a counter, which is incremented by 1 each time a write is made. When a file is created, blocks with the lowest possible count are used, and even if you write to the same block frequently, you may find a new block with a lower count. But you do not have to worry about that, the whole thing happens completely transparent, but can lead to short-term delays in the program. The Dataflash modules should not be formatted too often as they will lose information about the "wear" of the blocks. The free space is divided into blocks (pages) of 256 bytes, which in turn can be assigned to a maximum of 128/256 files. Each file can contain a minimum of 1 and a maximum of 128 data blocks, allowing file sizes from 256 bytes to 32 kilobytes. File names, as they are known from the PC, are not the same here. To make files distinguishable in the Fileselect box, they have a hard-coded type and the first 12 bytes are displayed as a file name. When USR files are created, a more or less unique identification should also be written in the first 12 bytes. For the sake of simplicity, you can also reserve the first block of the file for the name only, even if it gives away space. Otherwise, simply work with the file number. In addition, there are the commands RREAD and RWRITE, with which Pages can be read or written directly in the dataflash.

4.1 FTYPE(n)

The function FTYPE returns either the flash type (n=-1) or the file type of the file n. For n=-1, the result is


value meaning
0 no data flash connected
2048 4MBit Dataflash connected
4096 8MBit Dataflash connected


for 0<=n<= 255 the result is (currently)


value meaning
252 File is not used
16 BASIC program
18 Backup file
20 USR file
22 Chip-8 file
24 AVR binary
26 GPS location list
28 Sampling data
30 Logic block definition
31 Image file
32 Screenshot file
34 S12(X) binary
-1 File number does not exist




4.2 FSIZE(n)

The FSIZE(n) function returns either the number of available files/pages or the size of a file in 256 bytes pages.


n return value
-1 Number of free files
-2 Number of free pages
0...255 Number of pages in the file or 0 (not used)

4.3 FCREATE f,p [FCR]

Generates the USR file f with p pages. The number of pages can be between 1 and 128, which corresponds to a file size of 256 bytes to 32 Kbytes. Since FCREATE terminates in the event of an error, FTYPE and FSIZE should first be used to ensure that the file can also be generated. Files of the type USR (file type 0x14) are always created, unless the third parameter specifies a different file type.
40 'create file F with P pages
41 'R=F or -1 if failed
42 R=-1:IF P<1 THEN RETURN
43 IF P>128 THEN RETURN
44 IF FTYPE(-1)=0 THEN RETURN
45 IF FTYPE(F)<>0 THEN RETURN
46 IF FSIZE(-2)<P THEN RETURN
47 FCREATE F,P: R=F: RETURN
The subroutine generates the file F with P pages if possible. In the variable R the result is then: either the file number F or -1, if the creation of the file is not possible. It should be noted that the last third of the array (cell 512-767) is used temporarily for this function and data located there is overwritten.

4.4 FWRITE f,p,a [FWR]

Writes 256 bytes from the array to the page P of file F. The third parameter determines the array position:


a array area
0 0...255
1 256...511
2 512...767


Since FWRITE terminates in the event of an error, FTYPE and FSIZE should first be used to ensure that the page can be written.
50 'write array 0...255 to
51 'file F in page P
52 R=-1:IF P<1 THEN RETURN
53 IF FTYPE(F)<>20 THEN RETURN
54 IF P>FSIZE(F) THEN RETURN
55 FWRITE F,N,0: R=F: RETURN
The subroutine writes the contents of the array cells 0...255 into the Page P of File F. In the variable R the result is: either the file number F or -1, if the writing of the page is not possible.

4.5 FREAD f,p,a [FRD]

Reads 256 bytes from Page P of File F and writes them into the array. The third parameter again determines the array position:


a array area
0 0...255
1 256...511
2 512...767


Since FREAD terminates in the event of an error, it should first be ensured with FTYPE and FSIZE that the page can also be read.
50 'read page P of file F to
51 'array 256...511
52 R=-1:IF P<1 THEN RETURN
53 IF FTYPE(F)<>20 THEN RETURN
54 IF P>FSIZE(F) THEN RETURN
55 FREAD F,N,1: R=F: RETURN
The subroutine reads the contents of the page P of file F into the array cells 256...511. In the variable R the result is: either the file number F or -1, if the reading of the page is not possible.

4.6 FDELETE f [FDEL]

Deletes the file F if it exists and is of type USR. Since FDELETE terminates in the event of an error, FTYPE and FSIZE should first be used to ensure that the file exists.
56 'delete file F
57 R=-1
58 IF FTYPE(F)<>20 THEN RETURN
59 FDELETE F: R=F: RETURN
The subroutine clears the file F, if it exists.

4.7 FSELECT v,a [FSEL]

Represents the Fileselect box if a formatted Dataflash block is connected. The number of the selected file is then in the variable v. If the dataflash can not be addressed or the selection is canceled with the ESC key, the variable v is set to -1. The value a is the array position starting with the zero-terminated box header. The frame of the Fileselct box is drawn with the currently set foreground color, the background is always black. The original image content is restored after exiting the Fileselect box.
60 'draw fileselct box
61 DATA 0,"Select file:",0
62 FSELECT F,0: RETURN
The subroutine shows a Filelesect box entitled "Select file:".

4.8 FFIND(a)

Since the file system does not work with directories, you need the file number to write to or read from a specific file. The function FFIND serves this purpose . The parameter a is again a pointer to the byte area of ​​the array. The first byte indicates the desired file type (see table above), followed by the number of bytes to compare at the beginning of the file and the comparison pattern. Return value is the first found file number or -1, if no corresponding file was found.
10 DATA 0,252,0:F=FFIND(0)
It searches for the first free file (identifier 252) and returns the file number or -1 if there is no free file left.

5 Direct access to the Dataflash module

In some cases, it may be useful to write or read data directly from the file system functions to the Dataflash module. The following two commands are used for this purpose:

5.1 RREAD p,a [RRD]

Reads 256 bytes from Page P and writes them into the array. P is the page number in the dataflash and does not refer to a file. The second parameter again determines the array position:


a array area
0 0...255
1 256...511
2 512...767


Since RREAD terminates in the event of an error, it should be ensured that the page can also be read.

5.2 RWRITE p,a [RWR]

Writes 256 bytes from the array to page P. P is the page number in the dataflash and does not refer to a file.
Warning! This feature can destroy the file system and should therefore be used with caution or on unformatted dataflash building blocks. The second parameter determines the array position:


a array area
0 0...255
1 256...511
2 512...767


Since RWRITE terminates in the event of an error, it should be ensured that the page can also be written.

6 Loading and saving programs

Since the BASIC programs with 95 lines of 32 characters are not very lavish, there is the possibility to write programs at runtime to the Dataflash or to load from there.

6.1 LOADP f,p

Loads the program with the file number f to the program location p. It is not possible to overwrite the current program. If this is attempted, the program aborts with an error message.

6.2 SAVEP f,p

Writes the program from program location n to file number f. For this purpose, the file must either not exist or be a program file. Warning!, any existing file will be overwritten without any confirmation!
10 DATA 0,252,0:C=FFIND(0)
11 IF C<0 THEN E=1:RETURN
12 DATA 0,16,4,"Test"
13 D=FFIND(0)
14 IF D<0 THEN E=2:RETURN
15 SAVEP C,8:LOADP D,8
16 GOSUB 8,1:LOADP C,8
17 FDELETE C:E=0:RETURN
This subprogram searches for a free file location and for a program file that starts with "hello". If both are found, the current program 8 is saved on the free space, the hello program is loaded into program slot 8 and then GOSUB begins. When the program then returns by means of RETURN, the program originally at program location 8 is restored and the temporarily generated file is deleted. The called program should not change the variable C.

7 Messages and questions in the box



7.1 ALERT n

Displays an alert box. The data for this is in the array starting at position n. First there is a byte (foreground color + 16 * background color), followed by zero-terminated text. If the completion is missing 0x00, the output is aborted after 20 characters. The current screen content is saved in advance and restored after pressing the ENTER key.
01 DATA 0,97,"Hello World",0
02 ALERT 0
Draws an alert box with blue letters Hello World on a yellow background. If the Enter key is pressed, the box disappears.

7.2 ASK V,n

Displays a question box. The data for this is in the array starting at position n. First there is a byte (foreground color + 16 * background color), followed by zero-terminated text. If the value is 0x00, the output will be aborted after 20 characters.
01 DATA 0,97,"Continue?",0
02 ASK P,0
03 IF P=0 WAIT 20: GOTO 2
04 ? "The End"
If "Y" or Enter is pressed, P is assigned the value 1, if "N" or ESC is pressed, P is given the value 0. It is case-insensitive. The current screen content is saved in advance and restored after pressing a valid button.

8 Menu functions


8.1 MENU(n)

The MENU(n) function displays a user-defined menu. In this case, n points to a line in the current program, from which array text is stored in 1 or 2 comment lines. The last character in the first line contains two control bits. These can be set eg by means of the numbers "0"..."3":


Character Menu Properties
0 A menu level, function returns only when one of the keys listed in the next table is pressed.
1 Two menu levels, function returns only when one of the keys listed in the next table is pressed.
2 A menu level, function returns only when you press any key (except Shift, CTRL and Alt).
3 Two menu levels, function returns only when you press any key (except Shift, CTRL and Alt).


The following table lists the return values ​​that are displayed when you press the ESC and F1...F3 keys. For all other keys, the "normal" key code is returned.
Offset Button Return value
0...5 ESC 1
6...11 F1 2
12...17 F2 3
18...23 F3 4
24...29 F4 5
30...35 left CTRL + ESC 6
36...41 left CTRL + F1 7
42...47 left CTRL + F2 8
48...53 left CTRL + F3 9
54...59 left CTRL + F4 10


The following program displays a sample menu. The data for this can be found in lines 1 and 2
01 '1111112222223333334444445555551
02 '666666777777888888999999AAAAAA
03 A=MENU(1)
04 ? @0,0;"Menu:",A," "
05 B=KEY(2):IF A>1 GOTO 3
The left CTRL key can be used to switch between the two menu levels. It waits until a valid key (ESC, F1...F4) has been pressed and the last line of the last return value is displayed. ESC aborts the program.