Skip to content

PIXXI Internal Functions

Introduction

The 4D Labs family of embedded graphics processors are powered by a highly optimised soft-core virtual engine, E.V.E. (Extensible Virtual Engine). EVE was designed and created by 4D Labs in the early 2000’s and should not be confused by FTDI’s solution of EVE, which was developed a decent decade or so later.

EVE is a proprietary, high performance virtual processor with an extensive byte-code instruction set optimised to execute compiled 4DGL programs. 4DGL (4D Graphics Language) was specifically developed from ground up for the EVE engine core. It is a high-level language which is easy to learn and simple to understand yet powerful enough to tackle many embedded graphics applications.

4DGL is a graphics-oriented language allowing rapid application development. An extensive library of graphics, text and file system functions and the ease of use of a language that combines the best elements and syntax structure of languages such as C, Basic, Pascal, etc. Programmers familiar with these languages will feel right at home with 4DGL. It includes many familiar instructions such as IF..ELSE..ENDIF, WHILE..WEND, REPEAT..UNTIL, GOSUB..ENDSUB, GOTO as well as a wealth of (chip-resident) internal functions that include SERIN, SEROUT, GFX_LINE, GFX_CIRCLE and many more.

This document covers the internal (chip-resident) functions available for the PIXXI-28 and PIXXI-44 processors. This document should be used in conjunction with the 4DGL Programmers Reference Manual.

Internal Functions Summary

PIXXI Internal functions can be categorized based on usage as listed below:

C Type Functions

isdigit

Tests the character parameter and returns a 1 if the character is an ASCII digit else returns a 0. Valid Range: "0123456789"

Syntax: isdigit(char);

Argument Description
char Specifies the ASCII character for the test

Returns: 1 if character is ASCII digit, otherwise 0

Example

func main()
    var ch;    
    print("Serial Input Test\nDownload prog to flash\n");
    print("Then use debug terminal\n");
    to(COM0); print("serial input test:\n");
    repeat
        ch := serin();
        if (ch != -1) 
            print([CHR]ch); // if a key was received from PC,  print its ascii value
            if (isdigit(ch))  print("Character is an ASCII digit\n");
            if (isxdigit(ch)) print("Character is ASCII Hexadecimal\n");
            if (isupper(ch))  print("Character is ASCII uppercase letter\n");
            if (islower(ch))  print("Character is ASCII uppercase letter\n");
            if (isalpha(ch))  print("Character is ASCII uppercase or lowercase\n");
            if (isalnum(ch))  print("Character is an ASCII Alphanumeric\n");
            if (isprint(ch))  print("Character is a printable ASCII\n");
            if (isspace(ch))  print("Character is a space type character\n");
        endif
    forever
endfunc

isxdigit

Tests the character parameter and returns a 1 if the character is an ascii hexadecimal digit else returns a 0. Valid Range: "0123456789ABCDEF"

Syntax: isxdigit(char);

Argument Description
char Specifies the ASCII character for the test

Returns: 1 if character is ASCII hexadecimal digit, otherwise 0

Example: Refer to isdigit() for an example

isupper

Tests the character parameter and returns a 1 if the character is an ASCII uppercase letter else returns a 0. Valid Range: "ABCDEF....WXYZ"

Syntax: isupper(char);

Argument Description
char Specifies the ASCII character for the test

Returns: 1 if character is ASCII uppercase letter, otherwise 0

Example: Refer to isdigit() for an example

islower

Tests the character parameter and returns a 1 if the character is an ASCII lowercase letter else returns a 0. Valid Range: "abcd....wxyz"

Syntax: islower(char);

Argument Description
char Specifies the ASCII character for the test

Returns: 1 if character is ASCII lowercase letter, otherwise 0

Example: Refer to isdigit() for an example

isalpha

Tests the character parameter and returns a 1 if the character is an ASCII lowercase or uppercase letter else returns a 0. Valid Range: "abcd....wxyz", "ABCD....WXYZ"

Syntax: isalpha(char);

Argument Description
char Specifies the ASCII character for the test

Returns: 1 if character is ASCII lowercase or uppercase letter, otherwise 0

Example: Refer to isdigit() for an example

isalnum

Tests the character parameter and returns a 1 if the character is an ASCII alphanumeric character else returns a 0. Valid Range: "abcd....wxyz", "ABCD....WXYZ", "0123456789"

Syntax: isalnum(char);

Argument Description
char Specifies the ASCII character for the test

Returns: 1 if character is ASCII alphanumeric character, otherwise 0

Example: Refer to isdigit() for an example

isprint

Tests the character parameter and returns a 1 if the character is a printable ASCII character else returns a 0. Valid Range: 0x20... 0x7F

Syntax: isprint(char);

Argument Description
char Specifies the ASCII character for the test

Returns: 1 if character is a printable ASCII character, otherwise 0

Example: Refer to isdigit() for an example

isspace

Tests the character parameter and returns a 1 if the character is any one of the space type character else returns a 0. Valid Range: space, formfeed, newline, carriage return, tab, vertical tab.

Syntax: isspace(char);

Argument Description
char Specifies the ASCII character for the test

Returns: 1 if character is a space character, otherwise 0

Example: Refer to isdigit() for an example

toupper

Tests the character parameter and if the character is a lowercase letter it returns the uppercase equivalent else returns the input character. Valid Range: "abcd ... wxyz"

Syntax: toupper(char);

Argument Description
char Specifies the ASCII character to convert

Returns: The uppercase equivalent of the input character if input is a lowercase character. Otherwise, it returns back the input character.

Example

func main()
    var ch, Upconvch, Loconvch;
    gfx_Cls();

    txt_Set(FONT_ID, FONT2);
    print ("Serial Input Test\n");
    print ("Download prog to flash\n");
    print ("Then use debug terminal\n");

    to(COM0); print("serial input test:\n");
    repeat // now just stay in a loop
        ch := serin();
        if (ch != -1)           // if a key was received from PC,  
            print([CHR] ch);    // print its ascii value
            if (isupper(ch)) 
                print("Uppercase ASCII found. Converting to lowercase");
                Loconvch := tolower(ch);
            endif
            if (islower(ch)) 
                print("Lowercase ASCII found. Converting to Uppercase");
                Upconvch := toupper(ch);
            endif
        endif
    forever
endfunc

tolower

Tests the character parameter and if the character is an uppercase letter it returns the lowercase equivalent else returns the input character. Valid Range: "ABCD ... WXYZ"

Syntax: tolower(char);

Argument Description
char Specifies the ASCII character to convert

Returns: The lowercase equivalent of the input character if input is a uppercase character. Otherwise, it returns back the input character.

Example: Refer to toupper() for an example

LObyte

Returns the lower byte (lower 8 bit) of a 16-bit variable.

Syntax: LObyte(var);

Argument Description
var User variable

Returns: The lower byte (lower 8 bit) of a 16-bit variable

Example

myvar := LObyte(myvar2);

HIbyte

Returns the upper byte (upper 8 bit) of a 16-bit variable.

Syntax: HIbyte(var);

Argument Description
var User variable

Returns: The upper byte (upper 8 bit) of a 16-bit variable

Example

myvar := HIbyte(myvar2);

ByteSwap

Returns the swapped upper and lower bytes of a 16-bit variable.

Syntax: ByteSwap(var);

Argument Description
var User variable

Returns: Returns the endian swapped value of a 16-bit variable.

Example

myvar := ByteSwap(myvar2);

CRC Functions

crc_CSUM_8

Calculates the Checksum CRC as an 8 bit number. This is equivalent to simple addition of all bytes and returning the negated sum an 8 bit value. For the standard test string "123456789", crc_CSUM_8 will return 0x23.

Syntax: crc_CSUM_8(buf, count);

Argument Description
buf Source memory buffer. This is a string pointer.
count Number of bytes to be used to generate the CRC.

Returns: The generated 8-bit checksum CRC

Example

var crc;
var buf[5];
// [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]
to (buf); putstr("123456789");
crc := crc_CSUM_8(str_Ptr(buf), 10);

Note

If you calculate all of the incoming data including the CRC, the result should be 0x00.

Display I/O Functions

disp_SetReg

Sets the Display driver IC register from display driver datasheet.

Syntax: disp_SetReg(register, data);

Argument Description
register Refer to the display driver datasheet
data Refer to the display driver datasheet

Returns: None

disp_setGRAM

Prepares the (Graphics RAM) GRAM area for user access. The lower 16 bits of the pixel count in the selected area is returned This is usually all that is needed unless GRAM area exceeds 2562. A copy of the 32-bit value can be found in GRAM_PIXEL_COUNT_LO and GRAM_PIXEL_COUNT_HI.

Syntax: disp_setGRAM(x1, y1, x2, y2);

Argument Description
x1 Top position in the GRAM window
y1 Left position in the GRAM window
x2 Bottom position in the GRAM window
y2 Right position in the GRAM window

Returns: The LO word of the 32-bit pixel count is returned

Example

disp_setGRAM(40, 60, 100, 150);

disp_WrGRAM

Data can be written to the GRAM consecutively using this function once the GRAM access window has been setup.

Syntax: disp_WrGRAM(colour);

Argument Description
colour Pixel color to be populated

Returns: None

Example

disp_WrGRAM(0xFFF0);

disp_WriteControl

Sends a 16-bit value to the display bus. Refer to individual datasheets for the display for more information This function is used to extend the capabilities of the user code to gain access to the the display hardware.

Syntax: disp_WriteControl(value);

Argument Description
value Specifies the 16-bit value to be written to the display control register

Returns: None

Example

disp_WriteControl(0x0FFA);

disp_WriteWord

Sends a 16-bit value to the display bus. Refer to individual datasheets for the display for more information. This function is used to extend the capabilities of the user code to gain access to the the display hardware.

Syntax: disp_WriteWord(value);

Argument Description
value Specifies the 16-bit value to be written to the display data register

Returns: None

Example

disp_WriteWord(0x7FF0);

disp_ReadWord

Read a word from the display controller.

Syntax: disp_ReadWord(command, dummy);

Argument Description
command Specifies the value to be read from the display data register
dummy Dummy byte required by for LCD read command

Returns: 16-bit value in the register

Example

var val;
val := disp_ReadWord(0, 0);

Note

  • Many displays are write only
  • Some SPI displays required the command be given as part of the read sequence.
  • Use -1 if no command is to be written.

disp_Sync

Allows the program to synchronise writing to the hardware for flicker free operation. Some experimentation may be needed to find an optimum line for disp_Sync depending on the graphics operation. The higher the value, the slower the throughput. A certain point will be reached (number of scanlines + blanking lines within the vertical retrace period) where it will just 'hang up' stopping the entire process. Eg, in 640x480 mode, if the 'lines' value is 507, operation will be slowest (as it’s right at the end of the blanking period) and 508 will cause a hangup situation as it is above the highest scanline value.

Syntax: disp_Sync(line);

Argument Description
line scan line

Returns: 16-bit value in the register

Note

Applies to 4.3” modules only.

disp_Disconnect

This function disconnects the display driver pins and/or reconfigures it to achieve its lowest possible power consumption. Use after disabling peripheral power to ensure the minimal power usage by the display. disp_Init() should be used to reinitialise the display.

Syntax: disp_Disconnect();

Returns: None

disp_Init

This function is used to initialise the display.

This is useful in several situations, however mainly for modules which can disable the power supply to the display for low power sleep modes. This function is required to re-initialise the display once power to the display has been restored, so the display is usable once again.

Syntax: disp_Init();

Returns: None

FAT16 File Functions

file_Error

Returns the most recent error code or 0 if there were no errors.

Here are the possible errors:

Error Code Value Description
FE_OK 0 IDE Function Succeeded
FE_IDE_ERROR 1 IDE command execution error
FE_NOT_PRESENT 2 CARD not present
FE_PARTITION_TYPE 3 WRONG partition type, not FAT16
FE_INVALID_MBR 4 MBR sector invalid signature
FE_INVALID_BR 5 Boot Record invalid signature
FE_MEDIA_NOT_MNTD 6 Media not mounted
FE_FILE_NOT_FOUND 7 File not found in open for read
FE_INVALID_FILE 8 File not open
FE_FAT_EOF 9 Fat attempt to read beyond EOF
FE_EOF 10 Reached the end of file
FE_INVALID_CLUSTER 11 Invalid cluster value > maxcls
FE_DIR_FULL 12 All root dir entry are taken
FE_MEDIA_FULL 13 All clusters in partition are taken
FE_FILE_OVERWRITE 14 A file with same name exist already
FE_CANNOT_INIT 15 Cannot init the CARD
FE_CANNOT_READ_MBR 16 Cannot read the MBR
FE_MALLOC_FAILED 17 Malloc could not allocate the FILE struct
FE_INVALID_MODE 18 Mode was not r.w.
FE_FIND_ERROR 19 Failure during FILE search
FE_INVALID_FNAME 20 Invalid Filename
FE_INVALID_MEDIA 21 bad media
FE_SECTOR_READ_FAIL 22 Sector Read fail
FE_SECTOR_WRITE_FAIL 23 Sector write fail

Syntax: file_Error();

Return: Error Code

Example

e := file_Error();

Note

This function is only available for use on the uSD based PmmC version.

file_Count

Returns number of files found that match the criteria. The wild card character '*' matches up with any combination of allowable characters and '?' matches up with any single allowable character.

Syntax: file_Count(filename);

Argument Description
filename Filename of the file(s) for the search (passed as a string)

Return: Number of files that match the criteria

Example

count := file_Count("*.4XE"); // Returns number of files with ".4XE"

Note

This function is only available for use on the uSD based PmmC version.

file_Dir

Streams a string of file names that agree with the search key. Returns number of files found that match the criteria. The wild card character '*' matches up with any combination of allowable characters and '?' matches up with any single allowable character.

Syntax: file_Dir(filename);

Argument Description
filename Filename of the file(s) for the search (passed as a string)

Return: Number of files found that match the criteria

Example

count := file_Dir("*.4XE"); //Returns number of files with ".4XE"

Note

This function is only available for use on the uSD based PmmC version.

file_FindFirst

Returns true if at least one file exists that satisfies the file argument. Wildcards are usually used so if file_FindFirst returns true, further tests can be made using file_FindNext() to find all the files that match the wildcard class. Note that the stream behaviour is the same as file_Dir().

Syntax: file_FindFirst(fname);

Argument Description
fname Filename of the file(s) for the search (passed as a string)

Return: 1 if at least one file exists that satisfies the criteria, 0 otherwise

Example

if (file_FindFirst("*.4XE")) 
   print("File Found"); 
endif

Note

This function is only available for use on the uSD based PmmC version.

file_FindNext

Returns true if more file exists that satisfies the file argument that was given for file_FindFirst. Wildcards must be used for file_FindFirst(), else this function will always return zero as the only occurence will have already been found. Note that the stream behaviour is the same as file_Dir().

Syntax: file_FindNext();

Return: 1 if at least one file exists that satisfies the criteria in file_FindFirst(), 0 otherwise

Example

while (file_FindNext())
   filecount++;
wend

Note

This function is only available for use on the uSD based PmmC version.

file_Exists

Tests for the existence of the file provided with the search key. Returns true if found.

Syntax: file_Exists(fname);

Argument Description
fname Filename of the file for the search (passed as a string)

Return: 1 if file exists, 0 otherwise

Example

if (file_Exists("fil1.4XE")) 
   print("File Found") ;
endif

Note

This function is only available for use on the uSD based PmmC version.

file_Open

Returns handle if file exists. The file "handle" created is now used as reference for "filename" for further file functions such as file_Close(), etc. For FILE_WRITE and FILE_APPEND modes ('w' and 'a') the file is created if it does not exist.

If the file is opened for append and it already exists, the file pointer is set to the end of the file ready for appending, else the file pointer will be set to the start of the newly created file.

If the file was opened successfully, the internal error number is set to 0 (ie: - no errors) and can be read with the file_Error() function.

For FILE_READ mode ('r') the file must exist else a null handle (0) is returned and the 'file not found' error number is set which can be read with the file_Error() function.

Syntax: file_Open(fname, mode);

Argument Description
fname Filename of the file to be opened (passed as a string)
mode FILE_READ ('r'), FILE_WRITE ('w') or FILE_APPEND ('a')

Return: File handle if file exists, null (0) otherwise.

Example

handle := file_Open("myfile.txt", 'r');

Note

  • This function is only available for use on the uSD based PmmC version.
  • If a file is opened for write mode 'w', and the file already exists, the operation will fail. Unlike C and some other languages where the file will be erased ready for re-writing when opened for writing, 4DGL offers a simple level of protection that ensures that a file must be purposely erased before being re-written.
  • A file opened with FILE_APPEND may be randomly read and or written. Also any altered file will have the Archive bit set in the directory entry.

file_Close

Closes file created by file_Open().

Syntax: file_Close(handle);

Argument Description
handle the file handle that was created by file_Open used to reference the file

Return: True (1) if file closed, False (0) otherwise.

Example

res := file_Close(hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_Read

Reads the number of bytes specified by "size" from the file referenced by "handle" into a destination memory buffer.

Syntax: file_Read(*destination, size, handle);

Argument Description
destination Destination memory buffer, this is a normal word aligned address
size Number of bytes to be read
handle File handle created by file_Open referencing the file to read

Return: Number of characters read

Example

res := file_Read(memblock, 20, hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_Seek

Places the file pointer at the required position in a file that has been opened in 'r' (read) or 'a' (append) mode. In append mode, file_Seek does not expand a filesize, instead, the file pointer (handle) is set to the end position of the file, eg:- assuming the file size is 10000 bytes, file_Seek(handle, 0, 0x1234); will set the file position to 0x00001234 (byte position 4660) for the file handle, so subsequent data may be read from that position onwards with file_GetC(...), file_GetW(...), file_GetS(...), or an image can be displayed with file_Image(...). Conversely, file_PutC(...), file_PutW(...) and file_PutS(...) can write to the file at the position. A FE_EOF (end of file error) will occur if you try to write or read past the end of the file.

Syntax: file_Seek(handle, HiWord, LoWord);

Argument Description
handle File handle created by file_Open referencing the file
HiWord Contains the upper 16bits of the memory pointer into the file
LoWord Contains the lower 16bits of the memory pointer into the file

Return: True if successful (usually ignored)

Example

res := file_Seek(hSource, 0x0000, 0x1234);

Note

This function is only available for use on the uSD based PmmC version.

file_Index

Places the file pointer at the position in a file that has been opened in 'r' (read) or 'a' (append) mode. In append mode, file_Index does not expand a filesize, instead, the file pointer (handle) is set to the end position of the file, eg:- assuming the record size is 100 bytes, file_Index(handle, 0, 100, 22); will set the file position to 2200 for the file handle, so subsequent data may be read from that position onwards with file_GetC(...), file_GetW(...), file_GetS(...), or an image can be displayed with file_Image(...). Conversely, file_PutC(...), file_PutW(...) and file_PutS(...) can write to the file at the position. A FE_EOF (end of file error) will occur if you try to write or read past the end of the file.

Syntax: file_Index(handle, HiSize, LoSize, recordNum);

Argument Description
handle File handle created by file_Open referencing the file
HiSize Contains the upper 16bits of the size of the file records
LoSize Contains the lower 16bits of the size of the file records
recordNum The index of the required record

Return: True if successful (usually ignored)

Example

res := file_Index(hSource, 0, 100, 22);

Note

This function is only available for use on the uSD based PmmC version.

file_Tell

Returns the current value of the file pointer.

Syntax: file_Tell(handle, &HiWord, &LoWord);

Argument Description
handle File handle created by file_Open referencing the file
HiWord Contains the upper 16bits of the memory pointer into the file
LoWord Contains the lower 16bits of the memory pointer into the file

Return: True if successful (usually ignored)

Example

res := file_Tell(hSource, HIptr, LOptr);

Note

This function is only available for use on the uSD based PmmC version.

file_Write

Writes the number of bytes specified by "size" from the source buffer into the file referenced by "handle".

Syntax: file_Write(*source, size, handle);

Argument Description
source Source memory buffer, this is a byte aligned string pointer
size Number of bytes to be written
handle File handle created by file_Open referencing the file

Return: Number of bytes written

Example

res := file_Write(memblock, 20, hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_Size

Reads the 32-bit file size and stores it into two variables

Syntax: file_Tell(handle, &HiWord, &LoWord);

Argument Description
handle File handle created by file_Open referencing the file
HiWord Variable to contain the upper 16bits of the file size
LoWord Variable to contain the lower 16bits of the file size

Return: True if successful (usually ignored)

Example

res := file_Size(hSource, sizeHi, sizeLo);

Note

This function is only available for use on the uSD based PmmC version.

file_Image

Display an image from the file stream at screen location specified by x, y (top left corner). If there is more than 1 image in the file, it can be accessed with file_Seek(...).

Syntax: file_Image(x, y, handle);

Argument Description
x X-position of the image to be displayed
y Y-position of the image to be displayed
handle File handle created by file_Open referencing the file

Return: Returns a copy of the file_Error() error code

Example

err := file_Image(x, y, handle);

Note

This function is only available for use on the uSD based PmmC version.

file_ScreenCapture

Save an image of the screen shot to file at the current file position.

The image can later be displayed with file_Image(...). The file may be opened in append mode to accumulate multiple images. Later, the images can be displayed with file_Seek(...). The image is saved from x, y (with respect to top left corner), and the capture area is determined by "width" and "height".

Syntax: file_ScreenCapture(x, y, width, height, handle);

Argument Description
x X-position of the image to be captured
y Y-position of the image to be captured
width Width of the area to be captured
height Height of the area to be captured
handle File handle created by file_Open referencing the file for storing the image(s)

Return: 0 if successful

Example

file_Mount(); 
hFile := file_Open("test.img", 'a'); // open a file to save the image 
file_ScreenCapture(20,20,100,100, hFile);// save an area 
file_ScreenCapture(0,0,50,50, hFile);    // (save another area) 
file_Close(hFile);                       // now close the file 

// and to display the saved area(s)

hFile := file_Open("test.img", 'r');    // open the saved file 
file_Image(20,180, hFile);              // display the image 
file_Image(150,180, hFile);             // (display the next image) 
file_Close(hFile);
file_Unmount();                         // finished with file system

Note

This function is only available for use on the uSD based PmmC version.

file_PutC

This function writes the byte specified by "char" to the file, at the position indicated by the associated file-position pointer and advances the pointer appropriately (incremented by 1). The file must be previously opened with 'w' (write) or 'a' (append) modes.

Syntax: file_PutC(char, handle);

Argument Description
char Data byte about to be written
handle File handle created by file_Open referencing the file to write to

Return: Number of bytes written

Example

file_PutC('A', hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_GetC

This function reads a byte from the file, at the position indicated by the associated file-position pointer and advances the pointer appropriately (incremented by 1). The file must be previously opened with 'r' (read) mode.

Syntax: file_GetC(handle);

Argument Description
handle File handle created by file_Open referencing the file to read from

Return: the data byte read from the file

Example

mychar := file_GetC(hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_PutW

This function writes word sized (2 bytes) data specified by "word" to the file, at the position indicated by the associated file-position pointer and advances the pointer appropriately (incremented by 2). The file must be previously opened with 'w' (write) or 'a' (append) modes.

Syntax: file_PutW(word, handle);

Argument Description
word Data about to be written
handle File handle created by file_Open referencing the file to write to

Return: Number of bytes written

Example

file_PutW(0x1234, hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_GetW

This function reads a word (2 bytes) from the file, at the position indicated by the associated file-position pointer and advances the pointer appropriately (incremented by 2). The file must be previously opened with 'r' (read) mode.

Syntax: file_GetW(handle);

Argument Description
handle File handle created by file_Open referencing the file to read from

Return: 16-bit data read from the file

Example

val := file_GetW(hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_PutS

This function writes an ASCIIZ (null terminated) string from a buffer specified by "*source" to the file, at the position indicated by the associated file-position pointer and advances the pointer appropriately. The file must be previously opened with 'w' (write) or 'a' (append) modes.

Syntax: file_PutS(*source, handle);

Argument Description
source A pointer to the string to be written.
handle File handle created by file_Open referencing the file to write to

Return: Number of characters written (excluding the null terminator)

Example

file_PutS(mystring, hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_GetS

This function reads a line of text to a buffer (specified by "*string") from a file at the current file position indicated by the associated file-position pointer and advances the pointer appropriately. Characters are read until either a newline or an EOF is received or until the specified maximum "size" is reached. In all cases, the string is null terminated. The file must be previously opened with 'r' (read) mode.

Syntax: file_GetS(*string, size, handle);

Argument Description
string Destination buffer to store the string in
size The maximum number of bytes to be read from the file
handle File handle created by file_Open referencing the file to read from

Return: Number of characters read from file (excluding the null teminator)

Example

res := file_GetS(mystring, 80, hndl);

Note

This function is only available for use on the uSD based PmmC version.

file_Erase

This function erases a file on the disk.

Syntax: file_Erase(fname);

Argument Description
fname Filename of the file to be erased (passed as a string)

Return: True (1) if successful, False (0) otherwise

Example

res := file_Erase("myfile.txt"); 

Note

This function is only available for use on the uSD based PmmC version.

file_Rewind

Resets the file pointer to the beginning of a file that has been opened in 'r' (read), 'w' (write), or 'a' (append) mode.

Syntax: file_Rewind(handle);

Argument Description
handle File handle created by file_Open referencing the file

Return: True (1) if successful, False (0) otherwise

Example

res := file_Rewind(hSource);

Note

This function is only available for use on the uSD based PmmC version.

file_LoadFunction

Load a function or program from disk and return a function pointer to the allocation. The function can then be invoked just like any other function would be called via a function pointer. Parameters may be passed to it in a conventional way. The function may be discarded at any time when no longer required, thus freeing its memory resources.

The loaded function can be discarded with mem_Free(..). Note that any pointer references passed to the child function may not include references to the parents DATA statements or any static string references. Any string or array information must be in the parent’s global or local memory space. The reason for this is that DATA statements and static strincs are contained in the parents CODE segment and cannot be accessed by the child process.

Syntax: file_LoadFunction(fname);

Argument Description
fname Filename of the 4DGL application program that is about to be loaded into RAM

Return: Pointer to the memory allocation where the function has been loaded from file which can be then used as a function call

Examples

var titlestring[20];
var textstring[20];
to (titlestring); putstr("My Window Title");
to (textstring); putstr("My Special Message");
popupWindow := file_LoadFunction("popupWindow1.4fn");
if(!popupWindow) goto LoadFunctionFailed; // could not load the function

// then elsewhere in your program
res := popupWindow(MYMODE,titlestring,textstring);
if(res == QUIT_APPLICATION) goto exitApp;

// Later in your program, when popupWindow is no longer required 
// for the application

res := mem_Free(popupWindow);
if(!res) goto FreeFunctionFailed; // should never happen if memory not        
                                  // corrupted 

var fncHandle;   // a var for a handle to sliders2.4dg
var slidervals;  // reference var to access global vars in sliders.4dg

fncHandle := file_LoadFunction("sliders2.4xe"); // load the function
slidervals := fncHandle & 0x7FFF; // note that memory allocations
// for transient programs are biased with 8000h which must be removed.
slidervals++;    // note that all globals start at '1'

slidervals[0] := 25; // set sliders to initial positions
slidervals[1] := 20;
slidervals[2] := 30;
slidervals[3] := 15;
slidervals[4] := 35;
slidervals[5] := 20;
slidervals[6] := 40;
slidervals[7] := 25;
slidervals[8] := 45;
slidervals[9] := 5;

r := fncHandle();     // activate the function

print("Return value = 0x", [HEX] r,"\n");

// print the  values, they may have changed
print("Slider 1  ", slidervals[0]," Slider 2  ", slidervals[1],"\n");
print("Slider 3  ", slidervals[2]," Slider 4  ", slidervals[3],"\n");
print("Slider 5  ", slidervals[4]," Slider 6  ", slidervals[5],"\n");
print("Slider 7  ", slidervals[6]," Slider 8  ", slidervals[7],"\n");
print("Slider 9  ", slidervals[8]," Slider 10 ", slidervals[9],"\n");

mem_Free(fncHandle); // done with sliders, release its memory

Note

This function is only available for use on the uSD based PmmC version.

file_Run

Any memory allocations in the main FLASH program are released, however, the stack and globals are maintained.

The function 'main' in the called program accepts the arguments, if any. If arglistptr is 0, no arguments are passed, else arglistptr points to an array, the first element containing the number of additional elements in the array which contain the arguments.

The disk does not need to be mounted, file_Run automatically mounts the drive.

Syntax: file_LoadFunction(fname);

Argument Description
fname Filename of the 4DGL child program to be loaded into RAM and executed
arglistptr Pointer to the list of arguments to pass to the new program

Return: Value returned by main function in the called program

Example

#inherit "4DGL_16bitColours.fnc"
#inherit "FONT4.fnt"

#constant MAXBUTTONS 30 // for now, maximum number of buttons we want
                   // (also sets maximum number of files we can exec)

#STACK 500
//stack must be large enough to be shared with called program
#MODE RUNFLASH      
// This is a 'top down' main program and must be run from FLASH

//-------------------------------------------------------------------// local global variables
//-------------------------------------------------------------------
// NB:- demo assigns all arrays to MAXBUTTONS.
// The arrays could be dynamically assigned to minimise memory usage.
// There is break even point between extra code and smallish arrays.
var keyval;       // 0 if no key pressed else 1-n
var filenames;    // pointer to byte array that holds the filenames

var buttontexts[MAXBUTTONS]; // pointers into the filenames array 
//holds the filenames we use as button text

var vButtonState[MAXBUTTONS]; 
//button state flag( bit 0 = up:down state)
var vOldButtonState[MAXBUTTONS];        
// OLD button state flags (bit 0 = up:down state)

// (we keep 2 copies so we can test for a state change and only redraw when a state change occurs)

var touchX1[MAXBUTTONS];           // touch regions for the buttons
var touchY1[MAXBUTTONS];
var touchX2[MAXBUTTONS];
var touchY2[MAXBUTTONS];

var btnTextColor;                       // button text colour
var btnBtnColor;                        // button background colour
var buttoncount;                   // actual number of buttons created (set by number of *.4XE files we find on drive)

var tempstr[20];                // general purpose string, 40 bytes

#DATA
 byte fred 1,2,3,4,5,6,7,8,9,10,11,12
#END

/*===================================================================
Redraw the button matrix. Only draw buttons that have changed state.
The top lef corner of the button matrix is set with the xorg and yorg parameters depending on the font and text string width, the button matrix dynamically resizes.
Parameters:-
maxwidth    = rhs from xorg (in pixels) to cause wrap at rhs
maxwidth    = maximum matrix width (in pixel units)
buttoncount = number of buttons to display
font        = FONT1 to FONT4
xorg:yorg   = top left corner of button array
NB:- The  touch detect matrix array is updated when any button changes state.
When you need to draw the matrix for the first instance of the matrix, you must
call with mode = 1 to instantiate the buttons.
call with mode = 0 for normal button action.
===================================================================*/

func redraw(var bcount, var font, var xorg, var yorg, var maxwidth, var mode )

    var xgap, ygap, n, x1, y1, x2, y2;

    xgap := 2;
    ygap := 2;
    x1 := xorg;
    y1 := yorg;

    // if first, set all the buttons to the up state
    if (mode)
        n := 0;
        repeat
            vButtonState[n]:=UP;            
// set all the buttons to inverse state
            vOldButtonState[n]:=DOWN;       
// so we guarantee they are all drawn in the 'up' state (not pressed)
        until(++n >= buttoncount);
    endif

// check all the button states, if a change occured, draw the new button state and update the touch detect matrix array
    n := 0;
    repeat
        // if the button state has changed
        if ( vButtonState[n] != vOldButtonState[n])
            vOldButtonState[n] := vButtonState[n];

            // if we already have all the co-ordinates, use them
            if (!mode)
                x1 := touchX1[n];
                y1 := touchY1[n];
                x2 := touchX2[n];
                y2 := touchY2[n];
            endif

            // draw the button
            gfx_Button( vButtonState[n], x1, y1, btnBtnColor, btnTextColor, font, 1, 1, buttontexts[n] );

           // update the touch screen regions only during first build
            if (mode)
                x2 := gfx_Get(RIGHT_POS);
                y2 := gfx_Get(BOTTOM_POS);

                touchX1[n] := x1;
                touchY1[n] := y1;
                touchX2[n] := x2;
                touchY2[n] := y2;

                // calculate next button position
                x1 := x2 + xgap;
                if (x1 >= xorg + maxwidth)
                    x1 := xorg;
                    y1 := y2 + ygap;
                endif
            endif

        endif
    until (++n >= buttoncount);
endfunc

//===================================================================
// do something with the key data
// In this example, we reconstitute the button name to a file name
// by appending ".4XE" and then call the file_Run command to
// run an application.
//===================================================================
func sendkey()
    var p;

    p := buttontexts[keyval-1];
    to(tempstr); str_Printf(&p, "%s.4XE");

    txt_Set(TEXT_OPACITY, OPAQUE);
    txt_Set(FONT_ID , FONT4);
    txt_MoveCursor(3, 0);

    print ("                 ");

    if(file_Exists(str_Ptr(tempstr)))
        touch_Set(TOUCH_DISABLE);         // disable the touch screen
        txt_Set(TEXT_COLOUR, ORANGE);
        print ("\rRUN: ", [STR] tempstr );// run the required program
        pause(500);
        gfx_Cls();
        file_Run(str_Ptr(tempstr),0);   // just run the prog, no args
     else
        txt_Set(TEXT_COLOUR, RED);
        print ("\rFAULT: ", [STR] tempstr );  // run required program
        pause(1000);
    endif

endfunc

//===================================================================
// convert the touch co-ordinates to a key value
// returns 0 if no key down else return index 1..n of button
//===================================================================
func readKeys(var x, var y)

    var n, x1, y1, x2, y2, r;

    n := 0;
    r := 0;

    while (n < buttoncount && !r)
        x1 := touchX1[n];
        y1 := touchY1[n];
        x2 := touchX2[n];
        y2 := touchY2[n];
        n++;
        if (x >= x1 && x < x2 && y >= y1 && y < y2) r := n;
    wend

    return r;
endfunc

//==================================================================
func main()

    var k, n, state, x, y;
    var p, s, w, f;
redo:
    w := 140;
    f := FONT4;
    btnTextColor := BLACK;
    btnBtnColor := LIGHTGREY;

    gfx_Cls();
    gfx_Set(BEVEL_WIDTH, 2);

    txt_Set(FONT_ID, FONT3);
    print("Simple test for file_Run(...);\n");
    print("Memory available = ",mem_Heap(),"\n");

    if(!file_Mount())
        putstr("Disk not mounted");
        while(!file_Mount());
    else
        putstr("Disk mounted\n");
    endif

    buttoncount := file_Count("*.4xe");             
// count all the executable files on the drive
    print("4XE File count = ",buttoncount,"\n");

    n := buttoncount;       // k holds entry count
    if (!n)
        print("No 4XE executables\n");              
// critical error, nothing to run!
        repeat forever
    endif

    filenames := mem_AllocZ(n*13);                  
// allocate a buffer for the filenames
    if(!filenames)
        print("Out of memory\n");                   
// critical error, could not allocate buffer
        repeat forever
    endif

    to(filenames); file_Dir("*.4xe");               
// load the filenames array

    p := str_Ptr(filenames);    // point to the string

//assign array of string pointers and truncate filename extensions
    n := 0;
    while ( n < buttoncount )
        buttontexts[n++] := p;    // save pointer to the string
        p:=str_Find ( &p , "." ); // find end of required string
        str_PutByte(p++,'\0');    // change '.' to \0
        p := p + 4;               // skip over "4XE\n"
    wend

    touch_Set(TOUCH_ENABLE);      // enable the touch screen

    redraw(buttoncount, f, 10, 80, w, 1);               
// draw buttons for the first time

    // now just stay in a loop
    repeat
        state := touch_Get(TOUCH_STATUS);  // get touchscreen status
        x := touch_Get(TOUCH_GETX);
        y := touch_Get(TOUCH_GETY);

       if(state == TOUCH_PRESSED)          // if there's a press
            if (keyval := readKeys(x, y))
                vButtonState[keyval-1] := DOWN;             
// put button in DOWN state
                redraw(buttoncount, f, 10, 80, w, 0);        
// draw any button down states
            endif
        endif

        if(state == TOUCH_RELEASED)                          
// if there's a release
            if (keyval)
                vButtonState[keyval-1] := UP;               
// restore the buttons UP state
                redraw(buttoncount, f, 10, 80, w, 0);        
// draw any button up states
                sendkey();                                  
// do something with the key data
                keyval := 0;
// because prog(main prog) gave up all its allocations for file_Exec,
// we have lost our file mount info and the directory list so we must
// re-establish these to be able to continue. A better approach to
// ensure total stability for the main program is to reset the system
                // with SystemReset()
                //==================================
                // systemReset() // restart the main program
                // or
                goto redo;      // re-mount disk, reload filenames
                //==================================

            endif
        endif

    forever

    // mem_Free(filenames);                    
   // no need to release buffer, this prog is in flash and never exits.....
    // file_Unmount();                         // ditto

endfunc
//===================================================================

Note

This function is only available for use on the uSD based PmmC version.

file_Exec

This function is similar to file_Run, however, the main program in FLASH retains all memory allocations (eg file buffers, memory allocated with mem_Alloc etc)

Syntax: file_LoadFunction(fname);

Argument Description
fname Filename of the 4DGL child program to be loaded into RAM and executed
arglistptr Pointer to the list of arguments to pass to the new program

Return: Value returned by main function in the called program

Example

var args[4], l[50] ;

func main()
    var i ;

    putstr("Mounting...\n");         // must mount uSD for file_Exec
    if (!(file_Mount()))
        while(!(file_Mount()))
            putstr("Drive not mounted...");
            pause(200);
            gfx_Cls();
            pause(200);
        wend
    endif

    for (i := 0; i < sizeof(l); i++)  // init array that will be passed
        l[i] := i ;
    next
    args[0] := 2 ;              // init arg count
    args[1] := 1234 ;           // init arg 1, this cannot be changed
    args[2] := l ;              // init arg 2 to address of l

    print("main Program\n" ) ;
    i := file_Exec("uSDProg.4fn", args) ;
    print("Back in main program\n" ) ;
    print("uSD Program returned ", i, "\n") ; // number from return statement

    for (i := 0; i < sizeof(l); i++)     // find what changed in array
        if (l[i] != i) print("l[", i, "] was changed to ", l[i], "\n" ) ;
    next
    print("Done") ;

    repeat
    forever

endfunc
func main(var j, var *l)    // parameters appear in the normal way
                            // The * shows that l will be indexed. It
                            // simply stops the compiler issuing a 'notice'
    txt_FGcolour(WHITE);
    print("In file_Exec's Program\n") ;
    print("Parms=", j, " ", l, "(ptr to l)\n") ;   // can't change these
    print("Incrementing l[5] to ", ++l[5], "\n") ; // can change these
    print("Returning 188\n") ;                     // can return a value
    txt_FGcolour(LIME);
    return 188;
endfunc

Note

This function is only available for use on the uSD based PmmC version.

file_LoadImageControl

Reads a control file to create an image list.

The following are the modes of operation

Mode Description
0 It is assumed that there is a graphics file with the file extension "fname2.gci". In this case, the images have been stored in a FAT16 file concurrently, and the offsets that are derived from the "fname1.dat" file are saved in the image control so that the image control can open the file (*.gci) and use file_Seek(...) to get to the position of the image which can then automatically be displayed using file_Image(...).
Mode 0 builds the image control quickly as it only scans the *.dat file for the file offsets and saves them in the relevant entries in the image control. The penalty is that images take longer to find when displayed due to file_Seek(...) overheads.
1 It is assumed that there is a graphics file with the file extension "fname2.gci". In this case, the images have been stored in a FAT16 file concurrently, and the offset of the images are saved in the image control so that image file (*.gci) can be mapped to directly. The absolute cluster/sector is mapped so file seek does not need to be called internally. This means that there is no seek time penalty, however, the image list takes a lot longer to build, as all the seeking is done at control build time.
2 In this case, the images have been stored in a in a RAW partition of the uSD card, and the absolute address of the images are saved in the DAT file. This is the fastest operation of the image control as there is no seeking or other disk activity taking place.
3 This mode is for Flash based 'file system' GCI (GCIF) with integrated DAT and other file types. "fname1" and "fname2" are then the Flash high and low words of the GCIF start location.

When an image control is loaded, an array is built in RAM. It consists of a 6 word header with the following entries as defined by the constants:

Information Index
IMG_COUNT 0
IMG_ENTRYLEN 1
IMG_MODE 2
IMG_GCI_FILENAME 3
IMG_DAT_FILENAME 4
IMG_GCIFILE_HANDLE 5

No images are stored in FLASH or RAM, the image control holds the index values for the absolute storage positions on the uSD card for RAW mode, or the cluster/sector position for formatted FAT16 mode.

When an image control is no longer required, the memory can be released with mem_Free();

Syntax: file_LoadImageControl(fname1, fname2, mode);

Argument Description
fname1 The control list filename "*.dat".
fname2 The image filename "*.gci".
mode Determines the mode of operation

Return: Pointer (handle) to the memory allocation to the image control list that has been created, null (0) if function fails

Example

#inherit "4DGL_16bitColours.fnc"

#constant OK   1
#constant FAIL 0

    var p;                          // buffer pointer
    var img;                        // handle for the image list
    var n, exit, r;

//-------------------------------------------------------------------
// return true if screen touched, also sets ok flag
func CheckTouchExit()
    return (exit := (touch_Get(TOUCH_STATUS) == TOUCH_PRESSED));   // if there's a press, exit
endfunc
//-------------------------------------------------------------------

func main()

    gfx_Cls();
    txt_Set(FONT_ID, FONT2);
    txt_Set(TEXT_OPACITY, OPAQUE);

    touch_Set(TOUCH_ENABLE);               // enable the touch screen

    print("heap=", mem_Heap(), " bytes\n");  // show the heap size

    r := OK; // return value
    exit := 0;

    if (!file_Mount())
        print("File error ", file_Error());
        while(!CheckTouchExit());  
// just hang if we didnt get the image list
        r := FAIL;
        goto quit;
    endif

    print ("WAIT...building image list\n");

  // slow build, fast execution, higher memory requirement
    img := file_LoadImageControl("GFX2DEMO.dat", "GFX2DEMO.gci", 1);        
  // build image control, returning a pointer to structure allocation

    if (img)
        print("image control=",[HEX] img,"\n");  
// show the address of the image control allocation
    else
        putstr("Failed to build image control....\n");
        while(CheckTouchExit() == 0);  
// just hang if we didnt get the image list
        r := FAIL;
        goto quit;
    endif

    print ("Loaded ", img[IMG_COUNT], " images\n");
    print ("\nTouch and hold to exit...\n");
    pause(2000);

    pause(3000);
    gfx_Cls();

    repeat
        n := 0;

        while(n < img[IMG_COUNT] && !exit) // go through all images
            CheckTouchExit();        // if there's a press, exit
            img_SetPosition( img, n, (ABS(RAND() % 240)), (ABS(RAND() % 320)));  // spread out the images
            n++;
        wend

        img_Show(img, ALL);    // update the entire control in 1 hit

    until(exit);

quit:

    mem_Free(img);      // release the image control
    file_Unmount();     // (program must release all resources)
    return r;

endfunc
//===================================================================

Note

This function is only available for use on the uSD based PmmC version.

file_Mount

Starts up the FAT16 disk file services and allocates a small 32 byte control block for subsequent use. When you open a file using file_Open(...), a further 512 + 44 = 556 bytes are attached to the FAT16 file control block. When you close a file using file_Close(...), the 556 byte allocation is released leaving the 32 byte file control block. The file_Mount() function must be called before any other FAT16 file related functions can be used. The control block and all FAT16 file resources are completely released with file_Unmount().

Syntax: file_Mount();

Return: True (1) if successful, False (0) otherwise

Example

if( !file_Mount() )
   while(!(file_Mount()))
      putstr("Disk not mounted");
      pause(200);
      gfx_Cls();
      pause(200);
   wend
endif 

Note

This function is only available for use on the uSD based PmmC version.

file_MountSpeed

Creates a control block for FAT16 and mounts the File System at the specified speed.

Syntax: file_MountSpeed(speed);

Argument Description
speed Specifies the speed. Speed can be from SPI_SPEED0 (slowest) to SPI_SPEED15 (fastest)

Return: True (1) if successful, False (0) otherwise

Example

if (!file_MountSpeed(SPI_SPEED0))
    repeat
        putstr("Disk not mounted");
        pause(200);
        gfx_Cls();
        pause(200);
    until (file_MountSpeed(SPI_SPEED0));
endif

Note

This function is only available for use on the uSD based PmmC version.

file_Unmount

Release any buffers for FAT16 and unmount the Disk File System. This function is to be called to close the FAT16 file system.

Syntax: file_Unmount();

Return: None

Example

file_Unmount();

Note

This function is only available for use on the uSD based PmmC version.

file_PlayWAV

Open the wav file, decode the header to set the appropriate wave player parameters and set off the playing of the file as a background process. See Sound Control Functions for additional play control functions.

This function may return the following values if unsuccessful:

Value Error Description
-7 Insufficient memory available for WAV buffer and file
-6 cant play this rate
-5 no data chunk found in first rsector
-4 no format data
-3 no wave chunk signature
-2 bad wave file format
-1 file not found

Syntax: file_PlayWAV(fname);

Argument Description
fname Filename of the wav file to be opened and played

Return: Number of blocks to play (1 to 32767), or error code otherwise.

Example

print("\nding.wav\n");
for (n := 0; n < 45; n++)
    pitch := NOTES[n];
    print([UDEC] pitch,"\r");
    snd_Pitch(pitch);
    file_PlayWAV("ding.wav");
    while(snd_Playing());
    //pause(500);
next

Note

This function is only available for use on the uSD based PmmC version.

file_CheckUpdate

Checks and/or updates the program running in Flash using the specified file on uSD.

The following options determine the mode of operation:

Option Value Description
CHECKUPDATE_QUERY 1 Checks the specified file and compares its DateTime to the program running in Flash
CHECKUPDATE_UPDATENEWER 2 Updates the program in Flash if the program on uSD is newer
CHECKUPDATE_UPDATEALWAYS 3 Always updates the program in Flash

If update occurs and the program is running from Flash, the display is reset after update. Otherwise, if a query or an error occurs, the following is returned:

Option Value Description
CHECKUPDATE_NEWFILE 1 The specified file is newer than the file running in Flash
CHECKUPDATE_OLDFILE 2 The specified file is equal to or older than the file running in Flash
CHECKUPDATE_UPDATEDONE 3 An update was performed, and the program is running from RAM
CHECKUPDATE_NOFILE 4 The specified file does not exist
CHECKUPDATE_INVALIDFILE 5 The specified file is not valid '4xe' or '4fn'

Syntax: file_CheckUpdate(fname, options);

Argument Description
fname Filename of the 4DGL program on the uSD card
options Determines whether to update always (3), update if newer (2) or simply query (1)

Return: Result of the operation

Example

if (!(file_Mount()))
    while(!(file_Mount()))
        putstr("Drive not mounted...");
        pause(200);
        gfx_Cls();
        pause(200);
    wend
endif

if (file_CheckUpdate("Program.4xe", CHECKUPDATE_QUERY) == CHECKUPDATE_NEWFILE)
    putstr("Program will now update") ;
    file_CheckUpdate("Program.4xe", CHECKUPDATE_UPDATENEWER) ;
endif

Note

This function is only available for use on the uSD based PmmC version.

Flash Memory Functions

flash_SIG

Read JEDEC signature from SPI Flash device

Syntax: flash_SIG();

Return: Flash Signature returned from the 'FLASH WAKEUP RETURN SIG' (0xAB) command

Example

var signature;
signature := flash_SIG();
print("JEDEC Signature: ", signature);

Note

This function is only available for use on the Flash based PmmC version

flash_ID

Read ID code from SPI Flash device

Syntax: flash_ID();

Return: The second (memory type) and third (memory capacity) bytes returned from the 'FLASH READ ID REG' (0x9F) command

Example

var ID;
ID := flash_ID();
print("Memory type: ", [HEX] HIbyte(ID), "\n");
print("Capacity: ", [HEX] LObyte(ID));

Note

This function is only available for use on the Flash based PmmC version

flash_BulkErase

Erase entire SPI Flash device

Syntax: flash_BulkErase();

Return: None

Example

flash_BulkErase();

Note

This function is only available for use on the Flash based PmmC version

flash_Block32Erase

Erase the 32KB flash block including the currently set address. This uses the 0x52 command.

Syntax: flash_Block32Erase();

Return: None

Example

flash_Block32Erase();

Note

This function is only available for use on the Flash based PmmC version

flash_Block64Erase

Erase the 64KB flash block including the currently set address. This uses the 0xD8 command.

Syntax: flash_Block64Erase();

Return: None

Example

flash_Block64Erase();

Note

This function is only available for use on the Flash based PmmC version

flash_Sector4Erase

Erase the 4KB flash sector including the currently set address. This uses the 0x20 command.

Syntax: flash_Sector4Erase();

Return: None

Example

flash_Sector4Erase();

Note

This function is only available for use on the Flash based PmmC version

General Purpose Functions

lookup8

Search a list of 8-bit constant values for a match with a search value 'key'. If found, the index of the matching constant is returned. Thus, if the value is found first in the list, result is set to one. If second in the list, result is set to two etc. If not found, result is zero.

Syntax: lookup8(key, ...byteConstList);

Argument Description
key A byte value to search for in a fixed list of constants
byteConstList A comma separated list of constants and strings to be matched against 'key'

Return: Index/Position of the matching constant starting with 1. 0 if 'key' doesn't exist

Example

func main()
    var r, key := 'a';
    r := lookup8(key, 0x4D, "abcd", 2, 'Z', 5);
    print("\nSearch value 'a' \nfound as index ", r);

    key := 5;
    r := lookup8(key, 0x4D, "abcd", 2, 'Z', 5);
    print("\nSearch value 5 \nfound at index ", r);
    putstr("\nScanning..\n");

    key := -12000; // we will count from -12000 to +12000, only
                   // the hex ascii values will give a match value

    while (key <= 12000)
        r := lookup8(key, "0123456789ABCDEF"); // hex lookup
        if (r) print([HEX1] r-1); // only print if we got a match in the table
        key++;
    wend
    repeat forever
endfunc

Note

  • The list of constants cannot be re-directed.
  • This function offer a versatile way for returning an index for a given value. This can be very useful for data entry filtering and parameter input checking and wherever you need to check the validity of certain inputs.
  • The entire search list field can be replaced with a single name if you use the $ operator in constant, eg: #constant HEXVALUES $"0123456789ABCDEF"

lookup16

Search a list of 16-bit constant values for a match with a search value 'key'. IIf found, the index of the matching constant is returned. Thus, if the value is found first in the list, result is set to one. If second in the list, result is set to two etc. If not found, result is zero.

Syntax: lookup16(key, wordConstList);

Argument Description
key A word value to search for in a fixed list of constants
wordConstList A comma separated list of constants and strings to be matched against 'key'

Return: Index/Position of the matching constant starting with 1. 0 if 'key' doesn't exist

Example

func main()
    var key, r;

    key := 5000;
    r := lookup16(key, 5,10,20,50,100,200,500,1000,2000,5000,10000);
    //r := lookup16(key, LEGALVALS);

    if(r)
        print("\nSearch value 5000 \nfound at index ", r);
    else
        putstr("\nValue not found");
    endif

    print("\nOk");  // all done

    repeat forever
endfunc

Note

  • This function offer a versatile way for returning an index for a given value. This can be very useful for data entry filtering and parameter input checking and wherever you need to check the validity of certain inputs.
  • The entire search list field can be replaced with a single name if you use the $ operator in constant, eg: #constant LEGALVALS $5,10,20,50,100,200,500,1000,2000,5000,10000

rect_Intersect

This function detects if two rectangles intersect each other or not. It is ideal for use as a collision detector. Each rectangle is an array of four words in the format [xpos, ypos, width, height]

Syntax: rect_Intersect(&rect1, &rect2);

Argument Description
rect1 An array of 4 vars containing left, top, width and height values
rect2 An array of 4 vars containing left, top, width and height values

Return: True (1) if any part of rect1 is within rect2, False (0) otherwise

Example

var rect1[4] := [50,50,75,75];
var rect2[4] := [20,20,100,100];

if (rect_Intersect(rect1, rect2))
    print("rect1 intersects rect2\n");
else
    print("rect1 does not intersect rect2\n");
endif

rect_Within

This function detects if a certain rectangle is completely within another rectangle or not. Each rectangle is an array of four words in the format: [xpos, ypos, width, height]

Syntax: rect_Within(&rect1, &rect2);

Argument Description
rect1 An array of 4 vars containing left, top, width and height values
rect2 An array of 4 vars containing left, top, width and height values

Return: True (1) if rect1 is fully within rect2, False (0) otherwise

Example

var rect1[4] := [50,50,25,25];
var rect2[4] := [20,20,100,100];

if (rect_Within(rect1, rect2))
    print("rect1 is fully within rect2\n");
else
    print("rect1 is not fully within rect2\n");
endif

pause

Stop execution of the user program for a predetermined amount of time.

Syntax: pause(time);

Argument Description
time A value specifying the delay time in milliseconds

Return: None

Example

if (status)     // if fire button pressed
    pause(30)   // slow down the loop
else

GPIO Functions

pin_Set

Initializes the 'pin' to the 'mode' specified. A pin can be initialized as an OUTPUT, INPUT, ANALOGUE or SOUND pin.

Constant Value Description
OUTPUT 0 Pin is set to an output
INPUT 1 Pin is set to an input
ANALOGUE 2 Pin is set as analog input
SOUND 3 Pin is set as sound output

The tables below show the applicable pin modes for PIXXI-28 and PIXXI-44

Pin Name Pin No. OUTPUT INPUT ANALOGUE SOUND
IO1_PIN 25 Yes Yes Yes Yes
IO2_PIN 27 Yes Yes Yes Yes
IO3_PIN 23 Yes Yes Yes Yes
IO4_PIN 24 Yes Yes Yes Yes
IO5_PIN 33 Yes Yes No Yes
IO6_PIN 37 Yes Yes No Yes
IO7_PIN 38 Yes Yes No Yes
IO8_PIN 19 Yes Yes No Yes
IO9_PIN 20 Yes Yes No Yes
IO10_PIN 41 Yes Yes No Yes
IO11_PIN 42 Yes Yes No Yes
IO12_PIN 1 Yes Yes No Yes
IO13_PIN 8 Yes Yes No Yes
IO14_PIN 9 Yes Yes No Yes
IO15_PIN 10 Yes Yes No Yes
IO16_PIN 11 Yes Yes No Yes
IO17_PIN 12 Yes Yes No Yes
IO18_PIN 44 Yes Yes No Yes
IO19_PIN 13 Yes Yes No Yes

Pin Name Pin No. OUTPUT INPUT ANALOGUE SOUND
IO1_PIN 1 Yes Yes Yes Yes
IO2_PIN 2 Yes Yes Yes Yes
IO3_PIN 4 Yes Yes No Yes
IO4_PIN 3 Yes Yes No Yes
IO5_PIN 11 Yes Yes No Yes
IO6_PIN 12 Yes Yes No Yes
IO7_PIN 28 Yes Yes No Yes

Syntax: pin_Set(mode, pin);

Argument Description
mode A value (usually a constant) specifying the pin operation
pin A value (usually a constant) specifying the pin number

Return: None

Example

pin_Set(OUTPUT, IO2_PIN);  // set IO2 to be used as an output
pin_Set(INPUT, IO1_PIN);   // set IO1 to be used as an input

pin_HI

Outputs a "High" level (logic 1) on the appropriate pin that was previously selected as an Output. If the pin is not already set to an output, it is automatically made an output.

Syntax: pin_HI(pin);

Argument Description
pin A value (usually a constant) specifying the pin number

Return: None

Example

pin_HI(IO2_PIN);        // output a Logic 1 on IO2 pin

pin_LO

Outputs a "Low" level (logic 0) on the appropriate pin that was previously selected as an output. If the pin is not yet set as an output, it is automatically made to an output.

Syntax: pin_LO(pin);

Argument Description
pin A value (usually a constant) specifying the pin number

Return: None

Example

pin_LO(IO1_PIN);        // output a Logic 0 on IO1 pin

pin_Read

Reads the logic state of the pin that was previously selected as an Input. If a digital input, this returns a "Low" (logic 0) or "High" (logic 1). Otherwise, it returns a 12-bit analogue value

Syntax: pin_Read(pin);

Argument Description
pin A value (usually a constant) specifying the pin number

Return

A Logic 1 (0x0001) or Logic 0 (0x0000)

12-bit analogue value

Example

if (pin_Read(IO1_PIN) == 1)     // read the value on IO1
    calc_Threshold();
endif

OW_Reset

Resets an 1-wire device and returns the status

Syntax: OW_Reset(pin);

Argument Description
pin A value (usually a constant) specifying the pin number

Return: Status of 1-wire device (0: ACK, 1: No Activity)

Example

// This example will print a 0 if the device initialised successfully.
print ("result=", OW_Reset(IO1_PIN));

Note

All PIXXI-28 and PIXXI-44 pins are capable of 1-wire protocol. Refer to these tables for the list of pins.

OW_Read

Reads the 8-bit value from a 1-wire devices register

Syntax: OW_Read(pin);

Argument Description
pin A value (usually a constant) specifying the pin number

Return: the lower 8-bits contain data bits received from the 1-Wire device

Example

// read temperature from DS1821 device
var temp_buf;
OW_Reset(IO1_PIN);               // reset the device
OW_Write(IO1_PIN, 0xAA);         // send the read command
temp_buf := OW_Read(IO1_PIN);    // read the device register

Note

All PIXXI-28 and PIXXI-44 pins are capable of 1-wire protocol. Refer to these tables for the list of pins.

OW_Read9

Reads the 9 or more bit value from a 1-wire devices register

Syntax: OW_Read9(pin);

Argument Description
pin A value (usually a constant) specifying the pin number

Return: 9 or more data bits received from the 1-Wire device

Example

// read temperature from DS1821 device
var temp_buf;
OW_Reset(IO1_PIN);                // reset the device
OW_Write(IO1_PIN,0xAA);           // send the read command
temp_buf := OW_Read9(IO1_PIN);    // read the device register

Note

All PIXXI-28 and PIXXI-44 pins are capable of 1-wire protocol. Refer to these tables for the list of pins.

OW_Write

Writes the 8-bit data to 1-Wire devices register.

Syntax: OW_Write(pin, value);

Argument Description
pin A value (usually a constant) specifying the pin number
value The lower 8-bits of data are sent to the 1-Wire device

Return: None

Example

//===================================================================
// For this demo to work, a Dallas DS18B20 must be connected to 
// IO1 AND POWERED FROM 3.3 to 5V.
// DS18B20 pin1 = Gnd / pin2 = data in/out / pin 3 = +3.3v
// Refer to the Dallas DS18B20 for further information
//===================================================================
func main()
    var temp_buf ;
    pause(1000);
    txt_MoveCursor(0,0);
    if(OW_Reset(IO1_PIN))                       // initialise and test
        print("No device detected");
        while(1);
    endif

    repeat
        txt_MoveCursor(0, 0);
        print ("result=", OW_Reset(IO1_PIN));
        OW_Write(IO1_PIN, 0xcc);                // skip ROM
        OW_Write(IO1_PIN, 0x44);                // start conversion
        OW_Reset(IO1_PIN);                      // reset
        OW_Write(IO1_PIN, 0xcc);                // skip ROM
        OW_Write(IO1_PIN, 0xBE);                // get temperature
        temp_buf := OW_Read(IO1_PIN);
        temp_buf += (OW_Read(IO1_PIN) << 8);

        txt_MoveCursor(1, 0);
        print ("temp_buf=0x", [HEX4] temp_buf);
    forever
endfunc

Note

All PIXXI-28 and PIXXI-44 pins are capable of 1-wire protocol. Refer to these tables for the list of pins.

joystick

Returns the value of the joystick position (5 position switch implementation). The joystick values are:

Value Status
0 JOY_RELEASED
1 JOY_UP
2 JOY_LEFT
3 JOY_DOWN
4 JOY_RIGHT
5 JOY_BTNB
6 JOY_BTNA

The joystick input uses the speficied pin utilizing the A/D converter. Refer to these tables for to determine the pins capable of ADC operation.

Each switch is connected to a junction of 2 resistors that form a unique voltage divider circuit.

The joystick can also be implemented using multiple buttons and resistors. Refer to the Analog Input section of the PIXXI-28 and PIXXI-44 processor datasheets for the required resistor values.

Syntax: joystick(pin);

Return: Joystick value

Example

txt_MoveCursor(0, 0);
joy := joystick(IO1_PIN);   // read the joystick on IO1
if (joy == JOY_RELEASED)    putstr("         ");
if (joy == JOY_UP)          putstr("UP");
if (joy == JOY_LEFT)        putstr("LEFT");
if (joy == JOY_DOWN)        putstr("DOWN");
if (joy == JOY_RIGHT)       putstr("RIGHT");
if (joy == JOY_BTNB)        putstr("BUTTON B");
if (joy == JOY_BTNA)        putstr("BUTTON A");

bus_In

Read the 7-bit port regardless of pin configurations. If a pin is configured as input, the pin is read directly as if it were a digital input. If a pin is configured as an output, the pin is also read directly, giving the output latch state.

Pin Name Pin Number BUS Bit Number
IO12_PIN 1 0
IO13_PIN 8 1
IO14_PIN 9 2
IO15_PIN 10 3
IO16_PIN 11 4
IO17_PIN 12 5
IO18_PIN 44 6

Syntax: bus_In();

Return: 7-bit value of the bus

Example

var1 := bus_In(); // Read the 7-bit value off the IO12-IO18 pins

Note

This is only available in Mode 2 (4-wire SPI Mode) of PIXXI-44

bus_Out

The lower 7 bits of the argument are placed on the 7bit wide bus. Any BUS pins that are set to inputs are not affected.

Syntax: bus_Out(value);

Argument Description
value A value (usually a constant) specifying the pin number. Bit 0 corresponds to IO12 through to bit6 which corresponds to IO18. This is a 7-bit BUS.

Return: None

Example

var arg1;
arg1 := 0b0011010; // set desired mask
bus_Out(arg1); // set IO13, IO15 and IO16 to output, making them HI

Note

This is only available in Mode 2 (4-wire SPI Mode) of PIXXI-44

Graphics Functions

gfx_Cls

Clear the screen using the current background colour. This brings some of the settings back to default, such as:

  • Transparency turned OFF
  • Outline colour set to BLACK
  • Opacity set to OPAQUE
  • Pen set to OUTLINE
  • Line patterns set to OFF
  • Right text margin set to full width
  • Text magnifications set to 1
  • All origins set to 0:0

The alternative to maintain settings and to clear screen is to draw a filled rectangle with the required background colour.

Syntax: gfx_Cls();

Return: None

Example

gfx_BGcolour(DARKGRAY);
gfx_Cls(); // clears the entire display using colour DARKGRAY 

gfx_ChangeColour

Changes all oldColour pixels to newColour within the clipping area. See gfx_SetClipRegion(...) and gfx_ClipWindow(...)

Syntax: gfx_ChangeColour(oldColour, newColour);

Argument Description
oldColour Specifies the sample colour to be changed within the clipping window
newColour Specifies the new colour to change all occurrences of oldColour within the clipping window

Return: None

Example

func main()

    txt_Width(3);                   
    txt_Height(5);                  
    gfx_MoveTo(8,20);
    print("TEST");          // print the string
    gfx_SetClipRegion();    // force clipping area to extents of text
                            // just printed.
    gfx_ChangeColour(BLACK, RED); // test change of background colour

    repeat forever
endfunc

gfx_Circle

Draws a circle with centre point x1, y1 with radius r using the specified colour.

Syntax: gfx_Circle(x, y, radius, colour);

Argument Description
x, y Specifies the center of the circle
radius Specifies the radius of the circle
colour Specifies the colour of the circle

Return: None

Example

// Draws a BLUE circle outline (assuming PEN_SIZE is OUTLINE)
gfx_Circle(50, 50, 30, RED); // centred at x=50, y=50 with a radius of 30 pixel units

Note

The default PEN_SIZE is set to OUTLINE, however, if PEN_SIZE is set to SOLID, the circle will be drawn filled, if PEN_SIZE is set to OUTLINE, the circle will be drawn as an outline. If the circle is drawn as SOLID, the outline colour can be specified with gfx_OutlineColour(...). If OUTLINE_COLOUR is set to 0, no outline is drawn.

gfx_CircleFilled

Draws a SOLID circle with centre point x1, y1 with radius using the specified colour. The outline colour can be specified with gfx_OutlineColour(...). If OUTLINE_COLOUR is set to 0, no outline is drawn.

Syntax: gfx_CircleFilled(x, y, radius, colour);

Argument Description
x, y Specifies the center of the circle
radius Specifies the radius of the circle
colour Specifies the colour of the circle

Return: None

Example

// Draws a RED solid circle centred at x=50, y=50 with a radius of 10 pixel units
gfx_CircleFilled(50, 50, 10, RED);

gfx_Line

Draws a line from x1, y1 to x2, y2 using the specified colour. The line is drawn using the current object colour. The current origin is not altered. The line may be tessellated with the gfx_LinePattern(...) function.

Syntax: gfx_Line(x1, y1, x2, y2, colour);

Argument Description
x1, y1 Specifies the starting coordinates of the line
x2, y2 Specifies the ending coordinates of the line
colour Specifies the colour of the line

Return: None

Example

// Draws a RED line from x1=10, y1=10 to x2=100, y2=100
gfx_Line(100, 100, 10, 10, RED);

gfx_Hline

Draws a fast horizontal line from x1 to x2 at vertical coordinate y using colour.

Syntax: gfx_Hline(y, x1, x2, colour);

Argument Description
y Specifies the vertical position of the horizontal line
x1, x2 Specifies the horizontal end points of the line
colour Specifies the colour of the line

Return: None

Example

// Draws a RED horizontal line at y=50, from x1=10 to x2=80
gfx_Hline(50, 10, 80, RED);

gfx_Vline

Draws a fast vertical line from y1 to y2 at horizontal coordinate x using colour.

Syntax: gfx_Vline(x, y1, y2, colour);

Argument Description
x Specifies the horizontal position of the vertical line
y1, y2 Specifies the vertical end points of the line
colour Specifies the colour of the line

Return: None

Example

// Draws a RED vertical line at x=20, from y1=30 to y2=70
gfx_Vline(20, 30, 70, RED);

gfx_Rectangle

Draws a rectangle from x1, y1 to x2, y2 using the specified colour. The line may be tessellated with the gfx_LinePattern(...) function.

Syntax: gfx_Rectangle(x1, y1, x2, y2, colour);

Argument Description
x1, y1 Specifies the top left corner of the rectangle
x2, y2 Specifies the bottom right corner of the rectangle
colour Specifies the colour of the rectangle

Return: None

Example

// Draws a GREEN rectangle from x1=10, y1=10 to x2=30, y2=30
gfx_Rectangle(10, 10, 30, 30, GREEN);

Note

The default PEN_SIZE is set to OUTLINE, however, if PEN_SIZE is set to SOLID, the rectangle will be drawn filled, if PEN_SIZE is set to OUTLINE, the rectangle will be drawn as an outline. If the rectangle is drawn as SOLID, the outline colour can be specified with gfx_OutlineColour(...). If OUTLINE_COLOUR is set to 0, no outline is drawn. The outline may be tessellated with the gfx_LinePattern(...) function.

gfx_RectangleFilled

Draws a SOLID rectangle from x1, y1 to x2, y2 using the specified colour. The line may be tessellated with the gfx_LinePattern(...) function.

Syntax: gfx_RectangleFilled(x1, y1, x2, y2, colour);

Argument Description
x1, y1 Specifies the top left corner of the rectangle
x2, y2 Specifies the bottom right corner of the rectangle
colour Specifies the colour of the rectangle

Return: None

Example

// Draws a filled RED rectangle from x1=30, y1=30 to x2=80, y2=80
gfx_RectangleFilled(30, 30, 80, 80, RED);

Note

The outline colour can be specified with gfx_OutlineColour(...). If OUTLINE_COLOUR is set to 0, no outline is drawn. The outline may be tessellated with the gfx_LinePattern(...) function. The PEN_SIZE is ignored, the rectangle is always drawn SOLID.

gfx_RoundRect

Draw a filled rectangle at the given co-ordinates with optional rounded corners.

If x1 = x2 or y1 = y2 no straight-line part is drawn.

gfx_RoundRect Diagram

The actual width of the round-corners rectangle is computed by: 2 * rad + x2 – x1

The actual height of the round-corners rectangle is computed by: 2 * rad + y2 – y1

Syntax: gfx_RoundRect(x1, y1, x2, y2, rad, colour);

Argument Description
x1, y1 Specifies the top left corner of the inner rectangle
x2, y2 Specifies the bottom right corner of the inner rectangle
rad Specifies the radius of corners
This is the distance in pixels extending from the corners of the inner rectangle
colour Specifies the colour of the rectangle

Return: None

Example

gfx_RoundRect(30, 30, 80, 80, 5, RED); 

gfx_Polyline

Plots lines between points specified by a pair of arrays using the specified colour. The lines may be tessellated with the gfx_LinePattern(...) function. This can be used to create complex raster graphics by loading the arrays from serial input or from MEDIA with very little code requirement.

Syntax: gfx_Polyline(n, vx, vy, colour);

Argument Description
n Specifies the number of elements in the x and y arrays specifying the vertices for the polyline
vx Specifies the addresses of the storage of the array of elements for the x coordinates of the vertices
vy Specifies the addresses of the storage of the array of elements for the y coordinates of the vertices
colour Specifies the colour for the lines

Return: None

Example

#inherit "4DGL_16bitColours.fnc"

var vx[20], vy[20];

func main()

    vx[0] := 36; vy[0] := 110; 
    vx[1] := 36; vy[1] := 80;
    vx[2] := 50; vy[2] := 80;
    vx[3] := 50; vy[3] := 110;

    vx[4] := 76; vy[4] := 104; 
    vx[5] := 85; vy[5] := 80;
    vx[6] := 94; vy[6] := 104;

    vx[7] := 76; vy[7] := 70; 
    vx[8] := 85; vy[8] := 76;
    vx[9] := 94; vy[9] := 70;

    vx[10] := 110; vy[10] := 66; 
    vx[11] := 110; vy[11] := 80;
    vx[12] := 100; vy[12] := 90;
    vx[13] := 120; vy[13] := 90; 
    vx[14] := 110; vy[14] := 80;

    vx[15] := 101; vy[15] := 70;
    vx[16] := 110; vy[16] := 76; 
    vx[17] := 119; vy[17] := 70;

    // house
    gfx_Rectangle(6,50,66,110,RED);         // frame
    gfx_Triangle(6,50,36,9,66,50,YELLOW);   // roof
    gfx_Polyline(4, vx, vy, CYAN);          // door

    // man
    gfx_Circle(85, 56, 10, BLUE);           // head
    gfx_Line(85, 66, 85, 80, BLUE);         // body
    gfx_Polyline(3, vx+4, vy+4, CYAN);      // legs
    gfx_Polyline(3, vx+7, vy+7, BLUE);      // arms

    // woman
    gfx_Circle(110, 56, 10, PINK);          // head
    gfx_Polyline(5, vx+10, vy+10, BROWN);   // dress       
    gfx_Line(104, 104, 106, 90, PINK);      // left arm         
    gfx_Line(112, 90, 116, 104, PINK);      // right arm        
    gfx_Polyline(3, vx+15, vy+15, SALMON);  // dress       

    repeat forever

endfunc

gfx_Polygon

Plots lines between points specified by a pair of arrays using the specified colour. The last point is drawn back to the first point, completing the polygon. The lines may be tessellated with the gfx_LinePattern(...) function. This can be used to create complex raster graphics by loading the arrays from serial input or from MEDIA with very little code requirement.

Syntax: gfx_Polygon(n, vx, vy, colour);

Argument Description
n Specifies the number of elements in the x and y arrays specifying the vertices for the polygon
vx Specifies the addresses of the storage of the array of elements for the x coordinates of the vertices
vy Specifies the addresses of the storage of the array of elements for the y coordinates of the vertices
colour Specifies the colour for the polygon

Return: None

Example

var vx[7], vy[7];

func main()
    vx[0] := 10; vy[0] := 10; 
    vx[1] := 35; vy[1] := 5; 
    vx[2] := 80; vy[2] := 10;
    vx[3] := 60; vy[3] := 25;
    vx[4] := 80; vy[4] := 40;
    vx[5] := 35; vy[5] := 50;
    vx[6] := 10; vy[6] := 40;
    gfx_Polygon(7, vx, vy, RED);
    repeat forever
endfunc

gfx_Triangle

Draws a triangle outline between vertices (x1, y1), (x2, y2) and (x3, y3) using the specified colour. The line may be tessellated with the gfx_LinePattern(...) function.

Syntax: gfx_Triangle(x1, y1, x2, y2, x3, y3, colour);

Argument Description
x1, y1 Specifies the first vertices of the triangle
x2, y2 Specifies the second vertices of the triangle
x3, y3 Specifies the third vertices of the triangle

Return: None

Example

// Draws a CYAN triangular outline with vertices  at (10, 10), (30, 10) and (20, 30)
gfx_Triangle(10, 10, 30, 10, 20, 30, CYAN);

gfx_Dot

Draws a pixel at at the current origin using the current object colour.

Syntax: gfx_Dot();

Return: None

Example

// Draws a RED pixel at x=40, y=50
gfx_MoveTo(40, 50);
gfx_ObjectColour(RED);
gfx_Dot();

gfx_Bullet

Draws a circle or 'bullet point' with radius r at at the current origin using the current object colour.

Syntax: gfx_Bullet(radius);

Argument Description
radius Specifies the radius of the bullet

Return: None

Example

gfx_MoveTo(30, 30);
gfx_Bullet(10); // Draw a 10pixel radius Bullet at x=30, y=30.

Note

The default PEN_SIZE is set to OUTLINE, however, if PEN_SIZE is set to SOLID, the circle will be drawn filled, if PEN_SIZE is set to OUTLINE, the circle will be drawn as an outline. If the circle is drawn as SOLID, the outline colour can be specified with gfx_OutlineColour(...)

gfx_OrbitInit

Sets up the internal pointers for the gfx_Orbit(..) result variables. The &x_orb and &y_orb parameters are the addresses of the variables or array elements that are used to store the result from the gfx_Orbit(..) function.

Syntax: gfx_OrbitInit(&x_dest, &y_dest);

Argument Description
&x_dest Specifies the address of storage location of the X value for the orbit calculation
&y_dest Specifies the address of storage location of the Y value for the orbit calculation

Return: None

Example

// Sets the variables that will receive the result from a gfx_Orbit(...) function call
var targetX, targetY;
gfx_OrbitInit(&targetX, &targetY);

gfx_Orbit

Prior to using this function, the destination address of variables for the calculated coordinates must be set using the gfx_OrbitInit(...) function. This function calculates the x, y coordinates of a distant point relative to the current origin, where the only known parameters are the angle and the distance from the current origin. The new coordinates are calculated and then placed in the destination variables that have been previously set with the gfx_OrbitInit(...) function.

Syntax: gfx_Orbit(angle, distance);

Argument Description
angle Specifies the angle from the origin to the remote point. The angle is specified in degrees.
distance Specifies the distance from the origin to the remote point in pixel units

Return: None

Example

var targetX, targetY;
gfx_OrbitInit(&targetX, &targetY);
gfx_MoveTo(30, 30);
gfx_Bullet(5);     // mark the start point with a small WHITE circle
gfx_Orbit(30, 50); // calculate a point 50 pixels away from origin at
                   // 30 degrees
// mark the target point with a RED circle
gfx_CircleFilled(targetX, targetY, 3, 0xF800);

Note

Result is stored in the variables that were specified with the gfx_OrbitInit(...) function.

gfx_PutPixel

Draws a pixel at position x, y using the specified colour.

Syntax: gfx_PutPixel(x, y, colour);

Argument Description
x, y Specifies the screen coordinates of the pixel
colour Specifies the 16-bit colour of the pixel (0x0000-0xFFFF)

Return: None

Example

// Draws a WHITE pixel at x=32, y=32
gfx_PutPixel(32, 32, 0xFFFF);

gfx_GetPixel

Reads the colour value of the pixel at position (x, y)

Syntax: gfx_GetPixel(x, y);

Argument Description
x, y Specifies the screen coordinates of the pixel colour to be returned

Return: 16-bit colour of the pixel

Example

// Prints 1234, the colour of the pixel that was previously placed
gfx_PutPixel(20, 20, 1234);
r := gfx_GetPixel(20, 20);
print(r);

gfx_MoveTo

Moves the origin to a new position

Syntax: gfx_MoveTo(xpos, ypos);

Argument Description
xpos Specifies the horizontal position of the new origin
ypos Specifies the vertical position of the new origin

Return: None

Example

#inherit "4DGL_16bitColours.fnc"

func help()
    var x, y, state;

    print("TOUCH ME");

    touch_Set(TOUCH_ENABLE);     // lets enable the touch screen
    while(touch_Get(TOUCH_STATUS) != TOUCH_PRESSED); //Wait for touch

    // we'll need a place on the screen to start with
    gfx_MoveTo(touch_Get( TOUCH_GETX), touch_Get( TOUCH_GETY)); 

    gfx_Set(OBJECT_COLOUR, WHITE); // this will be our line colour

    while(1)
        state := touch_Get(TOUCH_STATUS); // Look for touch activity
        x := touch_Get(TOUCH_GETX); // Grab x and the
        y := touch_Get(TOUCH_GETY); // y coordinates of the touch

        if(state == TOUCH_PRESSED)   // if there's a press
            gfx_LineTo(x, y); // Draw a line from previous spot
        endif

        if(state ==  TOUCH_RELEASED)       // if there's a release;
            gfx_CircleFilled(x, y, 10, RED);// Draw a solid red circle 
        endif

        if(state == TOUCH_MOVING)          // if there's movement
            gfx_PutPixel(x, y, LIGHTGREEN);  // we'll draw a green pixel
        endif
    wend                                  // Repeat forever 
endfunc

gfx_MoveRel

Moves the origin to a new position relative to the old position

Syntax: gfx_MoveRel(xoffset, yoffset);

Argument Description
xoffset Specifies the horizontal offset of the new origin
yoffset Specifies the vertical offset of the new origin

Return: None

Example

// Draws a pixel using the current object colour at x=5, y=17
gfx_MoveTo(10, 20);
gfx_MoveRel(-5, -3);
gfx_Dot();

gfx_IncX

Increment the current X origin by 1 pixel unit. The original value is returned before incrementing. The return value can be useful if a function requires the current point before insetting occurs.

Syntax: gfx_IncX();

Return: the current X origin before the increment

Example

// Draws a simple rounded vertical gradient
var n;
gfx_MoveTo(20,20);
n := 96;
while (n--)
    gfx_ObjectColour(n/3);
    gfx_Bullet(2);
    gfx_IncX();
wend

gfx_IncY

Increment the current Y origin by 1 pixel unit. The original value is returned before incrementing. The return value can be useful if a function requires the current point before insetting occurs.

Syntax: gfx_IncY();

Return: the current Y origin before the increment

Example

// Draws a simple horizontal gradient using lines
var n;
gfx_MoveTo(20,20);
n := 96;
while (n--)
    gfx_ObjectColour(n/3);
    gfx_LineRel(20, 0);
    gfx_IncY();
wend

gfx_LineTo

Draws a line from the current origin to a new position. The Origin is then set to the new position. The line is drawn using the current object colour. The line may be tessellated with the gfx_LinePattern(...) function.

Syntax: gfx_LineTo(xpos, ypos);

Argument Description
xpos Specifies the horizontal position of the line end as well as the new origin
ypos Specifies the vertical position of the line end as well as the new origin

Return: None

Example

// Draws a line using the current object colour between x1=10, y1=20 and x2=60, y2=70.
gfx_MoveTo(10, 20);
gfx_LineTo(60, 70);
// The new origin is now set at x=60, y=70.

gfx_LineRel

Draws a line from the current origin to a new position. The line is drawn using the current object colour. The current origin is not altered. The line may be tessellated with the gfx_LinePattern(...) function.

Syntax: gfx_LineRel(xpos, ypos);

Argument Description
xpos Specifies the horizontal end point of the line
ypos Specifies the vertical end point of the line

Return: None

Example

// Draws a tessellated line using the current object colour between (10, 20) and (50, 50)
gfx_LinePattern(0b1100110011001100);
gfx_MoveTo(10, 20);
gfx_LineRel(50, 50);
// Note: gfx_LinePattern(0); must be used after this to return line drawing to normal solid lines

gfx_BoxTo

Draws a rectangle from the current origin to the new point using the current object colour. The top left corner is anchored by the current origin (x1, y1), the bottom right corner is specified by x2, y2.

Syntax: gfx_BoxTo(x2, y2);

Argument Description
x2, y2 Specifies the diagonally opposed corner of the rectangle to be drawn, the top left corner (assumed to be x1, y1) is anchored by the current origin.

Return: None

Example

// Draws 2 boxes, anchored from the current origin
gfx_MoveTo(40,40);
n := 10;

while (n--)

    gfx_BoxTo(50,50);
    gfx_BoxTo(30,30);

wend

Note

The default PEN_SIZE is set to OUTLINE, however, if PEN_SIZE is set to SOLID, the rectangle will be drawn filled, if PEN_SIZE is set to OUTLINE, the rectangle will be drawn as an outline. If the circle is drawn as SOLID, the outline colour can be specified with gfx_OutlineColour(...). If OUTLINE_COLOUR is set to 0, no outline is drawn.

gfx_Ellipse

Plots a coloured Ellipse on the screen at centre (x, y) with xradius = xrad and yradius = yrad.

if PenSize = 0, Ellipse is Solid

if PenSize = 1, Ellipse is Outline

Syntax: gfx_Ellipse(x, y, xrad, yrad, colour);

Argument Description
x, y Specifies the horizontal and vertical position of the centre of ellipse
xrad, yrad Specifies x-radius and y-radius of the ellipse
colour Specifies the colour for the lines

Return: None

Example

gfx_Ellipse(200, 80, 5, 10, YELLOW);

gfx_EllipseFilled

Plots a solid coloured Ellipse on the screen at centre x,y with xradius = xrad and yradius = yrad.

Syntax: gfx_EllipseFilled(x, y, xrad, yrad, colour);

Argument Description
x, y Specifies the horizontal and vertical position of the centre of ellipse
xrad, yrad Specifies x-radius and y-radius of the ellipse
colour Specifies the colour for the lines

Return: None

Example

gfx_EllipseFilled(200, 110, 10, 5, GREEN);

gfx_ScreenCopyPaste

Copies an area of a screen from xs, ys of size given by width and height parameters and pastes it to another location determined by xd, yd.

Syntax: gfx_ScreenCopyPaste(xs, ys, xd, yd, width, height);

Argument Description
xs, ys Specifies the horizonal and vertical position of the top left corner of the area to be copied (source)
xd, yd Specifies the horizontal and vertical position of the top left corner of where the paste is to be made (destination)
width Specifies the width of the copied area
height Specifies the height of the copied area

Return: None

Example

// Copies 40x40 pixels originating from point (10,10) to (100,100);
gfx_ScreenCopyPaste(10, 10, 100, 100, 40, 40);

gfx_RGBto565

Returns the 16-bit (Red: 5, Green: 6, Blue: 5 format) colour value of a 24-bit (Red: 8, Green: 8, Blue: 8 format) colour.

Syntax: gfx_RGBto565(red, green, blue);

Argument Description
red 8-bit colour value for Red
green 8-bit colour value for Green
blue 8-bit colour value for Blue

Return: 16-bit (Red: 5, Green: 6, Blue: 5 format) colour value

Example

// convert 8-bit Red, Green and Blue color values to 16-bit 565 color value
var colorRGB; 
colorRGB := gfx_RGBto565(170, 126, 0);

gfx_332to565

Returns the 16-bit (Red: 5, Green: 6, Blue: 5 format) value of an 8-bit (Red: 3, Green: 3, Blue: 2 format) colour

Syntax: gfx_332to565(colour);

Argument Description
colour 8-bit colour value. 3 bits for Red, 3 bits for Green, 2 bits for blue

Return: 16-bit (Red: 5, Green: 6, Blue: 5 format) colour value

Example

// Convert 8-bit 332 color value to 16-bit 565 color value
var color565; 
color565 := gfx_332to565(0b11010100);

gfx_TriangleFilled

Draws a solid triangle between vertices x1,y1 , x2,y2 and x3,y3 using the specified colour.

Syntax: gfx_TriangleFilled(x1, y1, x2, y2, x3, y3, colour);

Argument Description
x1, y1 Specifies the first vertices of the triangle
x2, y2 Specifies the second vertices of the triangle
x3, y3 Specifies the third vertices of the triangle

Return: None

Example

// Draws a CYAN Solid triangle with vertices at (10, 10) (30, 10) and (20, 30)
gfx_TriangleFilled(10, 10, 30, 10, 20, 30, CYAN);

gfx_PolygonFilled

Draws a solid Polygon between specified vertices: (x1, y1), (x2, y2) ... (xn, yn) using the specified colour. The last point is drawn back to the first point, completing the polygon. Vertices must be minimum of 3 and can be specified in any fashion

Syntax: gfx_PolygonFilled(n, vx, vy, colour);

Argument Description
n Specifies the number of elements in the x and y arrays specifying the vertices for the polygon
vx Specifies the addresses of the storage of the array of elements for the x coordinates of the vertices
vy Specifies the addresses of the storage of the array of elements for the y coordinates of the vertices
colour Specifies the colour for the polygon

Return: None

Example

var vx[7], vy[7];

func main()
    vx[0] := 10; vy[0] := 10; 
    vx[1] := 35; vy[1] := 5; 
    vx[2] := 80; vy[2] := 10;
    vx[3] := 60; vy[3] := 25;
    vx[4] := 80; vy[4] := 40;
    vx[5] := 35; vy[5] := 50;
    vx[6] := 10; vy[6] := 40;
    gfx_PolygonFilled(7, vx, vy, RED);          

    repeat forever
endfunc

gfx_Origin

Sets relative screen offset for horizontal and vertical for the top left corner for graphics objects.

Syntax: gfx_Origin(x, y);

Argument Description
x, y Specifies the relative screen offset for horizontal and vertical for the top left corner for graphics objects

Return: None

Example

gfx_Origin(10, 20); // Sets origin position at (10,20)

gfx_SetClipRegion

Forces the clip region to the most recent extents. It can be the extents of the last text that was printed or the last image that was shown.

For the clipping region to take effect, "Clipping" setting must be enabled separately using gfx_Set(CLIPPING, ON) or the shortcut gfx_Clipping(ON).

Syntax: gfx_SetClipRegion();

Return: None

Example

gfx_MoveTo(10,10);   // move the origin to a new pixel location (x,y)
print("TEST");       // print a string
gfx_SetClipRegion(); // force the clipping region to the extent of the text
gfx_Clipping(ON);    // turn ON clipping
var n;
n := 50000;
while (n--)
    // Draw 50000 random colour pixels,
    // only the pixels within region of the text will be visible
    gfx_PutPixel(RAND()%100, RAND()%100, RAND());
wend
repeat forever

gfx_ClipWindow

Specifies a clipping window region on the screen such that any objects and text placed onto the screen will be clipped and displayed only within that region.

For the clipping window to take effect, "Clipping" setting must be enabled separately using gfx_Set(CLIPPING, ON) or the shortcut gfx_Clipping(ON).

Syntax: gfx_ClipWindow(x1, y1, x2, y2);

Argument Description
x1, y1 Specifies the horizontal and vertical position of the top left corner of the clipping window
x2, y2 Specifies the horizontal and vertical position of the bottom right corner of the clipping window

Return: None

Example

var n;
gfx_ClipWindow(10, 10, 50, 50 );
gfx_Clipping(ON);
n := 50000;
while (n--)
    // Draw 50000 random colour pixels,
    // only the pixels within the clipping area will be visible
    gfx_PutPixel(RAND()%100, RAND()%100, RAND());
wend
repeat forever

gfx_Get

Returns various graphics parameters to caller.

The following graphics parameters can be queried:

Mode Description
X_MAX Current orientations maximum X Value
Y_MAX Current orientations maximum Y Value
LEFT_POS Left location of Object
TOP_POS Top location of Object
RIGHT_POS Right location of Object
BOTTOM_POS Bottom location of Object
X_ORG Get current internal X position
Y_ORG Get current internal Y position

Syntax: gfx_Get(mode);

Argument Description
mode Specifies graphics parameter to query

Return: the value of the parameter being queried

Example

val := gfx_Get(X_MAX);      // Returns the maximum horizontal resolution of the display
val := gfx_Get(Y_MAX);      // Returns the maximum vertical resolution of the display
val := gfx_Get(RIGHT_POS);  // Returns the right location of the last drawn object
                            // that only has top, left parameters such as a button
                            // or an image/video.
val := gfx_Get(BOTTOM_POS); // Returns the bottom location of the last drawn object
                            // that only has top, left parameters such as a button
                            // or an image/video.

gfx_Set

Set the required graphics control parameter, such as size, colour, and other parameters

The following parameters can be set

Mode Description Value
PEN_SIZE Set the draw mode for gfx_LineTo, gfx_LineRel, gfx_Dot, gfx_Bullet and gfx_BoxTo (default mode is OUTLINE) 0 or SOLID
1 or OUTLINE
BACKGROUND_COLOUR Set the screen background colour 16-bit Colour, 0x0000-0xFFFF
OBJECT_COLOUR Generic colour for gfx_LineTo, gfx_LineRel, gfx_Dot, gfx_Bullet and gfx_BoxTo 16-bit Colour, 0x0000-0xFFFF
CLIPPING Turns clipping on/off
The clipping points are set with gfx_ClipWindow and must be set first.
1 or 0 (ON or OFF)
TRANSPARENT_COLOUR Colour that needs to be made transparent. 16-bit Colour, 0x0000-0xFFFF
TRANSPARENCY Turn the transparency ON or OFF. Transparency is automatically turned OFF after the next image or video command. 1 or 0 (ON or OFF)
FRAME_DELAY Set the inter frame delay for media_Video(...) 0 to 255msec
SCREEN_MODE Set required screen behaviour/orientation. 0 or LANDSCAPE
1 or LANDSCAPE_R
2 or PORTRAIT
3 or PORTRAIT_R
OUTLINE_COLOUR Outline colour for rectangles and circles
(set to 0 for no effect)
16-bit Colour, 0x0000-0xFFFF
CONTRAST Set contrast value, 0 = display off, 1-15 = contrast level 0 or OFF
1 to 15 for levels
BEVEL_WIDTH Set Button Bevel Width, 0 pixel to 15 pixels. 0 None
1 to 15 pixels

Syntax: gfx_Set(function, value);

Argument Description
function Determines the required action for various graphics control functions. There are pre-defined constants for each of the functions
value Target new setting/value for the target display function

Return: None

gfx_PenSize

Set the draw mode for gfx_LineTo(...), gfx_LineRel(...), gfx_Dot(...), gfx_Bullet(...) and gfx_BoxTo(...)

Syntax: gfx_PenSize(mode);

Argument Description
mode SOLID (0) or OUTLINE (1), default: OUTLINE

Return: None

Note

Pen size is set to OUTLINE for normal operation (default).

gfx_BGcolour

Set the screen background colour

Syntax: gfx_BGcolour(colour);

Argument Description
colour 16-bit Colour, 0x0000-0xFFFF

Return: None

gfx_ObjectColour

Sets the colour for gfx_LineTo(...), gfx_LineRel(...), gfx_Dot(...), gfx_Bullet(...) and gfx_BoxTo(...)

Syntax: gfx_ObjectColour(colour);

Argument Description
colour 16-bit Colour, 0x0000-0xFFFF

Return: None

gfx_Clipping

Turns clipping on/off. The clipping points are set with gfx_ClipWindow(...)

Syntax: gfx_Clipping(mode);

Argument Description
mode 0 (ON) or 1 (OFF)

Return: None

gfx_TransparentColour

Sets the colour that needs to be made transparent

Syntax: gfx_TransparentColour(colour);

Argument Description
colour 16-bit Colour, 0x0000-0xFFFF

Return: None

gfx_Transparency

Turn the transparency ON or OFF. 1 or 0 (ON or OFF)

Syntax: gfx_Transparency(mode);

Argument Description
mode 1 (ON) or 0 (OFF)

Return: None

gfx_FrameDelay

Set the inter frame delay for media_Video(...) 0 to 255msec

Syntax: gfx_FrameDelay(delay);

Argument Description
delay 0 to 255msec

Return: None

gfx_ScreenMode

Sets the screen graphics orientation to any of the following:

Option Value Description
LANDSCAPE 1 Landscape Orientation
LANDSCAPE_R 2 Reversed Landscape Orientation
PORTRAIT 3 Portrait Orientation
PORTRAIT_R 4 Reversed Portrait Orientation

Syntax: gfx_ScreenMode(mode);

Argument Description
mode Screen Orienation

Return: None

gfx_OutlineColour

Sets the outline colour for rectangles and circles. Set to 0x0000 for no effect.

Syntax: gfx_OutlineColour(colour);

Argument Description
colour 16-bit Colour, 0x0000-0xFFFF

Return: None

gfx_Contrast(value)

Set contrast value. Turn off the display by setting the value to 0. Acceptable value is from 1 to 15

Syntax: gfx_Contrast(value);

Argument Description
value 0 or OFF, 1 to 15 for levels

Return: None

gfx_LinePattern

Sets the draw pattern for line drawing. If set to zero, lines are solid, else each '1' bit represents a pixel that is turned off.

Syntax: gfx_LinePattern(pattern);

Argument Description
pattern 16-bit bitwise design representing the draw pattern

Return: None

Example: See gfx_LineRel example

gfx_BevelWidth

Sets graphics button bevel shadow depth

Syntax: gfx_BevelShadow(width);

Argument Description
width 0 to 15 pixels

Return: None

gfx_BevelShadow

Sets graphics button bevel shadow depth

Syntax: gfx_BevelShadow(value);

Return: None

gfx_Xorigin

Set the X offset of the graphics origin point

Syntax: gfx_Xorigin(offset);

Argument Description
offset Specifies the relative screen horizontal offset for the left side for graphics objects

Return: None

gfx_Yorigin

Set the Y offset of the graphics origin point

Syntax: gfx_Yorigin(offset);

Argument Description
offset Specifies the relative screen vertical offset for the top side for graphics objects

Return: None

gfx_RingSegment

Draw a Segment of a ring at (x, y) from rad2 to rad1 starting at starta to enda in colour

Syntax: gfx_RingSegment(x, y, Rad1, Rad2, starta, enda, colour);

Argument Description
x, y Specifies the center of the ring segment
Rad1 Specifies the outer radius of the ring segment
Rad2 Specifies the inner radius of the ring segment
starta Specifies the start angle of the ring segment
enda Specifies the end angle of the ring segment
colour Specifies the colour of the ring segment

Return: None

Example

gfx_RingSegment(100, 100, 50, 25, 90, 180, LIME);

gfx_ReadGRAMarea

Reads an arbitrary rectangular area from the display to an array. If "ptr" is 0, the correctly sized array is created, in which case it is up to the caller to eventually destroy it. Otherwise "ptr" is expected to point to a correctly sized array.

If an array is supplied, its size must be large enough, and may be calculated:

  • bytecount = (ABS(x2 - x1) + 1) * (ABS(y2 - y1) + 1)
  • wordcount = 2 * bytecount

*bytecount can be used when creating a buffer using mem_Alloc

*wordcount can be used when creating a fixed var array

Syntax: gfx_ReadGRAMarea(x1, y1, x2, y2, ptr);

Argument Description
x1, y1 Top left corner of the rectangular area
x2, y2 Bottom right corner of the rectangular area
ptr Pointer to an array large enought to store each pixel or;
0 to automatically create an array of the required size

Return:

  • If ptr is 0, returns the created array if there is insufficient memory, otherwise, returns 0
  • If ptr is nonzero, returns the user's array ptr

Example

var array;
array := gfx_ReadGRAMarea(50, 50, 250, 175, 0);
// Copy the pixels of the GRAM area with top left and bottom right 
// endpoints at (50,50) and (250,175) and saves it to the generated 
// array. The address is then returned and saved to variable ‘array’

gfx_BGcolour(LIME); 
gfx_Cls(); // Sets the background to a single color

gfx_WriteGRAMarea(100, 100, 300, 225, array);
// Copies the GRAM area to the new coordinates,
// Top left and bottom right corners are at (100,100) and (300,225)

gfx_WriteGRAMarea

Write an array back to the rectangular area

Syntax: gfx_WriteGRAMarea(x1, y1, x2, y2, ptr);

Argument Description
x1, y1 Top left corner of the rectangular area
x2, y2 Bottom right corner of the rectangular area
ptr Points to an array to be written

Return: None

Example: See gfx_ReadGRAMarea example

gfx_Surround

Draws an outline rectangle at the given co-ordinates with optional rounded corners determined by rad1. rad2 sets the radius of the outer rounded rectangle. If rad1 is zero, the inner rectangle will have square corners. Bounding rectangle is x1-rad1-rad2, y1-rad1-rad2, x2+rad1+rad2, y2+rad1+rad2.

Syntax: gfx_Surround(x1, y1, x2, y2, rad1, rad2, colour);

Argument Description
x1, y1 Specifies the top left corner position of the surround on the screen
x2, y2 Specifies the bottom right corner position of the surround on the screen
rad1 Specifies the inner corner radius of the surround
rad2 Specifies the outer corner radius of the surround
colour Specifies the colour of the surround

Return: None

Example

// Draw a surround with rounded corners, 3 pixels wide 
gfx_Surround(40, 40, 100, 60, 15, 3, YELLOW);

gfx_Gradient

Draws a graduated colour rectangle at the specified coordinate

The following gradient directions are supported:

Style Description
GRAD_DOWN gradient changes in the vertical direction
GRAD_RIGHT gradient changes in the horizontal direction
GRAD_UP gradient changes in the vertical direction
GRAD_LEFT gradient changes in the horizontal direction
GRAD_WAVE_VER gradient wave in the vertical direction
GRAD_WAVE_HOR gradient wave in the horizontal direction

Syntax: gfx_Gradient(style, x1, y1, x2, y2, colour1, colour2);

Argument Description
style Specifies the gradient style
x1, y1 Specifies top left corner of the rectangle
x2, y2 Specifies bottom right corner of the rectangle
colour1 Specifies the start colour of the gradient
colour2 Specifies the end colour of the gradient

Return: None

Example

// Draw graduated colour rectangle
gfx_Gradient(GRAD_WAVE_VER, 100, 100, 230, 120, BLACK, WHITE); 

gfx_RoundGradient

Draws a graduated colour rounded rectangle at the specified co-ordinate.

x1 and y1 may equal x2 and y2 allowing the function to be used for rounded panels, rounded buttons, circular buttons.

gfx_RoundGradient

Bounding rectangle is x1-radius, y1-radius, x2+radius, y2+radius.

Syntax: gfx_RoundGradient(style, x1, y1, x2, y2, radius, colour1, colour2);

Argument Description
style Specifies the gradient style
x1, y1 Specifies the top left corner of the inner rectangle
x2, y2 Specifies the bottom right corner of the inner rectangle
radius Specifies the radius of corners
This is the distance in pixels extending from the corners of the inner rectangle
colour1 Specifies the start colour of the gradient
colour2 Specifies the end colour of the gradient

Return: None

Example

// Draw graduated colour rounded rectangle
gfx_Gradient(GRAD_WAVE_VER, 100, 100, 230, 120, 20, BLACK, WHITE);

gfx_XYrotToVal

This function converts a rotational angle into a value. It calculates a position for a rotary input starting at mina and continuing to maxa. Both angles must be greater than 0.

Syntax: gfx_XYrotToVal(x, y, base, mina, maxa, minv, maxv);

Argument Description
x Relative x-coordinate (x-coordinate – x-center)
y Relative y-coordinate (y-coordinate – y-center)
base The base reference at which the angle is 0
XYROT_EAST angle 0 starts from the east
XYROT_SOUTH angle 0 starts from the south
mina Start angle (Clockwise from 0 angle)
maxa End angle (Clockwise from 0 angle)
minv Minimum value
maxv Maximum value

Return: The equivalent position, the value of which will be between minv and maxv.

Example

var pos;
pos := gfx_XYrotToVal(150 - 100, 150 - 100, XYROT_EAST, 0, 180, 0, 100);
print(pos); // Prints value of 25, expected at angle of 45 degrees
            // with the origin at x = 100, y = 100

gfx_XYlinToVal

This function converts a linear position into a value. It calculates a position for a linear input starting at minpos and continuing to maxpos.

Syntax: gfx_XYlinToVal(x, y, base, minpos, maxpos, minv, maxv);

Argument Description
x, y x and y position values
base Base reference axis
XYLIN_X to use the x value for calculations (Horizontal axis)
XYLIN_Y to use the y value for calculations (Vertical axis)
minpos Start position
maxpos End position
minv Minimum value
maxv Maximum value

Return: The equivalent position, the value of which will be between minv and maxv

Example

var pos;
pos := gfx_XYlinToVal(100, 100, XYLIN_X, 0, 200, 0, 100);
print(pos); // Prints 50, after mapping to min and max value

gfx_SpriteSet

This function sets the internal pointers for the 3 sets of data required by the sprite generator which are as follows: 1. the bitmaps for the sprites 2. the colour lookup table (CLUT) 3. the 4 colour palettes

Syntax: gfx_SpriteSet(bitmaps, colours, palette);

Argument Description
bitmaps Pointer to bitmaps
colours Pointer to colour lookup table
palette Pointer to the 4 colour palettes

Return: None

Example

#DATA
    word mySprites  0x0000, 0x0000, // line 1
    /* Cherry */    0x0000, 0x0000, // line 2
                    0x0000, 0x0500, // line 3                11
                    0x0000, 0x0550, // line 4              1111
                    0x0000, 0x0045, // line 5            11 1
                    0x4000, 0x0040, // line 6           1   1
                    0x1FC0, 0x0010, // line 7       3331   1
                    0xF7F0, 0x0004, // line 8      333133 1
                    0x3FF0, 0x00F7, // line 9      33333 3133
                    0xCFB0, 0x03F7, // line 10      3233 331333
                    0xCEF0, 0x03FF, // line 11      3323 333333
                    0xCFC0, 0x03FE, // line 12       333 323333
                    0xC000, 0x03FB, // line 13           332333
                    0x0000, 0x00FF, // line 14            3333
                    0x0000, 0x0000, // line 15
                    0x0000, 0x0000  // line 16
    word myColours  BLACK, RED, LIME, WHITE
    byte myPalette  0, 2, 3, 1      // BLACK, LIME, WHITE, RED
#END


func main()

    gfx_SpriteSet(mySprites, myColours, myPalette);

    // Show a cherry upside down using the first palette of myPalette as set by gfx_SpriteSet
    gfx_BlitSprite(0, 0, 10, 10, SOUTH, 0);  

    repeat forever

endfunc

gfx_BlitSprite

Places the required sprite bitmap at the origin xpos, ypos using the required 4 colour palettes. Orientation determines in which direction the sprite will be displayed. If preimage exists, it should be large enough to hold the entire image 'underneath' the sprite.

Here are the supported orientations:

Constant Name Value
NORTH 0
SOUTH 1
WEST 2
EAST 3
NORTH_MIRRORED 4
SOUTH_MIRRORED 5
WEST_MIRRORED 6
EAST_MIRRORED 7

Syntax: gfx_BlitSprite(spritenumber, palette, xpos, ypos, orientation, preimage);

Argument Description
spritenumber Index of sprite to be shown
palette Index of the colour palette to be used. Value can be from 0 to 3
xpos, ypos x and y coordinates of position at which the sprite will be shown
orientation Direction of the sprite when shown. Possible values for orientation
preimage Pointer to a preimage, if required

Return: None

Example: See gfx_SpriteSet example

gfx_Button

Draws a three-dimensional Text Button at screen location defined by x, y parameters (top left corner). The size of the button depends on the font, width, height and length of the text.

The button can contain multiple lines of text by having the \n character embedded in the string for the end of line marker. In this case, the widest text in the string sets the overall width, and the height of the button is set by the number of text lines. In the case of multiple lines, each line is left justified.

If you wish to centre or right justify the text, you will need to prepare the text string according to your requirements.

Syntax: gfx_Button(state, x, y, buttonColour, txtColour, font, txtWidth txtHeight, text);

Argument Description
state 0 = Button depressed; 1 = Button raised
x, y Specifies the top left corner position of the button on the screen
buttonColour Button colour
txtColour Text colour
font Specifies the Font ID
txtWidth Specifies the width of the text. This value is the font width multiplier and minimum value must be 1
txtHeight Specifies the height of the text. This value is the font height multiplier and minimum value must be 1
text Specifies the text string. The text string must be within the range of printable ascii character set. The string may have \n characters embedded to create a multiline button

Return: None

Example

#constant LEFT          30
#constant TOP           150
#constant TEXTWIDTH     2
#constant TEXTHEIGHT    2

func main()

    // Draw a button as a Text Box (indented)
    gfx_Button(DOWN, 0, 30, GREEN, WHITE, FONT3, TEXTWIDTH, TEXTHEIGHT, "4DGL-Demo");
    touch_Set(TOUCH_ENABLE);

    repeat

        // Draw the Push Button (raised)
        gfx_Button(UP, LEFT, TOP, BLUE, RED, FONT3, TEXTWIDTH, TEXTHEIGHT, " PRESS ");

        // set touch detect region to that of the push button
        touch_DetectRegion(LEFT, TOP, gfx_Get(RIGHT_POS), gfx_Get(BOTTOM_POS));

        // Wait until the button is pressed 
        while (touch_Get(TOUCH_STATUS) != TOUCH_PRESSED);

        // now redraw the Push Button (depressed)
        gfx_Button(DOWN, LEFT, TOP, BLUE, WHITE, FONT3, TEXTWIDTH, TEXTHEIGHT, " PRESS ");

        // Wait until the button is pressed
        while (touch_Get(TOUCH_STATUS) != TOUCH_RELEASED); 

    forever

endfunc

gfx_Button4

Draw a Button as defined by ButtonDef (if required), using ButtonRam positioning at position value. See the reference for the ButtonDef values.

The following are the required definitions gfx_ButtonDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
radius Radius
outerBevelColor1 Outer bevel gradient color 1
outerBevelColor2 Outer bevel gradient color 2
outerGradStyle Outer bevel gradient style
ringColor0 Ring Color (at state 0)
ringColor1 Ring Color (at state 1)
buttonBevelColor1 Button bevel gradient color 1
buttonBevelColor2 Button bevel gradient color 2
buttonBevelStyle0 Button bevel gradient (at state 0)
buttonBevelStyle1 Button bevel gradient (at state 1)
buttonFaceColor Button face color
buttonDesign Button text/string, or numeric 0 for Braille design
buttonParam1 Braille grid gradient color 1 if buttonDesign is 0
Font color (at state 0) if buttonDesign is text
buttonParam2 Braille grid gradient color 1 if buttonDesign is 0
Font color (at state 1) if buttonDesign is text
buttonParam3 Braille grid gradient style if buttonDesign is 0
Font style/ID if buttonDesign is text
buttonParam4 Not required if buttonDesign is 0
Text size if buttonDesign is text

Syntax: gfx_Button4(state, &gfx_ButtonRam, &gfx_ButtonDef);

Argument Description
state A value (usually a constant) specifying the current frame of the widget
&gfx_ButtonRam A pointer to a variable array for widget utilization
&gfx_ButtonDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var state;
var Button1Ram[10];
var Button2Ram[10];

#DATA
word Button1Info 0, 0, 50, 0x9CD3, 0x5ACB, GRAD_WAVE_VER, 0x8800, 0xF800, 0xDEDB, 0x2104, GRAD_DOWN, GRAD_UP, 0x6B6D, 0, 0xBDD7, 0x2965, GRAD_DOWN

word Button2Info 10, 120, 50, 0x9CD3, 0x5ACB, GRAD_WAVE_VER, 0x8800, 0xF800, 0xDEDB, 0x2104, GRAD_DOWN, GRAD_UP, 0x6B6D, ButtonText, 0xFFFF, 0x0, FONT1, 1

byte ButtonText "Button\0"
#END

func main()
    gfx_Button4(state, Button1Ram, Button1Info); // Button with braille
    gfx_Button4(state, Button2Ram, Button2Info); // Button with text
    repeat forever
endfunc

gfx_Switch

Draw a Switch as defined by SwitchDef (if required), using SwitchRam positioning at position value.

The following are the required definitions SwitchDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
length Widget length
thickness Widget thickness
options Option bits (See gfx_Switch Option Bits table)
baseBevelColor1 Container bevel main color
baseBevelColor2 Container bevel shadow color
baseBevelSize Container bevel thickness
switchBevelSize Switch bevel thickness
switchBevelColor1 Switch face color (State 1)
switchBevelColor0 Switch face color (State 0)
text1 Text (State 1)
text0 Text (State 0)
fontStyle Font style
fontSize Font size multiplier
textColor1 Text color (State 1)
textColor0 Text color (State 0)

The table below list all the option bits for the options definition:

Option Bit/Flag Set Unset
SWITCH1_F_ORIENT_VERT 0x0001 Vertical Horizontal

Syntax: gfx_Switch(state, &SwitchRam, &SwitchDef);

Argument Description
state A value (usually a constant) specifying the current frame of the widget
&SwitchRam A pointer to a variable array for widget utilization
&SwitchDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var state;
var Button1Ram[10];
#DATA
    word Button1Info        10, 10, 90, 49, 1, 0x9772, 0x8C1, 4, 3, 0x1C43, 0x32A6,
                            Button1LabelOn, Button1LabelOff, FONT3, 1, 0xFFFF, 0x120
    byte Button1LabelOn     "ON\0"
    byte Button1LabelOff    "OFF\0" 
#END

func main()
    gfx_Switch(state, Button1Ram, Button1Info); // Button Internal Widget
    repeat forever
endfunc

gfx_Slider

Draws a vertical or horizontal slider bar on the screen. The gfx_Slider function has several different modes of operation. To minimise the amount of graphics functions we need; all modes of operation are selected naturally depending on the parameter values.

Orientation Selection Rules:

  • if x2-x1 > y2-y1, slider is assumed to be horizontal (ie: if width > height, slider is horizontal)
  • if x2-x1 <= y2-y1, slider is assumed to be vertical (ie: if height <= width, slider is horizontal)

Thumb Selection Rules:

  • If value is positive, thumb is set to the position that is the proportion of value to the scale parameter. (Used to set the control to the actual value of a variable)
  • If value is negative, thumb is driven to the graphics position set by the ABSolute of value. (Used to set thumb to its actual graphical position (usually by touch screen)
  • The thumb colour is determine by gfx_Set(OBJECT_COLOUR, value);, however, if the current object colour is BLACK, a darkened shade of the colour parameter is used for the thumb.

Syntax: gfx_Slider(mode, x1, y1, x2, y2, colour, scale, value);

Argument Description
mode 0 : Slider Indented
1 : Slider Raised
2 : Slider Hidden (background colour)
x1, y1 Specifies the top left corner position of the slider on the screen
x2, y2 Specifies the bottom right corner position of the slider on the screen
colour Specifies the colour of the slider bar
scale Sets the full range of the slider for the thumb from 0 to this value
value if positive, sets the relative position of the thumb on the slider bar,
else set thumb to ABS position of the negative number

Return:

  • If the value parameter was a positive number (i.e:- value is a proportion of the scale parameter), the true (implied x or y axis) position of the thumb is returned.
  • If the value parameter was a negative number (i.e:- thumb is being set to an Absolute graphics position), the actual slider value (which is a proportion of the scale parameter) is returned.

Example

func drawRedSlider()

    gfx_Slider(0, rSlider[0], rSlider[1], rSlider[2], rSlider[3], RED, 255, valR);

    txt_MoveCursor(1,12);
    txt_Set(TEXT_OPACITY, OPAQUE);
    txt_Set(TEXT_COLOUR, RED);
    print("   ");

    txt_MoveCursor(1,12);
    print([DEC] valR);

endfunc

gfx_Slider5

Draw a Slider as defined by SliderDef (if required), using SliderRam positioning at position value.

The following are the required definitions SliderDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
length Widget length
width Widget width
options Option bits (See gfx_Slider5 Option Bits table)
minValue Minimum value
maxValue Maximum value
baseColor Base color
trackFillColor1 Track fill color (from Right/Top to current position)
trackFillColor2 Track fill color (from Left/Bottom to current position)
majorTickCount1 Total Marker partition for Top/Left Side (0 for no ticks)
majorTickCount2 Total Marker partition for Bottom/Right Side (0 for no ticks)
minorTickCount1 Minor ticks between each major ticks T/L Side (0 for small ticks)
minorTickCount2 Minor ticks between each major ticks B/R Side (0 for small ticks)
majorTickLength Major tick length
majorTickColor Major tick color
minorTickLength Minor tick length
minorTickColor Minor tick color
fontStyle Value indicator font style
fontColor Value indicator text color
knobBevelColor1 Slider knob bevel gradient color 1
knobBevelColor2 Slider knob bevel gradient color 2
knobBevelStyle Slider knob bevel gradient style
knobFaceColor1 Slider knob face gradient color 1
knobFaceColor2 Slider knob face gradient color 2
knobFaceStyle Slider knob face gradient style

The table below list all the option bits for the options definition:

Option Bit/Flag Set Unset
SLIDER5_F_ORIENT_VERT 0x0001 Vertical Horizontal
SLIDER5_F_TICKS 0x0002 Enable Disable
SLIDER5_F_VALUE_IND 0x0004 Enable Disable
SLIDER5_F_PROGRESSBAR 0x0008 Progress Bar (gauge mode) Slider mode

Syntax: gfx_Slider5(value, &SliderRam, &SliderDef);

Argument Description
value A value (usually a constant) specifying the current frame of the widget
&SliderRam A pointer to a variable array for widget utilization
&SliderDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var frame;
var Slider1Ram[10];
var Gauge1Ram[10];

#DATA
    word Slider1Info    10, 10, 250, 40, (0 + 0 + 0), 0, 100, 0x1082, 0x0, 0x7E0, 30, 30, 2,
                        2, 10, 0x7E0, 5, 0x7E0, FONT3, 0xFFE0, 0x1082, 0x9CD3, GRAD_DOWN,
                        0x1082, 0x9CD3, GRAD_UP 

    word Gauge1Info     10, 60, 250, 40, (SLIDER5_F_PROGRESSBAR + SLIDER5_F_ORIENT_VERT + 
                        SLIDER5_F_TICKS + SLIDER5_F_VALUE_IND), 0, 100, 0x1082, 0x0, 0x7E0,
                        30, 30, 2, 2, 10, 0x7E0, 5, 0x7E0, FONT3, 0xFFE0, 0x1082, 0x9CD3,
                        GRAD_DOWN, 0x1082, 0x9CD3, GRAD_UP 
#END

func main()
    gfx_Slider5(frame, Slider1Ram, Slider1Info); // Slider Internal Widget 
    gfx_Slider5(frame, Gauge1Ram, Gauge1Info); // Gauge Internal Widget
    repeat forever
endfunc

gfx_Dial

Draw a Dial as defined by DialDef (if required), using DialRam positioning at position value.

The following are the required definitions DialDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
width Width
height Height
xCenter Knob centre X-position
yCenter Knob centre Y-position
radius Knob radius
startAngle Rotation starting angle
endAngle Rotation ending angle
minValue Minimum value
maxValue Maximum value
backgroundColor Background color
knobColor Knob color
bevelThickness Bevel thickness
bevelColor1 Bevel gradient color 1 (Left side)
bevelColor2 Bevel gradient color 2 (Right side)
partAngle2 Starting angle for Partition 2
partAngle3 Starting angle for Partition 3
partLowColor1 Partition 1 low color
partLowColor2 Partition 2 low color
partLowColor3 Partition 3 low color
partHighColor1 Partition 1 high color
partHighColor2 Partition 2 high color
partHighColor3 Partition 3 high color
indTickOffset Indicator ticks offset distance
indTickSize1 Indicator size 1 (Radius/Width of circle, triangle or rectangle)
indTickSize2 Indicator size 2 (Length of line, triangle or rectangle)
knobPointerColor Knob pointer color
knobPointerSize1 Knob pointer size 1 (Radius/Width of circle, triangle or rectangle)
knobPointerSize2 Knob pointer size 2 (Length of line, triangle or rectangle)
indLabelColor Knob indicator label text color
indLabelStyle Knob indicator label font style
indLabelOffset Knob indicator label offset distance
indLabelCount Number of indicator labels
indTextPtr Pointer to string indicator labels (Numeric labels if zero (0))
captionStyle Caption font style
captionColor Caption text color
captionOffsetX Caption horizontal offset from knob centre
captionOffsetY Caption vertical offset from knob centre
captionText Knob Caption text
options Option bits (See gfx_Dial Option Bits table)

The table below list all the option bits for the options definition:

Option Bit/Flag Set Unset
SLIDER5_F_ORIENT_VERT 0x0001 Vertical Horizontal
SLIDER5_F_TICKS 0x0002 Enable Disable
SLIDER5_F_VALUE_IND 0x0004 Enable Disable
SLIDER5_F_PROGRESSBAR 0x0008 Progress Bar (gauge mode) Slider mode

Syntax: gfx_Dial(value, &DialRam, &DialDef);

Argument Description
value A value (usually a constant) specifying the current frame of the widget
&DialRam A pointer to a variable array for widget utilization
&DialDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var frame;
var Knob1Ram[10];

#DATA
    word Knob1Info      10, 10, 152, 129, 87, 80, 38, 135, 405, 0, 100, 0x0, 0x52AA, 5, 0xB5B6, 0x3186,
                        200, 300, 0x280, 0x528A, 0x5800, 0x7E0, 0xFFE0, 0xF800, 12, 3, 6, 0xF800, 3, 30,
                        0xFFFF, FONT2, 22, 10, Labels, FONT2, 0xFFFF, -15, 50, Knob1Caption,
                        (0 + DIAL_F_HANDLE_CIRCLE + DIAL_F_INDICATOR_LINE)
    byte Labels         "Text1\0Text2\0Text3\0Text4\0Text5\0"
    byte Knob1Caption   "KNOB\0"
#END

func main()
    gfx_Dial(frame, Knob1Ram, Knob1Info); // Dial Internal Widget 
    repeat forever
endfunc

gfx_AngularMeter

Draw an angular meter as defined by MeterDef (if required), using MeterRam positioning at position value.

The following are the required definitions MeterDef:

Definition Description
scaleOuterRadius Range scale outer edge radius
scaleInnerRadius Range scale inner edge radius
majorTickCount Number of partitions of marker ticks
minorTickCount Number of minor ticks before next major tick (0 to disable)
majorTickOuterLen Length for major ticks radiating from scale outer edge
minorTickOuterLen Length for minor ticks radiating from scale outer edge
majorTickInnerLen Length for major ticks radiating from scale inner edge
minorTickInnerLen Length for minor ticks radiating from scale inner edge
tickWidth Tick width
tickColor Tick color
partitionAngle2 Starting angle for range scale second ring section
partitionAngle3 Starting angle for range scale third ring section
partitionColor1 Range scale first ring section color
partitionColor2 Range scale second ring section color
partitionColor3 Range scale third ring section color
scaleStepSize Range scale section incremental step size
scaleLabelCount Total number of scale marker labels
scaleFontStyle Scale marker label font style
scaleFontColor Scale marker label text color
scaleLabelOffset Scale marker label offset distance (relative to range scale midpoint)
scaleLabelPtr Pointer to label strings (Default is numeric is set to zero (0))
options Gauge Options (see gfx_AngularMeter option bits table)
captionFontStyle Caption font style
captionFontColor Caption text color
captionOffsetX Caption horizontal offset from rotation centre
captionOffsetY Caption vertical offset from rotation centre
captionText Caption text pointer
xpos Top-Left X-position
ypos Top-Left Y-position
width Width
height Height
centerX Rotation centre X-position
centerY Rotation centre Y-position
backgroundColor Background color (required for erasing needle path)
startAngle Starting angle
endAngle Ending angle
minValue Minimum value
maxValue Maximum value
needleLen Needle length
needleStyle Needle style options (see gfx_Needle style table)
needleOffset Needle offset distance from center
needleWidth Needle width (Half value of overall needle thickness)
needleTailLength Needle tail length (Applicable only for double triangle style)
needleColor Needle color
needleHubRadius Needle Hub radius
needleHubColor Needle Hub color
needlePinRadius Needle Pin radius
needlePinColor Needle Pin color

The table below list all the option bits for the options definition:

Option Bit/Flag Set Unset
ANGULAR_F_LABEL_STRINGS 0x0001 Counter Clockwise Direction Clockwise Direction
ANGULAR_F_BG_TRANSPARENT 0x0002 Enable Disable
ANGULAR_F_TICK_PCT_COLOUR 0x0004 Replace Tick Color with Section Colors Disable
ANGULAR_F_TEXT_PCT_COLOUR 0x0008 Replace Label Color with Section Colors Disable

Syntax: gfx_AngularMeter(value, &MeterRam, &MeterDef);

Argument Description
value A value (usually a constant) specifying the current frame of the widget
&MeterRam A pointer to a variable array for widget utilization
&MeterDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var state;
var Gauge1Ram[10];

#DATA
    word Gauge1Info     90, 70, 20, 2, 17, 5, 10, 2, 1, 0xFFFF, 270, 337, 0xDF, 0x3BF, 0xF800,
                        0, 10, FONT1, 0xFFFF, 15, 0, (0 + 0 + 0 + 0), FONT2, 0xFFFF, -26, 56,
                        Gauge1Caption, 10, 10, 235, 197, 128, 125, 0x0, 135, 405, 0, 100, 60,
                        NEEDLE_F_TRIANGLE, 0, 6, 30, 0xFFFF, 6, 0xFFFF, 2, 0xF800
    byte Gauge1Caption  "Caption\0"
#END

func main()
    gfx_AngularMeter(state, Gauge1Ram, Gauge1Info); // Gauge
    repeat forever
endfunc

gfx_Needle

Draw a Needle as defined by NeedleDef (if required), using NeedleRam positioning at position value.

The following are the required definitions NeedleDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
width Width
height Height
centerX Rotation centre X-position
centerY Rotation centre Y-position
backgroundColor Background color (required for erasing needle path)
startAngle Starting angle
endAngle Ending angle
minValue Minimum value
maxValue Maximum value
needleLen Needle length
needleStyle Needle style options (see gfx_Needle style table)
needleOffset Needle offset distance from center
needleWidth Needle width (Half value of overall needle thickness)
needleTailLength Needle tail length (Applicable only for double triangle style)
needleColor Needle color
needleHubRadius Needle Hub radius
needleHubColor Needle Hub color
needlePinRadius Needle Pin radius
needlePinColor Needle Pin color

The table below list all the styles for the needle:

Option Value Description
NEEDLE_F_LINE 0 Line needle pointer
NEEDLE_F_RECTANGLE 1 Rectangular needle pointer
NEEDLE_F_POINTRECTANGLE 2 Pointed rectangular needle pointer
NEEDLE_F_TRIANGLE 3 Triangular needle pointer
NEEDLE_F_DOUBLETRIANGLE 4 Double ended triangular needle pointer
NEEDLE_F_ROUNDEDRECTANGLE 5 Rounded corner rectangular needle pointer

Syntax: gfx_Needle(value, &NeedleRam, &NeedleDef);

Argument Description
value A value (usually a constant) specifying the current frame of the widget
&NeedleRam A pointer to a variable array for widget utilization
&NeedleDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var frame;
var NeedleRam[10];

#DATA
    word NeedleInfo     10, 10, 235, 197, 128, 125, 0x0, 135, 405, 0, 100, 60,
                        NEEDLE_F_TRIANGLE, 0, 6, 30, 0xFFFF, 6, 0xFFFF, 2, 0xF800
#END

func main()

    gfx_Needle(frame, NeedleRam, NeedleInfo); // Rotating Needle 
    repeat forever

endfunc

gfx_Gauge

Draw a Gauge as defined by GaugeDef (if required), using GaugeRam positioning at position value.

The following are the required definitions GaugeDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
length Gauge length
width Gauge width
barCount Number of Gauge bars
minValue Minimum gauge value
maxValue Maximum gauge value
barSize Bar thickness
barGap Bar spacing
barGapColor Inter 'bar' gap color
inactiveColor1 Partition 1 low colour
activeColor1 Partition 1 active colour
inactiveColor2 Partition 2 low colour
activeColor2 Partition 2 active colour
inactiveColor3 Partition 3 low colour
activeColor3 Partition 3 active colour
section2Start Partition 2 starting bar
section3Start Partition 3 starting bar
options Gauge Option bits (see gfx_Gauge option bits table)

The table below list all the option bits for the options definition:

Option Bit/Flag Set Unset
GAUGE_F_TOPRIGHT 0x0001 Inverts direction (Starts from Top/Right) Disable
GAUGE_F_HORZ 0x0002 Horizontal Vertical

Syntax: gfx_Gauge(value, &GaugeRam, &GaugeDef);

Argument Description
value A value (usually a constant) specifying the current frame of the widget
&GaugeRam A pointer to a variable array for widget utilization
&GaugeDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var frame;
var Gauge1Ram[10];

#DATA
    word Gauge1Info     10, 10, 181, 59, 11, 0, 100, 10, 5, 0x18E3, 0x280, 0x7E0,
                        0x5280, 0xFFE0, 0xA000, 0xF800, 8, 5,
                        (GAUGE_F_HORZ + GAUGE_F_TOPRIGHT)
#END

func main()

    gfx_Gauge(frame, Gauge1Ram, Gauge1Info); // Gauge Internal Widget 
    repeat forever

endfunc

gfx_RulerGauge

Draw a RulerGauge as defined by RulerGaugeDef (if required), using RulerGaugeRam positioning at position value. See the reference for the RulerGaugeDef values.

The following are the required definitions RulerGaugeDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
length Widget length
width Widget width
frames Widget total frames/range
majorSectionCount Number of partitions between each major ticks
minorSectionCount Number of minor tick partitions between each major ticks
minorTickLength Minor tick length
majorTickLength Major tick length
mediumRangeStart Starting frame for medium range scale
highRangeStart Starting frame for high range scale
baseColor Base color
lowRangeColor Low range color
mediumRangeColor Medium range color
highRangeColor High range color
tickColor Marker tick color
options Option bits (see gfx_RulerGauge option bits table)

The table below list all the option bits for the options definition:

Option Bit/Flag Set Unset
RULERGAUGE_TICKS_TOP 0x0001 Position Marker on Top/Left Position Marker on Bottom/Right
RULERGAUGE_F_ORIENT_VERT 0x0002 Vertical Horizontal

Syntax: gfx_RulerGauge(value, &RulerGaugeRam, &RulerGaugeDef);

Argument Description
value A value (usually a constant) specifying the current frame of the widget
&RulerGaugeRam A pointer to a variable array for widget utilization
&RulerGaugeDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var value;
var Gauge1Ram[10];

#DATA
word Gauge1Info     10, 10, 250, 52, 100, 6, 5, 10, 20, 50, 75, 0x3A08, 0x1F,
                    0xFD20, 0xF800, 0xFFFF, RULERGAUGE_TICKS_BOTTOM
#END

func main()

    gfx_RulerGauge(value, Gauge1Ram, Gauge1Info); // Gauge Internal Widget
    repeat forever

endfunc

gfx_Led

Draw a Led as defined by LedDef (if required), using LedRam positioning in state state. See the reference for the LedDef values.

The following are the required definitions LedDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
width Widget width
height Widget height
baseColor1 Base gradient color 1
baseColor2 Base gradient color 2
shineColor LED shine effect color
activeColor LED color (State 1)
inactiveColor LED color (State 0)
innerRadius Base bevel inner radius
outerRadius Base bevel outer radius
shineRadius LED Shine effect radius
ledRadius Outer LED radius
shineEffect LED Shine effect (1 - enable, 0 - disable)

Syntax: gfx_Led(state, &LedRam, &LedDef);

Argument Description
state A value (usually a constant) specifying the current frame of the widget
&LedRam A pointer to a variable array for widget utilization
&LedDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var state;
var Led1Ram[10];

#DATA
    word  Led1Info  10, 10, 113, 96, 0x2965, 0x0, 0xFFFF,
                    0xF800, 0x5800, 35, 40, 20, 30, 1
#END

func main()

    gfx_Led(state, Led1Ram, Led1Info); // LED Internal Widget 
    repeat forever

endfunc

gfx_LedDigits

Draw a series of 7 segment Led Digits as defined by LedDigitDef, using LedDigitRam positioning at position value. This internal widget requires an array of size 12 for LedDigitRam.

The following are the required definitions LedDigitDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
width Widget width (Used only for touch region)
height Widget height (Used only for touch region)
digitCount Number of digits
separator Separator placement (To disable separator use -1)
digitSpacing Spacing distance between each digits
digitSize Digit size
activeColor LED segment ON color
inactiveColor LED segment OFF color
options Option bits (see gfx_LedDigits options tables)

The table below list all the option bits for the options definition:

Options Bit/Flag Description
LEDDIGITS_F_UNSIGNED 0x0000 Show value as unsigned (default)
LEDDIGITS_F_SIGNED 0x0010 Show value as signed
LEDDIGITS_F_LEADINGb 0x0000 Hide leading zeroes (default)
LEDDIGITS_F_LEADING0 0x0020 Show leading zeroes
LEDDIGITS_F_DP_DOT 0x0000 Show dot as separator (default)
LEDDIGITS_F_DP_COMMA 0x0040 Show comma as separator
Data Types
LEDDIGITS_F_INT16 0x0000 16-bit integer mode (default)
LEDDIGITS_F_INT32 0x0004 32-bit integer mode
value should be a 2 element array containing a 32-bit integer value
LEDDIGITS_F_FLOAT 0x0008 Floating point mode
value should be a 2 element array containing a 32-bit float value
(when using this option, format needs to be specified)
Format
LEDDIGITS_F_GENERAL 0x0003 Display float value using the general format
LEDDIGITS_F_FIXED 0x0002 Display float value using the fixed format
LEDDIGITS_F_SCIENTIFIC 0x0001 Display float value using the scientific format

Syntax: gfx_LedDigits(value, &LedDigitRam, &LedDigitDef);

Argument Description
value A value (usually a constant) specifying the current frame of the widget
&LedDigitRam A pointer to a variable array for widget utilization
&LedDigitDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var value;
var Digits1RAM [12];

#DATA
word Digits1Info    10, 10, 66, 106, 2, 0, 0, 5, 0xFFFF, 0x630C,
        (LEDDIGITS_F_LEADING0 | LEDDIGITS_F_UNSIGNED | LEDDIGITS_F_INT16 | LEDDIGITS_F_DP_DOT)
#END

func main()

    gfx_LedDigits (value, Digits1RAM, Digits1Info); // LED digit Widget 
    repeat forever

endfunc

gfx_LedDigit

Draws a single 7 segment led Digit at x, y of size digitsize using oncolour and offcolour. By default, the value can be 0-9 (0-9), A-F (0x0a-0x0f), blank(0x10) and - (0x11).

Additional options can be used in value as described in the table:

Options Bit/Flag Description
LEDDIGIT_F_DP_COMMA 0x0400 Uses a comma as the decimal point
LEDDIGIT_F_SHOW_DP 0x0800 Adds a decimal point to the value displayed
LEDDIGIT_F_SET_SEGMENTS 0x1000 Allows segments to be individually set

LEDDIGIT_F_SET_SEGMENTS can be used to turn value into a series of bits to turn on individual segments. For example, LEDDIGIT_F_SET_SEGMENTS + 9 will turn ON the top and bottom segments.

In this mode, LEDDIGIT_F_SHOW_DP and LEDDIGIT_F_DP_COMMA can be used, but in this case the DP is the 8th segment.

Syntax: gfx_LedDigit(x, y, digitsize, oncolour, offcolour, value);

Argument Description
x, y Specifies the top-left position of the digit
digitsize Specifies the size of the digit
oncolour Specifies the active colour of the segments/LEDs
offcolour Specifies the inactive colour of the segments/LEDs
value Specifies the value to show

Return: None

Example

// Show 3 in the 7-segment LED digit
gfx_LedDigit(10, 10, 5, YELLOW, LIME, 3);
// Show 4. in the 7-segment LED digit
gfx_LedDigit(10, 10, 5, YELLOW, LIME, 4 + LEDDIGIT_F_SHOW_DP);
// Turn ON top and bottom segments
gfx_LedDigit(10, 10, 5, YELLOW, LIME, 9 + LEDDIGIT_F_SET_SEGMENTS);

gfx_Scale

Draw a Scale as defined by ScaleDef, setting LedRam for use in touch processing. See the reference for the ScaleDef values. If touch processing is not required 0 may be used as the ScaleRam parameter.

The following are the required definitions LedDigitDef:

Definition Description
xpos Top-Left X-position
ypos Top-Left Y-position
length Length
minValue Minimum value
maxValue Maximum value
majorSectionCount Major tick partitions
majorTickLength Major tick length
minorTickCount Number of minor ticks inside each partition
minorTickLength Minor tick length
tickColor Tick color
fontBgColor Marker text background color
fontFgColor Marker text color
fontStyle Marker text font style
gapSize Gap size for centred marker text to ticks
options Option bits (see gfx_Scale option bits table)

The table below list all the option bits for the options definition:

Options Bit/Flag Description
SCALE_NONE 0x0000 Disables scale marker labels (default)
SCALE_TL 0x0001 Align scale marker labels to Top/Left side of the axis
SCALE_BR 0x0002 Align scale marker labels to Bottom/Right side of the axis
SCALE_CENTRE 0x0003 Align scale marker labels to Centre of the axis
SCALE_TICKS_NONE 0x0000 Disables marker ticks (default)
SCALE_TICKS_TL 0x0004 Align marker ticks to Top/Left side of the axis
SCALE_TICKS_BR 0x0008 Align marker ticks to Bottom/Right side of the axis
SCALE_TICKS_BOTH 0x000C Align marker ticks on both side of the axis
SCALE_HORZ 0x0000 Set scale orientation to horizontal (default)
SCALE_VERT 0x0010 Set scale orientation to vertical
SCALE_NO_END_ALIGN 0x0000 Always align each marker label to the ticks
SCALE_END_ALIGN 0x0020 Aligning the end marker labels to the end marker ticks
This makes the end labels fit inside the whole scale
SCALE_HIDE_ZERO 0x0000 Prevent zero value from showing as a label (default)
SCALE_SHOW_ZERO 0x0040 Allow zero digit in the scale markers

Syntax: gfx_Scale(&ScaleRam, &ScaleDef);

Argument Description
&ScaleRam A pointer to a variable array for widget utilization
&ScaleDef A pointer to the Data Block holding the widget parameters

Return: None

Example

var ImageRAM1[10];

#DATA
    word Image1Info     36, 10, 197, 0, 100, 5, 10, 2, 5, 0xFFFF, 0x0, 0xFFFF, FONT3, 0,
        (SCALE_CENTRE | SCALE_TICKS_BOTH | SCALE_VERT | SCALE_END_ALIGN | SCALE_SHOW_ZERO)
#END

func main()

    gfx_Scale(ImageRAM1, Image1Info); // Scale object
    repeat forever

endfunc

gfx_Panel

Draws a 3-dimensional rectangular panel at a screen location defined by x, y parameters (top left corner). The size of the panel is set with the width and height parameters. The colour is defined by colour. The state parameter determines the appearance of the panel, 0 = recessed, 1 = raised.

Syntax: gfx_Panel(state, x, y, width, height, colour);

Argument Description
state 0 : Recessed
1 : Raised
x, y Specifies the top left corner position of the panel on the screen
width Specifies the width of the panel
height Specifies the height of the panel
colour Specifies the colour of the panel

Return: None

Example

#constant LEFT 15
#constant TOP  15
#constant WIDTH  100
#constant HEIGHT 100

func main()

    // Draw a panel
    gfx_Panel(RAISED, LEFT, TOP, WIDTH, HEIGHT, GRAY);

    repeat forever

endfunc

gfx_Panel2

Draws a panel2 (groupbox) at screen location defined by x, y, width and height with left colour "cl" and right colour "cr". w1 and w2 define the width of the outer and inner borders.

Syntax: gfx_Panel2(state, x, y, width, height, w1, w2, cl, cr);

Argument Description
state 0 : Recessed (Bevel is inwards)
1 : Raised (Bevel is outwards))
add PANEL2_FILLED to fill color with cf
x, y Specifies the top left corner position of the panel on the screen
width Specifies the width of the panel
height Specifies the height of the panel
w1 Specifies the outer bevel offset
w2 Specifies the inner bevel offset
cl Specifies the main bevel colour of the panel
cr Specifies the shadow bevel colour of the panel
cf Specifies the fill colour of the panel

Return: None

Example

func main()
    gfx_Panel2(1, 10, 10, 77, 81, 5, 5, 0xFFFF, 0x528A, 0x8800); // Panel object
    repeat forever
endfunc

gfx_GradientShape

Produce a shaped color gradient using the supplied parameters This function requires a quantity of RAM to work which needs to be initialised beforehand as a global array. It's size varies according to the largest corner radius. When initializing the format below can be used:

var gradientRAM[29 + xxx * 2] := [-1,-1, -9999, 0, 0, xxx];

where xxx is maximum radius + 1

For example: gradientRAM[29+91*2] := [-1, -1, -9999, 0, 0, 91];

This can support a maximum radius of 90 pixels. Notice the 91 in two places.

Multiple gradient shape calls can share the same GradientRAM.

Syntax: gfx_GradientShape(GradientRAM, HorzVert, OuterWidth, X, Y, W, H, TLrad, TRrad, BLrad, BRrad, Darken, OuterColor, OuterType, OuterLevel, InnerColor, InnerType, InnerLevel, Split);

Argument Description
GradientRAM RAM buffer initialized to use for rendering gradient shapes
HorzVert 0 : Horizontal
1 : Vertical
OuterWidth Outer gradient width
X x co-ordinate
Y y co-ordinate
W Width
H Height
TLrad Top left corner radius
TRrad Top right corner radius
BLrad Bottom left radius
BRrad Bottom right radius
Darken Darken both colours by a value. Can be a negative value to lighten
OuterColor Outer gradient colour
OuterType 0 : Raised
1 : Sunken
2 : Raised flatter middle
3 : Sunken flatter middle
add 4 for Vertical mode
InnerLevel Inner Gradient level, Range: 0 - 63
Split Split gradient:
0 no split
1 : top
2 : bottom

Return: None

Example

gfx_GradientShape(GradientRAM, HorzVert, OuterWidth, X, Y, W, H, TLrad, TRrad, BLrad, BRrad,
        Darken, OuterColor, OuterType, OuterLevel, InnerColor, InnerType, InnerLevel, Split);

Note

This function is only available in Flash mode PIXXI PmmC

gfx_GradientColor

Given the parameters, adjust the input color to produce the output color.

Syntax: gfx_GradientColor(Type, Darken, Level, H, Pos, Color);

Argument Description
Type
0 : Raised
1 : Sunken
2 : Raised flatter middle
3 : Sunken flatter middle
add 4 for Vertical mode
Darken Darken colour by a value. Can be a negative value to lighten
Level Gradient level, Range: 0 - 63
H Height of the object that gradient is applied
Pos Position in the height that gradient is calculated
Color Source colour that gradient is applied to

Return: Colour after adjustment

Example

gfx_GradientColor(Type, Darken, Level, H, Pos, Color);

Note

This function is only available in Flash mode PIXXI PmmC

gfx_GradTriangleFilled

Produce a triangle with or without a gradient.

Syntax: gfx_GradTriangleFilled(X0, Y0, X1, Y1, X2, Y2, SolidCol, GradientCol, GradientHeight, GradientY, GradientLevel, Type);

Argument Description
X0 First triangle point x coordinate
Y0 First triangle point y coordinate
X1 Second triangle point x coordinate
Y1 Second triangle point y coordinate
X2 Third triangle point x coordinate
Y2 Third triangle point y coordinate
SolidCol Colour that will be used if the Solid or Gradient parameter is set to 0
GradientCol Colour that will be used if the Solid or Gradient parameter is set to 1
GradientHeight Height of the area that the gradient will be calculated. Can be larger than the triangle
GradientY Position on the Y axis that the gradient will be calculated from with respect to triangle position
GradientLevel Level of gradient applied
Type Select wether solid triangle or gardient triangle is drawn.

Return: None

Example

gfx_GradTriangleFilled(10, 10, 10, 100, 100, 100 ,YELLOW, DARKKHAKI, 100, 10, 30, 1);

Note

This function is only available in Flash mode PIXXI PmmC

I2C Master Functions

I2Cx_Open

This function configures the I2C module and initialises it to be ready. The I2C clock speed is specified by the speed parameter. Three I2C Speed settings are available to suit various requirements.

I2C Pin PIXXI-28 Pin PIXXI-44 Pin
I2C1 Bus SCL1 1 38
SDA1 2 37
I2C2 Bus SCL2 NA 25
SDA2 NA 27
I2C3 Bus SCL3 3 19
SDA3 12 42

The following are the available speed options:

Constant Speed
I2C_SLOW 100 kHz
I2C_MED 400 kHz
I2C_FAST 1 MHz

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Open(Speed); or I2C2_Open(Speed); or I2C3_Open(Speed);

Argument Description
Speed Specifies the I2C bus speed

Return: None

Example

I2C1_Open(I2C_MED); // Open the I2C1 port in 400KHz mode.

I2Cx_Close

Calling this function closes the I2C port and disables the I2C hardware

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Close(); or I2C2_Close(); or I2C3_Close();

Return: None

Example

I2C1_Close(); // Close I2C1 port and Disable the hardware

I2Cx_Start

Calling this function sends an I2C start condition. The hardware first pulls the SDA (data) line low, and next pulls the SCL (clock) line low.

Start Condition

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Start(); or I2C2_Start(); or I2C3_Start();

Return: None

Example

I2C1_Start(); // Send an I2C start condition

I2Cx_Stop

Calling this function sends an I2C stop condition. The hardware first releases the SCL to high state, and then releases the SDA line high.

Stop Condition

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Stop(); or I2C2_Stop(); or I2C3_Stop();

Return: None

Example

I2C1_Stop(); // Send an I2C stop condition

I2Cx_Restart

Calling this function generates a restart condition

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Restart(); or I2C2_Restart(); or I2C3_Restart();

Return: None

Example

I2C1_Restart() ; // Generates an I2C restart condition

I2Cx_Read

Calling this function reads a single byte from the I2C bus

Note

  • Data can only change when the clock is low.
  • This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Read(); or I2C2_Read(); or I2C3_Read();

Return: Byte from the I2C Bus in the lower 8 bits

Example

c := I2C1_Read() ; // Read a single byte from the I2C1 Bus

I2Cx_Write

Calling this function sends a single byte to the I2C bus

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Write(byte); or I2C2_Write(byte); or I2C3_Write(byte);

Argument Description
byte The byte to be written to the I2C Bus

Return:

  • 0: Failed
  • 1: Success
  • 2: NAK was received from device

Example

status := I2C1_Write(bytevalue); // Send a single byte to the I2C

I2Cx_Ack

Calling this function sends an I2C acknowledge condition. The hardware first pulls the SDA line low, and next releases SCL high followed by pulling SCL low again thus generating a clock pulse, SDA is then released high.

Note

  • Data can only change when the clock is low
  • This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Ack(); or I2C2_Ack(); or I2C3_Ack();

Return: None

Example

I2C1_Ack(); // Send I2C Acknowledge condition

I2Cx_Nack

Calling this function sends an I2C negative acknowledge condition. The hardware first releases the SDA line high, and next releases SCL HI followed by pulling SCL low thus generating a clock pulse.

Note

  • Data can only change when the clock is low.
  • This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Nack(); or I2C2_Nack(); or I2C3_Nack();

Return: None

Example

I2C1_Nack(); //Send an I2C Negative acknowledge condition

I2Cx_AckStatus

Call this function to get the ACK status from the slave device. The state of SDA is returned.

Note

  • Returns the state of SDA after the last clock pulse
  • This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_AckStatus(); or I2C2_AckStatus(); or I2C3_AckStatus();

Return: Device ACK status

Example

r := I2C1_AckStatus(); // returns the ACK Status

I2Cx_AckPoll

Call this function to wait for a device to return an ACK during ACK polling. The SDA is monitored for an Ack.

Note

  • Returns the state of SDA after the last clock pulse
  • This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_AckPoll(control); or I2C2_AckPoll(control); or I2C3_AckPoll(control);

Argument Description
control The control word to be written to the device

Return: Device ACK status

Example

r := I2C1_AckPoll(0xA0);   // send the control byte the wait for a device
                    // to return poll the device until an ACK is received

I2Cx_Idle

Call this function to wait until the I2C bus is inactive.

Note

  • Waits for the bus to become idle
  • This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Idle(); or I2C2_Idle(); or I2C3_Idle();

Return: Device ACK status

Example

r := I2C1_Idle(); // Wait until the I2C1 Bus is inactive

I2Cx_Gets

Reads up to size characters into buffer from an ascii string stored in a device. Reads up to the ASCII NULL terminator and includes the terminator.

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Gets(buffer, size); or I2C2_Gets(buffer, size); or I2C3_Gets(buffer, size);

Argument Description
buffer Storage for the string being read from the device
size Maximum size of the string to be read

Return: Number of bytes read

Example

c := I2C1_Gets(buf, size);    // read a string from the
            // I2C1 Bus to buffer up to size characters

I2Cx_Getn

Reads up to size characters into buffer from an ascii string stored in a device. Reads up to the ASCII NULL terminator and includes the terminator.

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Getn(buffer, count); or I2C2_Getn(buffer, count); or I2C3_Getn(buffer, count);

Argument Description
buffer Storage for the bytes being read from the device
count Number of bytes to be read

Return: True if block read ok else returns False

Example

I2C1_Getn(buffer, count); // read I2C count bytes from the I2C1 Bus to the buffer

I2Cx_Puts

Writes an ASII string from buffer to a device. The ASCII NULL terminator is also written.

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Puts(buffer); or I2C2_Puts(buffer); or I2C3_Puts(buffer);

Argument Description
buffer Storage for the string being written to the device

Return: Number of bytes written

Example

c := I2C1_Puts(mybuf); // write an ASCII string from buffer to the I2C1 bus

I2Cx_Putn

Writes count bytes from the buffer to the device, and returns count if function succeeds.

Note

This functions is available for all 3 I2C buses of PIXXI-44 and 2 I2C buses of PIXXI-28. The functions are prepended with I2Cx where x is 1 to 3. This represents the bus number and can be checked from the display and processor datasheets.

Syntax: I2C1_Putn(buffer, count); or I2C2_Putn(buffer, count); or I2C3_Putn(buffer, count);

Argument Description
buffer Storage for the bytes being written to the device
count Number of bytes to be written

Return: Number of bytes written

Example

b := I2C1_Putn(mybuf, count); // write count bytes
                // from the buffer to the I2C1 bus

Image Control Functions

img_SetPosition

This function requires that an image control has been created with file_LoadImageControl(...).

Sets the position where the image will next be displayed. You may turn off an image using img_Disable() so when img_Show() is called, the image will not be shown.

Syntax: img_SetPosition(handle, index, xpos, ypos);

Argument Description
handle Pointer to the Image List
index Index of the images in the list
xpos Top left horizontal screen position where image is to be displayed
ypos Top left vertical screen position where image is to be displayed

Return: True if successful

Example

gfx_Panel(PANEL_RAISED, 0, 0, 239, 239, GRAY);  // make a simple 'window'
img_SetPosition(hndl, BTN_EXIT, 224, 2);    // set checkout box position
img_Enable(hndl, BTN_EXIT);                 // enable checkout box

img_Enable

This function requires that an image control has been created with file_LoadImageControl(...).

Enables a selected image in the image list. This is the default state so when img_Show() is called all the images in the list will be shown. To enable all the images in the list at the same time set index to -1. To enable a selected image, use the image index number.

Syntax: img_Enable(handle, index);

Argument Description
handle Pointer to the Image List
index Index of the images in the list

Return: True if successful

Example

r := img_Enable(hImageList, imagenum);

img_Disable

This function requires that an image control has been created with file_LoadImageControl(...).

Disables an image in the image list. Use this function to turn off an image so that when img_Show() is called the selected image in the list will not be shown.

To disable all the images in the list at the same time set index to -1. To disable a selected image, use the image index number.

Syntax: img_Disable(handle, index);

Argument Description
handle Pointer to the Image List
index Index of the images in the list

Return: True if successful

Example

r := img_Disable(hImageList, imagenum);

img_Darken

This function requires that an image control has been created with file_LoadImageControl(...).

Darken an image in the image list. Use this function to darken an image so that when img_Show() is called the control will take effect.

To darken all the images in the list at the same time set index to -1.

Note

This feature will take effect one time only and when img_Show() is called again the darkened image will revert back to normal.

Syntax: img_Darken(handle, index);

Argument Description
handle Pointer to the Image List
index Index of the images in the list

Return: True if successful

Example

r := img_Darken(hImageList, imagenum);

img_Lighten

This function requires that an image control has been created with file_LoadImageControl(...).

Lighten an image in the image list. Use this function to lighten an image so that when img_Show() is called the control will take effect.

To lighten all the images in the list at the same time set index to -1.

Note

This feature will take effect one time only and when img_Show() is called again the lightened image will revert back to normal.

Syntax: img_Lighten(handle, index);

Argument Description
handle Pointer to the Image List
index Index of the images in the list

Return: True if successful

Example

r := img_Lighten(hImageList, imagenum);  

img_SetWord

This function requires that an image control has been created with file_LoadImageControl(...).

This set the specified word in an image entry. The following are the available parameters that can be set:

Offset Constant Value Description
IMAGE_XPOS 2 Specifies the image location X
IMAGE_YPOS 3 Specifies the image location Y

IMAGE_FLAGS

6 Specifies the image flags
IMAGE_DELAY 7 Specifies the inter frame delay
IMAGE_INDEX 9 Specifies the current frame
IMAGE_TAG 12 Specifies the user variable #1
IMAGE_TAG2 13 Specifies the user variable #2

Note

img_Show() will now show error box for out of range video frames. Also, if frame is set to -1, just a rectangle will be drawn in background colour to blank an image.

Syntax: img_SetWord(handle, index, offset, word);

Argument Description
handle Pointer to the Image List
index Index of the images in the list
offset Offset of the required word in the image entry
word The word to be written to the entry

Return: True if successful

Example

func cat()
    var private frame := 0;          // start with frame 0
    var private image := SPRITE_CAT; // cat image, can be changed with  cat.image := xxx
    img_SetWord(Ihndl, image, IMAGE_INDEX, frame++);
    frame := frame % img_GetWord(Ihndl, image, IMAGE_FRAMES);
    img_Show(Ihndl, image);
    sys_SetTimer(TIMER3, 30);      // reset the event timer
endfunc

img_GetWord

This function requires that an image control has been created with file_LoadImageControl(...). Returns specified word from an image entry.

Offset Constant Value Description
IMAGE_LOWORD 0 Specifies the image address LO
IMAGE_HIWORD 1 Specifies the image address HI
IMAGE_XPOS 2 Specifies the image location X
IMAGE_YPOS 3 Specifies the image location Y
IMAGE_WIDTH 4 Specifies the image width
IMAGE_HEIGHT 5 Specifies the image height

IMAGE_FLAGS

6 Specifies the image flags
IMAGE_DELAY 7 Specifies the inter frame delay
IMAGE_FRAMES 8 Specifies the number of frames
IMAGE_INDEX 9 Specifies the current frame
IMAGE_CLUSTER 10 Specifies the image start cluster pos (for FAT16 only)
IMAGE_SECTOR 11 Specifies the image start sector in cluster pos (for FAT16 only)
IMAGE_TAG 12 Specifies the user variable #1
IMAGE_TAG2 13 Specifies the user variable #2

Syntax: img_GetWord(handle, index, offset);

Argument Description
handle Pointer to the Image List
index Index of the images in the list
offset Offset of the required word in the image entry

Return: the image entry in the list

Example

myvar := img_GetWord(hndl, 5, IMAGE_YPOS);

img_Show

This function requires that an image control has been created with file_LoadImageControl(...).

Display the image entry from the image control.

Syntax: img_Show(handle, index);

Argument Description
handle Pointer to the Image List
index Index of the images in the list

Return: True if successful

Example

img_Show(hndl, imageIndex);

img_SetAttributes

This function requires that an image control has been created with file_LoadImageControl(...).

This function sets one or more bits in the IMAGE_FLAGS field of an image control entry.

A '1' bit in the "value" field sets the respective bit in the IMAGE_FLAGS field of the image control entry which may be combined with the + or | operators.

Flag Constant Bit Value Description
I_ENABLED 15 0x8000 set for image enabled
I_DARKEN 14 0x4000 display dimmed
I_LIGHTEN 13 0x2000 display bright
I_TOUCHED 12 0x1000 touch test result
I_Y_LOCK 11 0x0800 stop Y movement
I_X_LOCK 10 0x0400 stop X movement
I_TOPMOST 9 0x0200 draw on top of other images next update
I_STAYONTOP 8 0x0100 draw on top of other images always
I_TOUCH_DISABLE 5 0x0020 set to disable touch for this image:
1 for movie or 0 for image

Syntax: img_SetAttributes(handle, index, value);

Argument Description
handle Pointer to the Image List
index Index of the images in the list
value Refers to various bits in the image control entry (see image attribute flags)

Return: True if successful

Example

img_SetAttributes(Ihndl, ALL, I_TOUCH_DISABLE);         // Disable touch in all images
img_SetAttributes(Ihndl, ALL, I_Y_LOCK | I_X_LOCK );    // Prevents movement in all images

img_ClearAttributes

This function requires that an image control has been created with file_LoadImageControl(...).

Clear various image attribute flags in an image control entry.

Flag Constant Bit Value Description
I_ENABLED 15 0x8000 set for image enabled
I_DARKEN 14 0x4000 display dimmed
I_LIGHTEN 13 0x2000 display bright
I_TOUCHED 12 0x1000 touch test result
I_Y_LOCK 11 0x0800 stop Y movement
I_X_LOCK 10 0x0400 stop X movement
I_TOPMOST 9 0x0200 draw on top of other images next update
I_STAYONTOP 8 0x0100 draw on top of other images always
I_TOUCH_DISABLE 5 0x0020 set to disable touch for this image:
1 for movie or 0 for image

Note

Image attribute flags may be combined with the + or | operators

Syntax: img_ClearAttributes(handle, index, value);

Argument Description
handle Pointer to the Image List
index Index of the images in the list
value A '1' bit indicates that a bit should be set and a '0' bit indicates that a bit is not altered.

Note

If index is set to -1, the attribute is altered in ALL the entries in the image list.

Return: True if successful

Example

img_ClearAttributes(Ihndl, iWinbutton1, I_TOUCH_DISABLE); // Enable touch in all images
img_ClearAttributes(hndl, ALL, I_Y_LOCK | I_X_LOCK );     // Allows movement in all images

img_Touched

This function requires that an image control has been created with file_LoadImageControl(...).

Returns index if image touched or returns -1 if no image was touched.

If index is passed as -1 the function tests all images and returns -1 if no image was touched or returns index.

Syntax: img_Touched(handle, index);

Argument Description
handle Pointer to the Image List
index Index of the images in the list

Return: index of image touched, released or being held, or -1 if none

Example

if (state ==  TOUCH_PRESSED)
    n := img_Touched(Ihndl, -1);    // scan image list, looking for a touch
    if (n != -1)
        last := n;
        button := n;
        img_Lighten(Ihndl, n);      // lighten the button touched
        img_Show(Ihndl, -1);        // restore the images
    endif
endif

img_FileRead

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Reads the number of bytes specified by size from the file referenced by handle into a destination memory buffer. If dest is zero, data is directed to GRAM window.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileRead(*dest, size, handle, index);

Argument Description
dest Pointer to a destination memory buffer
size Number of bytes to read
handle Pointer to the image file control
index Index of the entry in the handle

Return: Number of characters read

Example

res := img_FileRead(memblock, 20, hnd1);

img_FileSeek

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Set file position to specified address for the file handle so subsequent data may be read from that position onwards with img_FileGetC(...), img_FileGetW(...) or img_FileGetS(...).

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileSeek(handle, index, HiWord, LoWord);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle
HiWord Contains the upper 16 bits of the file position
LoWord Contains the lower 16 bits of the file position

Return: True if successful

Example

res := img_FileSeek(hndl, 0, 0x1234); // Set file position to 0x00001234 (byte position 4660)

img_FileIndex

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Set file seek position to specified address for the file handle so subsequent data may be read from that position onwards with img_FileGetC(...), img_FileGetW(...) or img_FileGetS(...).

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileIndex(handle, index, HiSize, LoSize, recordnum);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle
HiSize Contains the upper 16 bits of the size of the file records
LoSize Contains the lower 16 bits of the size of the file records
recordnum The index of the required record

Return: True if successful

Example

res := img_FileIndex(hndl, 0, 1000, 123, 1); // set file seek position to 123000

img_FileTell

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Reads the current 32-bit file pointer and stores it into the two variables specified in HiWord and LoWord.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileTell(handle, index, &HiWord, &LoWord);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle
HiWord Specifies location for the upper 16 bits of the file pointer
LoWord Specifies location for the lower 16 bits of the file pointer

Return: True if successful

Example

img_FileTell(hndl, index, Hiptr, Loptr);

img_FileSize

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Reads the 32-bit file size and stores it into the two variables specified in HiWord and LoWord.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileSize(handle, index, &HiWord, &LoWord);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle
&HiWord Specifies location for the upper 16bits of the file size
&LoWord Specifies location for the lower 16bits of the file size

Return: True if successful

Example

img_FileTell(hndl, index, Hiptr, Loptr);

img_FileGetC

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

This function reads a byte from the file, at the position indicated by the associated file-position pointer and advances the pointer appropriately (incremented by 1).

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileGetC(handle, index);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle

Return: 8-bit (byte) data read from the file

Example

mychar := img_FileGetC(hndl, index);

img_FileGetW

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

This function reads a word (2 bytes) from the file, at the position indicated by the associated file-position pointer and advances the pointer appropriately (incremented by 2).

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileGetW(handle, index);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle

Return: 16-bit (word) data read from the file

Example

myword := img_FileGetW(hndl, index);

img_FileGetS

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

This function reads a line of text to a buffer (specified by *string) from a file at the current file position indicated by the associated file-position pointer and advances the pointer appropriately.

This function reads only reads up to size - 1 characters into *string (one character is reserved for the null-terminator). Characters are read until either a newline or an EOF is received or until the number of characters read reaches size - 1 or a read error is received.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileGetS(*string, size, handle, index);

Argument Description
string Destination buffer
size The maximum number of bytes to be read from the file
handle Pointer to the image file control
index Index of the entry in the handle

Return: Returns pointer to string or NULL if failed

Example

res := img_FileGets(mystr , 81, hnd1); // read up to 80 chars

img_FileRewind

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Resets the file pointer to the the beginning of the open file.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileRewind(handle, index);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle

Return: True if successful

Example

res := img_FileRewind(hnd1, index);

img_FileLoadFunction

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Load a function or program from disk and return a function pointer to the allocation.

The function can then be invoked just like any other function would be called via a function pointer. Parameters may be passed to it in a conventional way. The caller's stack is shared by the loaded function, however any global variables in the loaded function are private to that function.

The function may be discarded at any time when no longer required, freeing its memory resources through mem_Free(...)

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileLoadFunction(handle, index);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle

Return: pointer to the memory allocation where the function has been loaded from file which can be then used as a function call

Examples

popupWindow := img_FileLoadFunction(hndl, index);
if (!popupWindow) goto LoadFunctionFailed;  // Could not load the function
res := popupWindow(MYMODE, "My Title", "My Popup Text");
if (res == QUIT_APPLICATION) goto exitApp;
res := mem_Free(popupWindow);
if (!res) goto FreeFunctionFailed; // Could not free memory

img_FileRun

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Load a program from disk where the current program releases any allocated memory but retains the stack and global memory.

If arglistptr is 0, no arguments are passed, else, arglist points to an array, the first element being the number of elements in the array.

The func main in the called program accepts the arguments, if any. The arguments can only be passed by value, no pointers or references can be used as all memory is cleared before the file is loaded.

Refer to img_FileExec(...) and img_FileLoadFunction(...) for functions that can pass by reference.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileRun(handle, index, arglistptr);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle
arglistptr Pointer to the list of arguments to pass to the new program

Return: the returned value from main in the called program

Example

res := img_FileRun(hndl, index, argptr);

img_FileExec

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Load a program from disk and returns like a function, the calling program is kept active, and control returns to it.

The function main in the called program accepts the arguments, if any. If arglistptr is 0, no arguments are passed, else arglist points to an array, the first element being the number of elements in the array.

This function is similar to img_FileLoadFunction(...), however, the function argument list is passed by pointer, and the memory consumed by the function is released as soon as the function completes.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileExec(handle, index, arglistptr);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle
arglistptr Pointer to the list of arguments to pass to the new program

Return: the returned value from main in the called program

Example

res := img_FileExec(hndl, index, argptr);

img_FilePlayWAV

This requires that an image file control has been created with file_LoadImageControl under Mode 3.

Play a wave file at index in the image filesystem handle. This automatically grabs a chunk of memory for a file buffer, and a wave buffer.

The minimum memory requirement is about 580 bytes for disk I/O service and a minimum wave buffer size of 1024. The size of wave buffer allocation can be increased by snd_BufSize function. The default size 1024 bytes. The memory is only required during the duration of play and is automatically released while not in use.

See Sound Control Functions for additional play control functions.

This function may return the following error values:

Value Description
-7 Insufficient memory available for WAV buffer and file
-6 cant play this rate
-5 no data chunk found in first rsector
-4 no format data
-3 no wave chunk signature
-2 bad wave file format
-1 file not found

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FilePlayWAV(handle, index);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle

Return: Number of blocks to play (1 to 32767) or negative value in case of errors

Example

print("\nding.wav\n");
for (n:=0; n<45; n++)
    pitch := NOTES[n];
    print([UDEC] pitch,"\r");
    snd_Pitch(pitch);
    file_PlayWAV("ding.wav");
    while(snd_Playing());
    // pause(500);
next

img_TxtFontID

This function requires that an image file control has been created with the file_LoadImageControl(...) under Mode 3.

Set the font to a font held in the image file system.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_TxtFontID(handle, index);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle

Return: None

Example

img_TxtFontID(hnd1, index);

img_FileCheckUpdate

This function requires that an image file control has been created with the file_LoadImageControl(...) under Mode 3.

Checks and/or updates the program running in Flash using the specified file in Flash memory.

The following options determine the mode of operation:

Option Value Description
CHECKUPDATE_QUERY 1 Checks the specified file and compares its DateTime to the program running in Flash
CHECKUPDATE_UPDATENEWER 2 Updates the program in Flash if the program on uSD is newer
CHECKUPDATE_UPDATEALWAYS 3 Always updates the program in Flash

If update occurs and the program is running from Flash, the display is reset after update. Otherwise, if a query or an error occurs, the following is returned:

Option Value Description
CHECKUPDATE_NEWFILE 1 The specified file is newer than the file running in Flash
CHECKUPDATE_OLDFILE 2 The specified file is equal to or older than the file running in Flash
CHECKUPDATE_UPDATEDONE 3 An update was performed, and the program is running from RAM
CHECKUPDATE_NOFILE 4 The specified file does not exist
CHECKUPDATE_INVALIDFILE 5 The specified file is not valid '4xe' or '4fn'

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FileCheckUpdate(handle, index, options);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle
options Determines whether to update always (3), update if newer (2) or simply query (1)

Return: Result of the operation

Example

media_Init();
hndl := file_LoadImageControl(0, 0, 3);
if (file_CheckUpdate(hndl, index,CHECKUPDATE_QUERY) == CHECKUPDATE_NEWFILE)
    print("Program will now update") ;
    file_CheckUpdate(hndl, index, CHECKUPDATE_UPDATENEWER) ;
endif

img_FunctionCall

This function requires that an image file control has been created with the file_LoadImageControl(...) under Mode 3.

This function loads and calls the Function found at index in the Flash GCI filesystem identified by handle.

Parameters state, &FunctionRam and &FunctionDef are passed. The first two parameters are passed "as is", since the third parameter is normally in flash, and one programs flash is not accessible from another.

The FunctionArgCount constant is copied into a RAM array and passed to the Function.

The parameter FunctionStringMap is a bit array of the indexes containing single and multiple stringsthat are offset by 8. e.g., 0x0100 means parameter 8 is a single string, 0x0002 means parameter 9 is an array of strings with parameter 8 containing the count.

Any function called this way is loaded into RAM and then left there. RAM is managed using a Least Recently Used (LRU) mechanism wherein the least recently used entry is freed if there is not enough Heap to load the desired function.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FunctionCall(handle, index, state, &FunctionRam, &FunctionDef, FunctionArgCount, FunctionArgStringMap);

Argument Description
handle Pointer to the image file control
index Index of the entry in the handle
state Value passed to update function state
FunctionRam Pointer to the function RAM allocation
FunctionDef Pointer to the function definitions stored in Flash
FunctionArgCount Function argument count
FunctionArgStringMap String address array

Return: 0 if successful

Example

#DATA
word IIMediaRotaryDef   20, 4, 179, 179, 16, RED, BROWN, GRAY, GRAY, ORANGE,
                        YELLOW, 0x30FE, 3, 75, 13, 120, 2, 135, 405
#END

var IMediaRotaryRAM[WIDGET_RAM_SPACE] ;
var NewVal, hndl;

void main()
    img_FunctionCall(hndl, index, state, IMediaRotaryRAM, IIMediaRotaryDef, 19, 0x0);
    repeat forever
endfunc

img_FunctionFreeCache

This function requires that an image file control has been created with the file_LoadImageControl(...) under Mode 3.

Frees any RAM allocated to caching of functions located in the specified Flash GCI.

Note

  • This is only available for use on the Flash based PmmC version.
  • This is only for files embedded in a GCF, for Flash only, ie. this is not valid for GCI and uSD card access.

Syntax: img_FunctionFreeCache(handle);

Argument Description
handle Pointer to the image file control

Return: None

Example

img_FunctionFreeCache(hndl);

Internal Flash Functions

intflash_GetByte

Reads a single byte from internal flash. Each internal flash pointer location contains a single byte.

Syntax: intflash_GetByte(ptr);

Argument Description
ptr Pointer to a location in the internal flash (0-2047)

Return: Byte value from the location

Example

var myvar; 
myvar := intflash_GetByte(0); // read the 0th byte from internal flash

intflash_GetWord

Reads a single word from any internal flash location. Each internal flash pointer location contains a single byte.

Syntax: intflash_GetWord(ptr);

Argument Description
ptr Pointer to a location in the internal flash (0-2047)

Return: 16-bit value from the location

Example

var myvar; 
myvar := intflash_GetWord(0x0000); // read first word from internal flash

intflash_Copy

Copies bytes from any internal flash locations to a user buffer.

The destination pointer is byte-aligned, so a str_Ptr() must be raised to get correct address.

Syntax: intflash_Copy(ptr, dest, count);

Argument Description
ptr Pointer to a location in the internal flash (0-2047)
dest Byte-aligned pointer to the destination (usually, a pointer to a user array)
count Number of bytes to be copied (max: 2048)

Return: Number of bytes transferred

Example

var myvar, myptr; 
var mybuf[100];
myptr := str_Ptr(mybuf);
// read 20 bytes from internal flash starting from 0x123
myvar := intflash_Copy(0x123, myptr, 20); 

intflash_WriteBlock

Copies a buffer to NVM

Syntax: intflash_WriteBlock(sourceptr, size);

Argument Description
sourceptr Source buffer (word-aligned pointer) to save up to 2K bytes of data from
size Number of bytes to be written (max: 2048)

Return: True (1) if successful, False (0) otherwise

Example

var result;
result := intflash_WriteBlock(buffer, 2048); // store the 2k buffer

intflash_FunctionCall

This function loads and calls the Function found at index in Internal Flash

Parameters state, &FncRam, &FncDef are passed. The first two parameters are passed "as is", since the third parameter is normally in flash, and one programs flash is not accessible from another.

The FncArgCount constant is copied into a RAM array and passed to the Function.

The parameter FncArgStrMap is a bit array of the indexes containing single and multiple strings that are offset by 8. e.g. 0x0100 means parameter 8 is a single string, 0x0002 means parameter 9 is an array of strings with parameter 8 containing the count.

Any function called this way is loaded into RAM and then left there. RAM is managed using a Least Recently Used (LRU) mechanism wherein the least recently used entry is freed if there is not enough Heap to load the desired function.

Syntax: intflash_FunctionCall(handle, index, state, &FncRam, &FncDef, FncArgCount, FncArgStrMap);

Argument Description
handle Widget pointer allocated using widget_LoadFlash()
index Index of the entry in the handle
state Value passed to update function state
&FncRam Pointer to the function RAM allocation
&FncDef Pointer to the function definitions stored in Flash
FncArgCount Function argument count
FncArgStrMap String address array

Return: 0 if successful

Example

#DATA
word IIMediaRotaryDef 20, 4, 179, 179, 16, RED, BROWN, GRAY,
    GRAY, ORANGE, YELLOW, 0x30FE, 3, 75, 13, 120, 2, 135, 405
#END

var IMediaRotaryRAM[WIDGET_RAM_SPACE];
var NewVal, hndl;

void main()

    intflash_FunctionCall(hndl, index, state, IMediaRotaryRAM, IIMediaRotaryDef, 19, 0x0);
    repeat forever

endfunc

intflash_FunctionFreeCache

Frees any RAM allocated to caching of functions located in Internal Flash

Syntax: intflash_FunctionFreeCache(handle);

Argument Description
handle Widget pointer allocated using widget_LoadFlash()

Return: None

Example

intflash_FunctionFreeCache(hndl);

Math Functions

ABS

This function returns the absolute value of value.

Syntax: ABS(value);

Argument Description
value The arguments can be a variable, array element, expression or constant.

Return: the absolute value.

Example

var myvar, number;
number := -100;
myvar := ABS(number * 5); // This example returns 500 in variable myvar

MIN

This function returns the smaller of value1 and value2.

Syntax: MIN(value1, value2);

Argument Description
value 1 A variable, array element, expression or constant.
value 2 A variable, array element, expression or constant.

Return: the smaller of the two values.

Example

var myvar, number1, number2;
number1 := 33;
number2 := 66;
myvar := MIN(number1, number2); // This example returns 33 in variable myvar

MAX

This function returns the larger of value1 and value2.

Syntax: MAX(value1, value2);

Argument Description
value 1 A variable, array element, expression or constant.
value 2 A variable, array element, expression or constant.

Return: the larger of the two values.

Example

var myvar, number1, number2;
number1 := 33;
number2 := 66;
myvar := MAX(number1, number2); // This example returns 66 in variable myvar

SWAP

Given the addresses of two variables (var1 and var2), the values at these addresses are swapped.

Syntax: SWAP(&var1, &var2);

Argument Description
&var1 The address of the first variable.
&var2 The address of the second variable.

Return: None.

Example

// This example swaps the values in number1 and number2.
var myvar, number1, number2;
number1 := 33;
number2 := 66;
SWAP(&number1, &number2);
// After the function is executed, number1 will hold 66, and number2 will hold 33.

SIN

This function returns the sine of an angle. The input value is automatically shifted to lie within 0-359 degrees.

The returned value range is from 127 to -127 which is a more useful representation for graphics work. The real sine values vary from 1.0 to -1.0 so appropriate scaling must be done in user code as required.

Syntax: SIN(angle);

Argument Description
angle The angle in degrees.

Return: the sine in radians of an angle specified in degrees.

Example

var myvar, angle;
angle := 133;
// This example returns 92 in variable 'myvar'
myvar := SIN(angle);

COS

This function returns the cosine of an angle. The input value is automatically shifted to lie within 0-359 degrees.

The returned value range is from 127 to -127 which is a more useful representation for graphics work. The real sine values vary from 1.0 to -1.0 so appropriate scaling must be done in user code as required.

Syntax: COS(angle);

Argument Description
angle The angle in degrees.

Return: the cosine in radians of an angle specified in degrees.

Example

var myvar, angle;
angle := 133;
// This example returns -86 in variable 'myvar'
myvar := COS(angle);

RAND

This function returns a pseudo random signed number ranging from -32768 to +32767.

Returns a pseudo random signed number ranging from -32768 to +32767 each time the function is called. The random number generator may first be seeded by using the SEED(number) function. The seed will generate a pseudo random sequence that is repeatable. You can use the modulo operator (%) to return a number within a certain range, eg n := RAND() % 100; will return a random number between -99 and +99. If you are using random number generation for random graphics points, or only require a positive number set, you will need to use the ABS function so only a positive number is returned, eg: X1 := ABS(RAND() % 100); will set co-ordinate X1 between 0 and 99. Note that if the random number generator is not seeded, the first number returned after reset or power up will be zero. This is normal behavior.

Syntax: RAND();

Return: pseudo random signed number ranging from -32768 to +32767.

Example

SEED(1234);
// This example will print '3558, 1960' to the display.
print(RAND(),", ",RAND());

SEED

This function seeds the pseudo random number generator so it will generate a new repeatable sequence. The seed value can be a positive or negative number.

Syntax: SEED(number);

Argument Description
number Specifies the seed value for the pseudo random number generator.

Return: None.

Example

SEED(-50);
// This example will print '30129, 27266' to the display.
print(RAND(),", ",RAND());

SQRT

This function returns the integer square root which is the greatest integer less than or equal to the square root of number.

Syntax: SQRT(number);

Argument Description
number Specifies the positive number for the SQRT function.

Return: the integer square root of a number.

Example

var myvar;
// returns 161 in 'myvar' which is the 'integer square root' of 26000
myvar := SQRT(26000);

OVF

This function returns the high order 16 bits from certain math and shift functions. It is extremely useful for calculating 32 bit address offsets for MEDIA access. It can be used with the shift operations, addition, subtraction, multiplication and modulus operations.

Syntax: OVF();

Return: the high order 16 bits from certain math and shift functions.

Example

var loWord, hiWord;
loWord := 0x2710 * 0x2710; // (10000 * 10000 in hex format)
hiWord := OVF();
print("0x", [HEX] hiWord, [HEX] loWord);
// This example will print '0x05F5E100' to the display
// which is 100,000,000 in hexadecimal

CY

This function returns the carry status of an unsigned overflow from any 16 or 32bit additions or subtractions.

Syntax: CY();

Return: 0 or 1 as the status of carry.

Example

var myvar;
myvar := 0xFFF8 + 9;                                // result = 1
print("myvar ", myvar,"\nCarry ", CY(),"\n");   // carry = 1

// This example will print 'myvar 1 Carry 1'

umul_1616

This function performs an unsigned multiply of 2 x 16bit values placing the 32bit result in a 2 word array.

Syntax: umul_1616(&res32, val1, val2);

Argument Description
&res32 Points to 32bit result register.
val1 16bit register or constant.
val2 16bit register or constant.

Return: the pointer to the 32bit result. Carry and overflow are not affected.

Example

var val32[2];
var p;
umul_1616(val32, 500, 2000);
p := str_Ptr(val32);
str_Printf(&p, "%ld");

// This example prints 1000000

uadd_3232

This function performs an unsigned addition of 2 x 32bit values placing the 32bit result in a 2 word array.

Syntax: uadd_3232(&res32, &val1, &val2);

Argument Description
&res32 Points to 32bit result register.
&val1 Points to 32bit augend.
&val2 Points to 32bit addend.

Return: 1 on 32bit unsigned overflow (carry). Carry flag is also set on 32bit unsigned overflow and can be read with the CY() function.

Example

var carry, valA[2], valB[2], Result[2];
var p;
valA[0] := 0;
valA[1] := 1;
valB[0] := 0;
valB[1] := 1;

carry := uadd_3232(Result, valA, valB);
p := str_Ptr(Result);
print("0x");
str_Printf(&p, "%lX");  // prints the value at pointer in Hex long format.

// This example will print 0x20000

usub_3232

This function performs an unsigned subtraction of 2 x 32bit values placing the 32bit result in a 2 word array.

Syntax: usub_3232(&res32, &val1, &val2);

Argument Description
&res32 Points to 32bit result register.
&val1 Points to 32bit augend.
&val2 Points to 32bit addend.

Return: 1 on 32bit unsigned overflow (carry). Carry flag is also set on 32bit unsigned overflow and can be read with the CY() function.

Example

var carry, valA[2], valB[2], Result[2];
var p;
valA[0] := 0;
valA[1] := 0xFFFF;
valB[0] := 0;
valB[1] := 0xEFFF;

carry := usub_3232(Result, valA, valB);
p := str_Ptr(Result);
print("0x");
str_Printf(&p, "%lX");
repeat forever

// This example will print 0x10000000

ucmp_3232

This function performs an unsigned comparison of 2 x 32bit values. The result of the subtraction is returned.

This function does not affect the carry flag.

Syntax: ucmp_3232(&val1, &val2);

Argument Description
&val1 points to 32bit augend
&val2 points to 32bit addend

Return:

  • 0 if val1 = val2
  • 1 if val1 > val2
  • -1 if val1 < val2

Example

var valA[2], valB[2], Result;

valA[0] := 0;
valA[1] := 0xFFFF;
valB[0] := 0;
valB[1] := 0xEFFF;

Result  := ucmp_3232(valA, valB); // val1 > val2
print(Result);
repeat forever

// This example will print 1.

udiv_3232

This function performs an unsigned division of 2 x 32bit values placing the 32bit result in a 2 word array. Note A division by zero will result is 0xFFFFFFFF.

Syntax: udiv_3232(&res32, val1, val2);

Argument Description
&res32 Points to 32bit result register.
val1 32bit register or dividend.
val2 32bit register or divisor.

Return: the pointer to the 32bit result. Carry and overflow are not affected.

Example

var val32[2], dividend[2], divisor[2] ;
var p;
dividend[0] := 0x5c21 ;   // part of 1661985
dividend[1] := 0x19 ;     // part of 1661985
divisor[0] := 13 ;
divisor[1] := 0 ;
udiv_3232(val32, dividend, divisor);
p := str_Ptr(val32);
str_Printf(&p, "%ld");      // 1661985 / 13 = 127845

Media Functions

The media can be SD/SDHC, microSD or serial (NAND) flash device interfaced to the SPI port.

media_Init

Initialise a uSD/SD/SDHC memory card or a SPI Flash memory device (< 32 MB) for further operations. The SD card or Flash device is connected to the SPI (serial peripheral interface) of the processor.

Syntax: media_Init();

Return:

  • 1 if uSD is found, and has been successfully initialised
  • 0 if uSD is not present, or SPI memory is present

Example

// Waits for SD card to be inserted and initialised, flashing a message if no SD card detected.

while(!media_Init())
    gfx_Cls();
    pause(300);
    puts("Please insert SD card");
    pause(300);
wend

// This example simply initialises the SPI Flash memory

if(!media_Init())
    puts("Flash memory initialised")
endif

media_Init4

The command used to set the flash memory into 4 byte addressing mode, This is not used with uSD cards, only for SPI flash memory that requires 4 byte addressing (ie cards > 32MB). The SPI Flash device is connected to the SPI (serial peripheral interface) of the processor.

Syntax: media_Init4(command);

Argument Description
FLASH_ADDR_DEF_COMMAND The default command will be used to switch most chips into 4 byte mode (0xB7).
FLASH_ADDR_ALWAYS_4BYTE No command will be sent (for chips permanently in 4 byte mode)
0x?? For chips that don't use 0xB7 to put them into 4 byte mode. Refer to the Datasheet associated with the Flash Memory in question.

Return:

  • 1 if uSD is found (Error, this command should not be used when a uSD card is present)
  • 0 if uSD is not present (good) and therefore SPI memory card is present and successfully initialised

Note

For systems with SPI Flash memory device the response will be 0, however, this function still needs to be called to initialise the Flash memory chip.

Example

// This example simply initialises the SPI Flash memory into 4 byte mode for a 32MB card

if(!media_Init4(FLASH_ADDR_DEF_COMMAND))
    puts("Flash memory initialised")
Endif

media_InitSpeed

Initialise a uSD/SD/SDHC memory card at a given speed. The SD card is connected to the SPI (Serial Peripheral Interface) of the processor.

Syntax: media_InitSpeed(speed);

Argument Description
speed Specifies the speed. Speed can be from SPI_SPEED0 (slowest) to SPI_SPEED15 (fastest).

Return: 1 if memory card is successfully initialised, otherwise returns 0

Example

while(!media_InitSpeed(SPI_SPEED0))
    gfx_Cls();
    pause(300);
    puts("Please insert SD card");
    pause(300);
wend

// This example waits for SD card to be inserted and initialised at SPI_SPEED0, flashing a message if no SD card detected.

media_SetAdd

Set media memory internal Address pointer for access at a non sector aligned byte address.

Syntax: media_SetAdd(HIword, LOword);

Argument Description
HIword specifies the high word (upper 2 bytes) of a 4 byte media memory byte address location.
LOword specifies the low word (lower 2 bytes) of a 4 byte media memory byte address location.

Return: None

Example

// sets the media address to byte 513 (which is sector #1, 2nd byte in sector) for subsequent operations.
media_SetAdd(0, 513);

media_SetSector

Set media memory internal Address pointer for sector access.

Syntax: media_SetSector(HIword, LOword);

Argument Description
HIword specifies the high word (upper 2 bytes) of a 4 byte media memory byte address location.
LOword specifies the low word (lower 2 bytes) of a 4 byte media memory byte address location.

Returns: None

Example

// Sets the media address to the 11th sector for subsequent operations
// (which is also byte address 5120)
media_SetSector(0, 10);

media_RdSector

Reads and Returns 512 bytes (256 words) into a destination block (e.g. rdblock[256]) pointed to by the internal Sector pointer. After the read the Sector pointer is automatically incremented by 1.

Syntax: media_RdSector(Destination_Address);

Argument Description
Destination_Address Destination block pointed to by the internal Sector pointer.

Return:

  • TRUE if media response was TRUE.
  • 512 bytes (256 words) in to a destination block.

Example

var rdblock[256];

media_SetSector(0,10)
if (media_RdSector(rdblock));
Print("Data collected");
endif

// This example sets a 512 bytes block and collects data from the address pointed to by media_SetSector() function.

media_WrSector

Writes 512 bytes (256 words) from a source memory block (eg wrblock[256]) into the uSD card. After the write the Sect pointer is automatically incremented by 1.

Syntax: media_WrSector(Source_Address);

Argument Description
Source_Address Source memory block of 512bytes.

Return: TRUE if media response was TRUE.

Example

var wrblock[256];

func main()
prepare_block();

media_SetSector(0,10)
if (media_WrSector(wrblock));
   print("Data transferred");
endif

// This example sets a 512 bytes block and transfers data to the address pointed to by media_SetSector() function.

media_ReadByte

Returns the byte value from the current media address. The internal byte address will then be internally incremented by one.

Syntax: media_ReadByte();

Returns: byte value

Example

var LObyte, HIbyte;
if (media_Init())                       // initialises the media
    media_SetAdd(0, 510);               // sets the media byte address to 510
    LObyte := media_ReadByte();         // reads the last 2 bytes from sector 0
    HIbyte := media_ReadByte();
    print([HEX2]HIbyte,[HEX2]LObyte);
    // If the card happens to be FAT formatted, the result will be “AA55”.
    // The media internal address is internally incremented for each of the byte operations.
endif
repeat forever

media_ReadWord

Returns the word value (2 bytes) from the current media address. The internal byte address will then be internally incremented by one. If the address is not aligned, the word will still be read correctly.

Syntax: media_ReadWord();

Returns: word value

Example

var myword;
if (media_Init())               // initialises the media
    media_SetAdd(0, 510);       // sets the media byte address to 510
    myword := media_ReadWord(); // reads the last word from sector 0
    print([HEX4]myword);    // If the card happens to be formatted, the result will be “AA55”
endif
repeat forever

media_WriteByte

Writes a byte to the current media address that was initially set with media_SetSector(...);

Syntax: media_WriteByte(byte_val);

Argument Description
byte_val The lower 8 bits specifies the byte to be written at the current media address location.

Returns: Non zero if write was successful.

Example

// This example initialises the media, writes some bytes to the required sector,
// then prints the result from the required location.
var n, char;
while (media_Init()==0);            // wait if no SD card detected
media_SetSector(0, 2);              // at sector 2
//media_SetAdd(0, 1024);            // (alternatively, use media_SetAdd(),
                                    // lower 9 bits
while (n < 10)
    media_WriteByte(n++ +'0');      // write ASCII '0123456789' to the
wend                                // first 10 locations.

to(MDA); putstr("Hello World");     // now write a ascii test string
media_WriteByte('A');               // write a further 3 bytes
media_WriteByte('B');
media_WriteByte('C');
media_WriteByte(0);                 // terminate with zero
media_Flush();                      // we're finished, close the sector

media_SetAdd(0, 1024+5);            // set the starting byte address
while(char:=media_ReadByte()) putch(char);  // print result, starting
                                            // from '5'
repeat forever

Note

Due to design constraints on the PIXXI, there is no way of writing bytes or words within a media sector without starting from the beginning of the sector. All writes will start at the beginning of a sector and are incremental until the media_Flush() function is executed, or the sector address rolls over to the next sector. Any remaining bytes in the sector will be padded with 0xFF, destroying the previous contents. An attempt to use the media_SetAdd(..) function will result in the lower 9 bits being interpreted as zero. If the writing rolls over to the next sector, the media_Flush() function is issued automatically internally.

media_WriteWord

Writes a byte to the current media address that was initially set with media_SetSector(...).

Syntax: media_WriteWord(word_val);

Argument Description
word_val The 16 bit word to be written at the current media address location.

Returns: Non zero if write was successful.

Example

// This example initialises the media, writes some words to the required sector,
// then prints the result from the required location.
var n;
while (media_Init()==0);        // wait until a good SD card is found
n:=0;
media_SetAdd(0, 1536);          // set the starting byte address
while(n++ < 20)
    media_WriteWord(RAND());    // write 20 random words to first 20
wend                            // word locations.
n:=0;
while (n++ < 20)
    media_WriteWord(n++*1000);  // write sequence of 1000*n to next 20
wend                            // word locations.
media_Flush();                  // we're finished, close the sector

media_SetAdd(0, 1536+40);       // set the starting byte address
n:=0;
while(n++<8)                    // print result of fist 8 multiplication calcs
    print([HEX4] media_ReadWord()," n");
wend
repeat forever

Note

Due to design constraints on the PIXXI, there is no way of writing bytes or words within a media sector without starting from the beginning of the sector. All writes will start at the beginning of a sector and are incremental until the media_Flush() function is executed, or the sector address rolls over to the next sector. Any remaining bytes in the sector will be padded with 0xFF, destroying the previous contents. An attempt to use the media_SetAdd(..) function will result in the lower 9 bits being interpreted as zero. If the writing rolls over to the next sector, the media_Flush() function is issued automatically internally.

media_Flush

After writing any data to a sector, media_Flush() should be called to ensure that the current sector that is being written is correctly stored back to the media else write operations may be unpredictable.

Syntax: media_Flush();

Returns: None

Example

See the media_WriteByte(..) and media_WriteWord(..) examples.

media_Image

Displays an image from the media storage at the specified co-ordinates. The image address is previously specified with the media_SetAdd(..) or media_SetSector(...) function. If the image is shown partially off screen, it is necessary to enable clipping for it to be displayed correctly.

Syntax: media_Image(x, y);

Argument Description
x, y specifies the top left position where the image will be displayed.

Returns: None

Example

// This example draws an image at several positions, showing the effects of clipping.
while (media_Init()==0);        // wait if no SD card detected
media_SetAdd(0x0001, 0xDA00);   // point to the books04 image
media_Image(10, 10);
gfx_Clipping(ON);               // turn off clipping to see the difference
media_Image(-12, 50);           // show image off screen to the left
media_Image(50, -12);           // show image o ff screen at the top
repeat forever

Note

It is assumed that the media has been loaded with the example images in GFX2DEMO.GCI loaded at sector 0. This can be loaded using the Graphics Composer (directly onto the memory card).

media_Video

Displays a video clip from the media storage device at the specified co-ordinates. The video address location in the media is previously specified with the media_SetAdd(..) or media_SetSector(...) function. If the video is shown partially off screen, it is necessary to enable clipping for it be displayed correctly. Note that showing a video blocks all other processes until the video has finished showing. See the media_VideoFrame(...) functions for alternatives.

Syntax: media_Video(x, y);

Argument Description
x, y specifies the top left position where the video clip will be displayed.

Returns: None

Example

// This example plays a video clip at several positions, showing the effects of clipping.
while (media_Init()==0);            // wait if no SD card detected
media_SetAdd(0x0001, 0x3C00);       // point to the 10 gear clip
media_Video(10, 10);
gfx_Clipping(ON);                   // turn off clipping to see the difference
media_Video(-12, 50);               // show video off screen to the left
media_Video(50, -12);               // show video off screen at the top
repeat forever

Note

It is assumed that the media has been loaded with the example video in GFX2DEMO.GCI loaded at sector 0. This can be loaded using the Graphics Composer directly onto the memory card.

media_VideoFrame

Displays a video from the media storage device at the specified co-ordinates. The video address is previously specified with the media_SetAdd(..) or media_SetSector(...) function. If the video is shown partially off screen, it is necessary to enable clipping for it be displayed correctly. The frames can be shown in any order. This function gives you great flexibility for showing various icons from an image strip, as well as showing videos while doing other tasks

Syntax: media_VideoFrame(x, y, frameNumber);

Argument Description
x, y specifies the top left position where the video clip will be displayed.
frameBuffer Specifies the required frame to be shown.

Returns: None

Examples

// This example shows how to display frames as required while possibly doing other tasks.
// Note that the frame timing (although not noticeable in this small example) is not correct
// as the delay commences after the image frame is shown, therefore adding the display
// overheads to the frame delay.

var frame;

while (media_Init()==0);        // wait if no SD card detected
media_SetAdd(0x0002, 0x3C00);   // point to the 10 gear image

repeat
    frame := 0;                 // start at frame 0
    repeat
        media_VideoFrame(30,30, frame++);   // display a frame
        pause(peekB(IMAGE_DELAY));          // pause for the time given in
                                            // the image header
    until(frame == peekW(IMG_FRAME_COUNT)); // loop until we've
                                            // shown all the frames
forever                                     // do it forever
// This example employs a timer for the framing delay, and shows the same movie simultaneously
// running forward and backwards with time left for other tasks as well. A number of videos
// (or animated icons) can be shown simultaneously using this method.


var framecount, frame, delay, colr;
frame := 0;
// show the first frame so we can get the video header info
// into the system variables, and then to our local variables.
media_VideoFrame(30,30, 0);

framecount := peekW(IMG_FRAME_COUNT);       // we can now set some local
                                            // values.
delay := peekB(IMAGE_DELAY);                // get the frame count and delay
repeat
    repeat
        pokeW(TIMER0, dela y);              // set a timer
        media_VideoFrame(30,30, frame++);   // show next frame
        gfx_MoveTo(64,35);
        print([DEC2Z] frame);               // print the frame number
        media_VideoFrame(30,80, framecount frame);  // show movie
                                                    // backwards.
        gfx_MoveTo(64,85);
        print([DEC2Z] framecount-frame);    // print the frame number
        if ((frame & 3) == 0)
            gfx_CircleFilled(80,20,2,colr); // a blinking circle fun
            colr := colr ^ 0xF800;          // alternate colour,
        endif                               // BLACK/RED using XOR
        // do more here if required
        while(peekW(TIMER0));               // wait for timer to expire
    until(frame == peekW(IMG_FRAME_COUNT));
    frame := 0;
forever

Note

It is assumed that the media has been loaded with the example video in GFX2DEMO.GCI loaded at sector 0. This can be loaded using the Graphics Composer directly onto the memory card.

Memory Allocation Functions

mem_Alloc

Allocate a block of memory to a pointer. The allocated memory contains garbage but is a fast allocation. The block must later be released with mem_Free(…).

Syntax: mem_Alloc(size);

Argument Description
size Specifies the number of bytes that's allocated from the heap.

Returns: If successful, the return value is the pointer (Word) to the allocation, otherwise null (0).

Example

myvar := mem_Alloc(100);

mem_AllocV

Allocate a block of memory to a pointer. The block of memory is filled with initial signature values. The block starts with A5,5A then fills with incrementing number eg:- A5,5A,00,01,02,03...FF,00,11.... This can be helpful when debugging. The block must later be released with mem_Free(…).

Syntax: mem_AllocV(size);

Argument Description
size Specifies the number of bytes that's allocated from the heap.

Returns: If successful, the return value is the pointer (Word) to the allocation, otherwise null (0).

Example

myvar := mem_AllocV(100);

mem_AllocZ

Allocate a block of memory to pointer myvar. The block of memory is filled with zeros. The block must later be released with mem_Free(…).

Syntax: mem_AllocZ(size);

Argument Description
size Specifies the number of bytes that's allocated from the heap.

Returns: If successful, the return value is the pointer (Word) to the allocation, otherwise null (0).

Example

myvar := mem_AllocZ(100);

mem_Realloc

The function may move the memory block to a new location, in which case the pointer to the new location is returned. The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved. If the new size is larger, the value of the newly allocated portion is indeterminate. In case that ptr is NULL, the function behaves exactly as mem_Alloc(…), assigning a new block of size bytes and returning a pointer to the beginning of it. In case that the size is 0, the memory previously allocated in ptr is deallocated as if a call to mem_Free(…) was made, and a NULL pointer is returned.

Syntax: mem_Realloc(ptr, size);

Argument Description
ptr Specifies the new location to reallocate the memory block.
size Specifies the number of bytes of the block.

Returns: Pointer to the new object location

Example

newptr := mem_Realloc(myptr, 100);

mem_Free

The function de-allocates a block of memory previously created with mem_Alloc(...), mem_AllocV(...) or mem_AllocZ(...).

Syntax: mem_Free(allocation);

Argument Description
allocation Specifies the location of memory block to free up.

Returns: non-zero if function is successful, otherwise 0 if it fails

Example

myvar := mem_Free(buffer);

mem_Heap

Returns byte size of the largest chunk of memory available in the heap.

Syntax: mem_Heap();

Returns: the largest available memory chunk of the heap.

Example

howmuch := mem_Heap();

mem_Set

Fill a block of memory with a byte value.

Syntax: mem_Set(ptr, char, size);

Argument Description
ptr Specifies the memory block.
char Specifies the value to fill the block with.
size Specifies the size of the block in Bytes.

Returns: the pointer

Example

var mybuf[5];
var i;

func main()

mem_Set(mybuf,0x55,5); //Only fills half of mybuf[]
for(i:=0;i<sizeof(mybuf);i++)  //Show what is in the buffer
    print(" 0x",[HEX]mybuf[i]);
next
mem_Set(mybuf,0xAA,sizeof(mybuf)*2); //Fill entire buffer
print("\n"); //New line
for(i:=0;i<sizeof(mybuf);i++)
    print(" 0x",[HEX]mybuf[i]);
next
repeat forever
endfunc

mem_Copy

Copy a block of memory from source to destination.

Syntax: mem_Copy(source, destination, count);

Argument Description
source Specifies the source memory block.
destination Specifies the destination memory block.
count Specifies the size of the blocks.

Returns: source

Example

myptr := mem_Copy(ptr1, ptr2, 100);
// Source can also be a string constant eg: myptr := mem_Copy("TEST STRING", ptr2, 12); 

mem_Compare

Compare two blocks of memory ptr1 and ptr2. The comparison is done alphabetically.

Syntax: mem_Compare(ptr1, ptr2, count);

Argument Description
ptr1 Specifies the 1st memory block.
ptr2 Specifies the 2nd memory block.
count Specifies the number of bytes to compare.

Returns:

  • 0 if we have a match
  • -1 if ptr1 < ptr2
  • +1 if ptr2 > ptr1

Example

test := mem_Compare(this_block, that_block, 100);

Miscellaneous System Functions

sys_PmmC

Prints the system PmmC name and revision, e.g. "PIXXI\n1.0". Can be captured to a buffer using the to() function.

Syntax: sys_PmmC();

Returns: PmmC version

Example

to(myString); sys_PmmC();// save PmmC name and revision to buffer

sys_Driver

Prints the system driver name and date string, eg " pixxiLCD-XXXXX”. Can be captured to a buffer using the to() function.

Syntax: sys_Driver();

Returns: None

Example

to(mystring); sys_Driver();   // save Driver name to buffer

Serial (UART) Communications Functions

setbaud

Use this function to set the required baud rate of COM0. The default Baud Rate for COM0 is 115,200 bits per second or 115,200 baud.

Pre-defined baud rate constants for most common baud rates

Rate / Predefined Constant Error % Actual Baud Rate
BAUD_110 0.00% 110
BAUD_300 0.00% 300
BAUD_600 0.00% 600
BAUD_1200 0.00% 1200
BAUD_2400 0.04% 2401
BAUD_4800 0.04% 4802
BAUD_9600 0.16% 9615
BAUD_14400 0.27% 14439
BAUD_19200 0.38% 19273
BAUD_31250 0.00% 31250
MIDI 0.00% 31250
BAUD_38400 0.83% 38717
BAUD_56000 0.16% 56090
BAUD_57600 1.27% 58333
BAUD_115200 2.64% 118243
BAUD_128000 0.53% 128676
BAUD_256000 0.53% 257353
BAUD_300000 4.17% 312500
BAUD_375000 6.06% 397727
BAUD_500000 9.38% 546875
BAUD_600000 4.17% 625000

Note

Baud rates each have degree of accuracy for several reasons. The actual baud rate you would receive and relevant error% compared to the setting value, can be calculated.

ActualBaud = 4375000/(trunc(4375000/RequiredBaud)) 
Example for 115200 is, 4375000/115200 = 37.977, Trucated is 37. 4375000/37 = 118243 (rounded). 
Error% therefore is % difference between 115200 and 118243, therefore 2.64%

It is desirable to only use a baud rate between 2 devices which has a difference of typically < 2%. Note both devices will have a degree of error, not just this 4D Processor, both need to be considered.

Syntax: setbaud(rate);

Argument Description
rate specifies the baud rate divisor value or pre-defined constant

Returns: None

Example

setbaud(BAUD_19200);      // To set Com0 to 19200 BAUD rate.

com_SetBaud

Use this function to set the required baud rate for the required Com port, COM0 or COM1. Sets to any viable baud rate from 160 to 655350.

The default Baud Rate for COM0 is 115,200 bits per second or 115,200 baud.

There is no default Baud Rate for COM1, setting the baud rate also activates the pins for RX and TX. Note: COM1 only exists on Pixxi-44 in Mode 2 (4-Wire SPI).

Note

  • Baud Rates are not always precise, and an approximate error can be seen from the setbaud() function table on the previous page.
  • Several ‘low’ values have special meanings
    1. 2187500 baud
    2. 1458333 baud
    3. 1093750 baud
    4. 875000 baud
    5. 729167 baud
  • Baud rates each have degree of accuracy for several reasons. The actual baud rate you would receive and relevant error% compared to the setting value, can be calculated.
ActualBaud = 4375000/(trunc(4375000/RequiredBaud)) 
Example for 115200 is, 4375000/115200 = 37.977, Trucated is 37. 4375000/37 = 118243 (rounded). 
Error% therefore is % difference between 115200 and 118243, therefore 2.64% 

It is desirable to only use a baud rate between 2 devices which has a difference of typically < 2%. Note both devices will have a degree of error, not just this 4D Processor, both need to be considered.

Syntax: com_SetBaud(comport, baudrate/10);

Argument Description
comport Com port, COM0 or COM1.
baudrate/10 Specifies the baud rate.

Returns: True if BAUD rate was acceptable.

Example

var stat;
stat := com_SetBaud(COM0, 960);      // To set Com0 to 9600 BAUD rate.
if (stat)
    print("Com0 set to 9600 BAUD");
endif

com_Mode(Databits, parity, Stopbits, comport)

Use this function to set the required serial port parameters to other than 8N1.

Syntax: com_Mode(Databits, parity, Stopbits, comport);

Argument Description
Databits Specifies the number of databits, 8 is the only currently valid value
parity Specifies the parity bit. Valid values are N(one), E(ven) and O(dd).
Stopbits Specifies the number of stop bits. Valid values are 1 and 2.
comport Com port, COM0 or COM1.

Returns: True if the parameters were acceptable.

Example

stat := com_ Mode(8, 'E', 2, COM0 ) // To set Com 0 to 8E2
if (stat)
    Print("Com 2 set to 8E2");
endif

serin

Receives a character from the Serial Port COM0. The transmission format is: No Parity, 1 Stop Bit, 8 Data Bits (N,8,1). The default Baud Rate is 115,200 bits per second or 115,200 baud. The baud rate can be changed under program control by using the setbaud(...) function.

Syntax: serin();

Returns:

  • -1 if no character is available
  • -2 if a framing error or over-run has occurred (auto cleared)
  • 0 or a positive value (up to 255) for a valid character received

Example

var char;
char := serin();            // test the com port
if (char >= 0)              // if a valid character is received
    process(char);          // process the character
endif

serout

Transmits a single byte from the Serial Port COM0. The transmission format is: No Parity, 1 Stop Bit, 8 Data Bits (N,8,1). The default Baud Rate is 115,200 bits per second or 115,200 baud. The baud rate can be changed under program control by using the setbaud(...) function.

Syntax: serout(char);

Argument Description
char specifies the data byte to be sent to the serial port.

Returns: None

Example

serout('\n');       \\Send a linefeed to COM0.

com_Init

This is the initialisation function for the serial communications buffered service. Once initialised, the service runs in the background capturing and buffering serial data without the user application having to constantly poll the serial port. This frees up the application to service other tasks.

MODES OF OPERATION

No qualifier – simple ring buffer (aka circular queue)

If the qualifier is set to zero, the buffer is continually active as a simple circular queue. Characters when received from the host are placed in the circular queue (at the 'head' of the queue) Bytes may be removed from the circular queue (from the 'tail' of the queue) using the serin() function. If the tail is the same position as the head, there are no bytes in the queue, therefore serin() will return -1, meaning no character is available, also, the com_Count() function can be read at any time to determine the number of characters that are waiting between the tail and head of the queue. If the queue is not read frequently by the application, and characters are still being sent by the host, the head will eventually catch up with the tail setting the internal COM_FULL flag (which can be read with the com_Full() function) . Any further characters from the host are are now discarded, however, all the characters that were buffered up to this point are readable. This is a good way of reading a fixed size packet and not necessarily considered to be an error condition. If no characters are removed from the buffer until the COM_FULL flag (which can be read with the com_Full() function) becomes set, it is guaranteed that the bytes will be ordered in the buffer from the start position, therefore, the buffer can be treated as an array and can be read directly without using serin() at all. In the latter case, the correct action is to process the data from the buffer, re-initialise the buffer with the com_Init(..) function, or reset the buffered serial service by issuing the com_Reset() function (which will return serial reception to polled mode) , and send an acknowledgement to the host (traditionally a ACK or 6) to indicate that the application is ready to receive more data and the previous 'packet' has been dealt with, or conversely, the application may send a negative acknowledgement to indicate that some sort of error occurred, or the action could not be completed (traditionally a NAK or 16) .

If any low level errors occur during the buffering service (such as framing or over-run) the internal COM_ERROR flag will be set (which can be read with the com_Error() function).

Note

The COM_FULL flag will remain latched to indicate that the buffer did become full, and is not reset (even if all the characters are read) until the com_Init(..) or com_Reset() function is issued.

Using a qualifier

If a qualifier character is specified, after the buffer is initialised with com_Init(..) , the service will ignore all characters until the qualifier is received and only then initiate the buffer write sequence with incoming data. After that point, the behaviour is the same as above for the 'non qualified' mode.

Syntax: com_Init(buffer, bufsize, qualifier);

Argument Description
buffer Specifies the address of a buffer used for the background buffering service.
bufsize Specifies the byte size of the user array provided for the buffer (each array element holds 2 bytes). If the buffer size is zero, a buffer of 128 words (256 bytes) should be provided for automatic packet length mode (see below).
qualifier Specifies the qualifying character that must be received to initiate serial data reception and buffer write. A zero (0x00) indicates no qualifier to be used.

Returns: None

Examples

com_Init(combuf, 20, 0 );
// set up a comms ring buffer, maximum 12 characters before overflow

com_Reset

Resets the serial communications buffered service and returns it to the default polled mode.

Syntax: com_Reset();

Returns: None

Examples

com_Reset(); // reset to polled mode

com_Count

This function can be read at any time (when in buffered communications is active) to determine the number of characters that are waiting in the buffer.

Syntax: com_Count();

Returns: Current count of characters in the communications buffer.

Examples

n := com_Count(); // get the number of chars available in the buffer

com_Full

If the queue is not read frequently by the application, and characters are still being sent by the host, the head will eventually catch up with the tail setting the COM_FULL flag which is read with this function. If this flag is set, any further characters from the host are discarded, however, all the characters that were buffered up to this point are readable.

Syntax: com_Full();

Returns: 1 if buffer or queue has become full, or is overflowed, else returns 0.

Examples

if(com_Full() & (com_Count() == 0)) 
   com_Init(mybuf, 30, 0);  // buffer full, recovery
endif

com_Error

If any low level errors occur during the buffering service (such as framing or over-run) the internal COM_ERROR flag will be set which can be read with this function.

Syntax: com_Error();

Returns: non-zero if any low level communications error occurred

  • bit0 = Receiver Overflow Error
  • bit1 = Receiver Framing Error
  • bit2 = Parity Error Overflow
  • bit7 = Attempt to transmit when transmit is buffered and held

Examples

if(com_Error())       // if there were low level comms errors,
    resetMySystem();  // take corrective action
endif

com_Sync

If a qualifier character is specified when using buffered communications, after the buffer is initialized with com_Init(..) , the service will ignore all characters until the qualifier is received and only then initiate the buffer write sequence with incoming data. The com_Sync() function is called to determine if the qualifier character has been received yet.

Syntax: com_Sync();

Returns: 1 if the qualifier character has been received, else returns 0.

Examples

com_Sync(); // reset to polled mode

com_TXbuffer

Initialise a serial buffer for the COM0 or COM1 output.

The program must declare a var array as a circular buffer. When a TX buffer is declared for comms, the transmission of characters becomes non-blocking. The only time blocking will occur is if the buffer has insufficient space to accept the next character, in which case the function will wait for buffer space to become available. If the TX buffer is no longer required, just set the buffer pointer to zero, the size in this case doesn’t matter and is ignored. The function can resize or reallocated to another buffer at any time. The buffer is flushed before any changes are made.

"pin" designates an IO pin to control a bi-directional control device for half duplex mode. "pin" will go HI at the start of a transmission, and will return low after the final byte is transmitted.

Once the buffer has been initialised you just continue to use serout() in the usual way, no other programming changes are required.

Syntax: com_TXbuffer(buf, bufsize, pin);

Argument Description
buf Specifies the address of a buffer used for the buffering service.
bufsize Specifies the byte size of the user array provided for the buffer (each array element holds 2 bytes).
pin Specifies the turnaround pin. If not required, just set "pin" to zero.

Returns: None

Examples

com_TXbuffer(mybuf, 1024, IO1_PIN);       // set the TX buffer
com_TXbuffer(0, 0, 0);              // revert to non buffered service

com_TXbufferHold

This function is used in conjunction with com_TXbuffer(...);. It is often necessary to hold off sending serial characters until a complete frame or packet has been built in the output buffer. com_TXbufferHold(ON) is used for this, to stop the buffer being sent while it is being loaded. Normally, when using buffered comms, the transmit process will begin immediately. This is fine unless you are trying to assemble a packet.

To build a packet and send it later, issue a com_TXbufferHold(ON);, build the packet, when packet is ready, issuing com_TXbufferHold(OFF); will release the buffer to the com port.

Also, if using com_TXemptyEvent, erroneous empty events will occur as the transmit buffer is constantly trying to empty while you are busy trying to fill it.

Also refer to the pin control for com_TXbuffer(...); function.

Note

If you fill the buffer whilst it is held comms error 4 will be set and the data written will be lost.

Syntax: com_TXbufferHold(state);

Argument Description
state Specifies the state of the buffer used for the buffering service.

Returns:

  • Buffer count when called with argument of 1, for example com_TXbufferHold(ON)
  • 0 when argument is zero, eg com_TXbufferHold(OFF)

Examples

Refer to the com_TXemptyEvent example.

com_TXcount

Return count of characters remaining in COM0 or COM1 transmit buffer that was previously allocated with com_TXbuffer(...) or com1_TXbuffer(...).

Syntax: com_TXcount();

Returns: count of characters

Examples

arg := com1_TXCount(); //return count of characters in COM1 TX buffer

com_TXemptyEvent

If a comms TX buffer that was previously allocated with com_TXbuffer(...); or com1_TXbuffer(...);, this function can be used to set up a function to be called when the COM0 or COM1 TX buffer is empty. This is useful for either reloading the TX buffer, setting or clearing a pin to change the direction of eg a RS485 line driver, or any other form of traffic control. The event function must not have any parameters. To disable the event, simply call com_TXemptyEvent(0) or com1_TXemptyEvent(0). com_TXbuffer(...); or com1_TXbuffer(...); also resets any active event.

Syntax: com_TXemptyEvent(function);

Argument Description
functionAddress Address of the event Function to be queued when COM TX buffer empty.

Returns: any previous event function address, or zero if there was no previous function.

Examples

/*************************************************
* Description: buffered TX service
* Use terminal at 9600 baud to see result
* Example of Buffered TX service vs Non buffered
* Also explains the use of COMMS events
*
* NB Program must be written to flash so
* the Terminal can be used.
*
**************************************************/

var combuf[220];  // buffer for up to 440 bytes

// run a timer event while we are doing comms
func T7Service()
   var private colour := 0xF800;
   colour ^= 0xF800;
   gfx_RectangleFilled(50,200,80,220,colour);
   sys_SetTimer(TIMER7, 200);
endfunc

// event to capture the buffer empty event
func bufEmpty()
   com_TXbuffer(0, 0, IO1_PIN);   // done with the buffer, release it
   print("\n\nHELLO WORLD, I'M EMPTY ",com_TXcount(),"\n");
endfunc
func main()
    var n, r, D, fh;

    sys_SetTimerEvent(TIMER7,T7Service);      // run a timer event
    sys_SetTimer(TIMER7, 150);
    com_TXemptyEvent(bufEmpty); // set to capture  buffer empty event

    setbaud(BAUD_9600);

    txt_Set(TEXT_OPACITY, OPAQUE);

repeat

    gfx_Cls();

    txt_MoveCursor(3,1);        // reset cursor to line 3, column 2
    print("Send 440 chars non-buffered\n");
    pokeW(SYSTEM_TIMER_LO, 0);  // reset timer

    // note that 440 chars at 9600 baud takes approx 453msec
    for(n:=0; n<10; n++)
        to(COM0); putstr("The quick brown fox jumps over the lazy dog\n"); // 44 chars
    next

    print("took ",peekW(SYSTEM_TIMER_LO),"Msec\n\n"); 
    // time spent blocking is only approx 1msec

    com_TXbuffer(combuf, 440,IO1_PIN);// set up the TX buffer
    com_TXbufferHold(ON);             // hold the TX buffer til ready


    // note that here the time is only approx 1msec overhead due to buffering.
    print("Send 440 chars buffered\n");
    pokeW(SYSTEM_TIMER_LO, 0);        // reset timer

    for(n:=0; n<10; n++)
        to(COM0); putstr("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\n"); // 44 chars
    next

    print("took ",peekW(SYSTEM_TIMER_LO),"Msec\n\n");           
    // time spent blocking is only approx 1msec

    // demonstrate how to modify a prepared comms buffer that is   
    // still being held
    to(combuf); print("MY CONTENTS HAVE BEEN CHANGED");
    to(combuf+50); print("*** AND CHANGED HERE TOO ***");
    combuf[218] := 'CA';    // the last 'DOG' changed here
    combuf[219] := 'T\n';    // the last 'DOG' changed here

    // now we are ready to send to buffer
    n := com_TXbufferHold(OFF);   // release TX buffer
    print("TXBuffer is holding ", n, " chars\n");
    // show how many characters were in the buffer


    // watch the buffer empty
    repeat
        print("TX count = ", [DEC5ZB] n := com_TXcount(),"\r");  // watch the count as the buffer empties
    until(!n);

com_InitBrk

This is the initialisation function for the serial communications buffered service with the ability to receive the BREAK signal as though it is a character. The parameters are identical to com_Init() except that each buffer entry can now only hold one byte. The BREAK ‘character’ is is a predefined constant call BREAK.

Syntax: com_InitBrk(buffer, bufsize, qualifier);

Argument Description
buffer Specifies the address of a buffer used for the background buffering service.
bufsize Specifies the byte size of the user array provided for the buffer (each array element holds 1 byte). If the buffer size is zero, a buffer of 128 words (256 bytes) should be provided for automatic packet length mode (see below).
qualifier Specifies the qualifying character that must be received to initiate serial data reception and buffer write. A zero (0x00) indicates no qualifier to be used.

Returns: None

Examples

com_InitBrk(combuf, 20, 0 );       
//set up a comms ring buffer for COM0, 10 characters before overflow

com_TXbufferBrk

This is the initialisation function for the serial communications tramsmit buffered service with the ability to sent the BREAK signal as though it is a character. The parameters are identical to com_TXbuffer() except that each buffer entry can now only hold one byte. The BREAK ‘character’ is is a predefined constant call BREAK.

Syntax: com_TXbufferBrk(buf, buffsize, pin);

Argument Description
buf Specifies the address of a buffer used for the buffering service.
bufsize Specifies the byte size of the user array provided for the buffer (each array element holds 1 byte).
pin Specifies the turnaround pin. If not required, just set "pin" to zero.

Returns: None

Examples

com_TXbufferBrk(mybuf, 1024, PA1); // set the TX buffer of COM0
com_TXbufferBrk(0, 0, 0);          // revert COM0 to non buffered service

Sound Control Functions

snd_Volume

Set the sound playback volume. Var must be in the range from 8 (min volume) to 127 (max volume). If var is less than 8, volume is set to 8, and if var > 127 it is set to 127.

Syntax: snd_Volume(var);

Argument Description
var Sound playback volume

Returns: None

Examples

snd_Volume(127) ; // Set Volume to maximum 

snd_Pitch

Sets the samples playback rate to a different frequency. Setting pitch to zero restores the original sample rate.

Syntax: snd_Pitch(pitch);

Argument Description
pitch Sample's playback rate. Minimum is 4KHz. Range is, 4000 – 65535.

Returns: sample's original sample rate.

Examples

snd_Pitch(7000); //Play the wav file with a sample frequency of 7KHz.  

snd_BufSize

Specify the memory chunk size for the wavefile buffer, default size 1024 bytes. Depending on the sample size, memory constraints, and the sample quality, it may be beneficial to change the buffer size from the default size of 1024 bytes. This function is for control of a wav buffer, see the file_PlayWAV() function.

Syntax: snd_BufSize(var);

Argument Description
var Specifies the buffer size.
0 = 1024 bytes (default)
1 = 2048 bytes
2 = 4096 bytes

Returns: None

Examples

snd_BufSize(1);// allocate a 2k wav buffer   

snd_Stop

Stop any sound that is currently playing, releasing buffers and closing any open wav file. This function is for control of a wav buffer, see the file_PlayWAV() function.

Syntax: snd_Stop();

Returns: None

Examples

snd_Stop(); 

snd_Pause

Pause any sound that is currently playing. This function is for control of a wav buffer, see the file_PlayWAV() function.

Syntax: snd_Pause();

Returns: None

Examples

snd_Pause(); 

snd_Continue

Resume any sound that is currently paused by snd_Pause. This function is for control of a wav buffer, see the file_PlayWAV() function.

Syntax: snd_Continue();

Returns: None

Examples

snd_Continue(); 

snd_Playing

Returns 0 if sound has finished playing, else return number of 512 byte blocks to go. This function is for control of a wav buffer, see the file_PlayWAV() function.

Syntax: snd_Playing();

Returns: Number of 512 byte blocks to go.

Examples

count := snd_Playing(); 

snd_Freq

Produces a pure square wave waveform. This command is designed to drive Piezo transducers which require this sort of input. It can be used directly with high impedance speakers. Whilst it also works on displays with a built-in amplifier the sound produced is extremely annoying.

Syntax: snd_Freq(freq, duration);

Argument Description
freq The frequency of the sound to produce, 20Hz is the minimum.
duration The duration of the sound in milliseconds.

Returns: 0 if note cannot be played because a frequency is playing, else returns True.

Examples

snd_Freq(2731, 100); // produce a 100ms burst at the Piezo’s resonant frequency. 

snd_RTTTL

This function uses the "Ring Tone Text Transfer Language" (RTTTL) developed by Nokia for cellphone ring tones. There are certain differences that need to be taken into account, and several additions that will be described later. It is recommended to check the original format first, with the suggested reference located at: http://en.wikipedia.org/wiki/Ring_Tone_Transfer_Language

With little practice and minor modifications, most RTTTL tunes that can be downloaded off the web are playable with this function. Also, a wide range of sound effects can be made using standard RTTTL notation augmented with the additional 4DGL functions.

Syntax: snd_RTTTL(tunePtr);

Argument Description
tunePtr Specifies a pointer to a data statement or a string constant containing RTTTL information.

Note

The argument passed to the snd_RTTTL (...) function must be an ASCII string. If the string is passed as a pointer from a #DATA statement, it must be terminated with a zero (0x00). If a string is passed directly as a parameter, the '0' is automatically appended by the compiler as per normal strings.

Returns: None

Examples

/*
This example shows how to use the RTTTL tunes to  
generate complex sounds and music.
*/

//------------------------------------------------------------------- 
#DATA
   // b=250
   byte Muppets   "d=4,o=5,b=15,",
                  "c6,c6,a,b,8a,b,g,p,c6,c6,a,8b,8a,8p,g.,p,e,e,g,f,
                   8e,f,8c6,8c,8d,e,8e,8e,8p,8e,g,2p,c6,",
                  "c6,a,b,8a,b,g,p,c6,c6,a,8b,a,g.,p,e,e,g,f,8e,f,
                   8c6,8c,8d,e,8e,d,8d,c",0

   // part of haunted house theme
   byte HauntedHouse  "d=4,o=5,b=20,",
                      "2a4,2e,2d#,2b4,2a4,2c,2d,2a#4,2e.,e,1f4,1a4,
                       1d#,2e.,d,2c.,b4,1a4", 0

   // simple scale with default settings
   byte SimpleScale   "c,d,e,f,g,a,b,c7", 0

   // simple scale with default settings and portamento use.
   // Note the portamento speed change in the middle of the string,
   // and the curly braces that turn the portamento on and off.
   byte SimpleScaleP   "b=50,{,c,d,e,f,p=7,g,a,},b,c7", 0

   // simple scale, much faster
   // note b=20 as default, so each note plays for 20msec when d=64
   byte Scale2        "d=64,c,d,e,f,g,a,b,c7", 0

   // simple scale, much faster - with a repeat command set to 20
   // note b=20 as default, so each note plays for 20msec when d=64,
   // and we repeat 20 times
   byte ScaleRep      "d=64,r=20,c,d,e,f,g,a,b,c7,R", 0

   // simple scale, at the fastest possible rate, repeat 200 times
   // note that b=1 and d=64 so each note plays for only 1msec
   byte ScaleRep2     "b=1,d=64,r=200,c,d,e,f,g,a,b,c7,R", 0

   // simple scale using appregiation to increment the note step
   // note that commas can be left out to save space if there is no
   // indecision about delimit value 
   byte ApprScale   "a=1,c,+++++++++++------------", 0

   // scale using appregiation to increment the note step, and the
   // note step is larger
   // note that commas can be left out to save space if there is no
   // indecision about delimit value 
   byte ApprScaleF   "d=8,a=4,c,++++++++++++------------", 0

   // same as above but demonstrates repeating instead of multiple
   // inc/dec operators
   // note that commas can be left out to save space if there is no
   // indecision about delimit value 
   byte ApprScaleFR   "d=8,a=4,c5,r=11,+,R,r=11,-,R", 0

   // you can build your own scale sequencers
   byte COMPLEX_C         "d=64,a=5,c4,r=8,+,R", 0
   byte COMPLEX_DSHARP    "d=64,a=5,d#4,r=8,+,R", 0
   byte COMPLEX_G         "d=64,a=5,g4,r=8,+,R", 0

   // just having a bit of fun
   byte DEMO     "a=3,p=3,o=5,d=4,b=5, 
                 {,a,r=20,+,R,},c,d=16,a=5,r=50,-,R, R",0  // forever
#END
//-------------------------------------------------------------------

#constant number_of_examples 13
var examples[number_of_examples];
var names[number_of_examples];

//-------------------------------------------------------------------
func main()
   var n;

    pin_Set(SOUND, IO1_PIN);          // sound on default pin
   // pin_Set(SOUND, IO2_PIN);

   // lookup table for the examples
   examples[0] := HauntedHouse;
   examples[1] := SimpleScale;
   examples[2] := SimpleScaleP;
   examples[3] := Scale2;
   examples[4] := ScaleRep;
   examples[5] := ScaleRep2;

SPI Control Functions

The SPI functions in this section apply to any general-purpose SPI device. To be used only when the uSD card is not active.

spi_Init

Sets up the PIXXI-GFX2 SPI port to communicate with SPI devices.

SPI Mode Arguments

Syntax: spi_Init(speed, input_mode, output_mode);

Argument Description
speed Sets the speed of the SPI port.
input_mode Sets the input mode of the SPI port.
output_mode Sets the output mode of the SPI port.

Returns: None

Note

  • The SPI functions in this section are not necessary when using the memory card or serial flash chips interfaced to the SPI port.
  • The SPI functions in this section are relevant to those devices other than the memory card and the serial flash chip used for media access. This is relevant in cases where Flash Memory or uSD card is not present, and the SPI port on PIXXI is used for another SPI device.

Example

spi_Init(SPI_FAST,RXMODE_0,CKMODE_0);

spi_Read

This function allows a raw unadorned byte read from the SPI device.

Syntax: spi_Read();

Returns: Returns a single data byte from the SPI device.

Example

var result;
spi_Init(SPI_SPEED0, RXMODE_0, CKMODE_0);
print("Hello World\n") ; // replace with your code
//...
spi_Write(0x40); // x_Accel Request
result := spi_Read();
print("result: ", result);

Note

The Chip Select line (SDCS) is lowered automatically.

spi_Write

This function allows a raw unadorned byte write to the SPI device.

Syntax: spi_Write(byte);

Argument Descrption
byte specifies the data byte to be sent to the SPI device.

Returns: None

Example: See the example in section spi_Read().

Note

The Chip Select line (SDCS) is lowered automatically.

spi_Disable

This function raises the Chip Select (SDCS) line of the SPI device, disabling it from further activity. The CS line will be automatically lowered next time the SPI functions spi_Read() or spi_Write(...) are used, and also by action of any of the media_ functions.

Syntax: spi_Disable();

Returns: None

String Class Functions

str_Ptr

Return a byte pointer to a word region.

Syntax: str_Ptr(&var);

Argument Descrption
&var Pointer to string buffer.

Returns: the byte pointer to string buffer.

Example:

var buffer[100]; // 200 character buffer for a source string
var p; // string pointer
var n;
var vars[3]; // for our results

func main()
    to(buffer); print("0x1234 0b10011001 12345 abacus");
    p := str_Ptr(buffer);//raise string pointer for the string functions
    while(str_GetW(&p, &vars[n++]) != 0); // read all the numbers till we
    //get a non number
    print(vars[0],"\n", vars[1],"\n", vars[2],"\n"); // print them out
endfunc

str_GetD

Convert number in a string to DWORD (myvar[2]).

Syntax: str_GetD(&ptr, &var);

Argument Descrption
&ptr Byte pointer to string
&var Destination for result

Returns: TRUE if function succeeds, advancing ptr

Example:

var buffer[100]; // 200 character buffer for a source string
var p; // string pointer
var n;
var vars[6]; // for our results

func main()
    to(buffer); print("100000 200000 98765432 abacus");
    p := str_Ptr(buffer); // raise a string pointer so we can use the
    // string functions
    while(str_GetD(&p, &vars[n]) != 0) n:=n+2; //read all the numbers
    //till we get a non number
    print( [HEX4] vars[1], ":" , [HEX4] vars[0], "\n" );
    // show the longs as hex numbers
    print( [HEX4] vars[3], ":" , [HEX4] vars[2], "\n" );
    print( [HEX4] vars[5], ":" , [HEX4] vars[4], "\n" );
endfunc

Note

The address of the pointer must be passed so the function can advance it if required.

str_GetW

Convert number in a string to WORD (myvar).

Syntax: str_GetW(&ptr, &var);

Argument Descrption
&ptr Byte pointer to string
&var Destination for result

Returns: TRUE if function succeeds, advancing ptr.

Example:

var buffer[100]; // 200 character buffer for a source string
var p; // string pointer
var n;
var vars[3]; // for our results

func main()
    to(buffer); print("0x1234 0b10011001 12345 abacus");
    p := str_Ptr(buffer); // raise a string pointer so we can use the
    // string functions
    while(str_GetW(&p, &vars[n++]) != 0); // read all the numbers till
    // we get a non number
    print(vars[0],"\n", vars[1],"\n", vars[2],"\n"); // print them out
    str_Printf (&p, "%s\n" ); // numbers extracted, now just print
    // remainder of string
endfunc

Note

The address of the pointer must be passed so the function can advance it if required.

str_GetHexW

Convert hex number in a string to WORD (myvar). This function is for extracting 'raw' hex words with no "0x" prefix.

Syntax: str_GetHexW(&ptr, &var);

Argument Descrption
&ptr Byte pointer to string
&var Destination for result

Returns: TRUE if function succeeds, advancing ptr.

Example:

var buffer[100]; // 200 character buffer for a source string
var p; // string pointer
var n;
var vars[4]; // for our results

func main()
    to(buffer); print("1234 5678 9 ABCD");
    p := str_Ptr(buffer); // raise a string pointer so we can use the
    // string functions
    while(str_GetHexW(&p, &vars[n++]) != 0);// read all the hex numbers
    // till we get a non number
    print(vars[0],"\n", vars[1],"\n" , vars[2],"\n", vars[3],"\n");
endfunc

Note

The address of the pointer must be passed so the function can advance it if required.

str_GetC

Get next valid ascii char in a string to myvar. The function returns 0 if end of string reached. Used for extracting single characters from a string.

Syntax: str_GetC(&ptr, &var);

Argument Descrption
&ptr Byte pointer to string
&var Destination for our result

Returns: TRUE if function succeeds, advancing ptr.

Example:

var p; // string pointer
var n;
var char;
var buffer[100]; // 200 character buffer for a source string

func main()
    to(buffer); print("Quick Brown Fox");
    p := str_Ptr(buffer); // raise a string pointer so we can use the
    //string functions
    while(str_GetC(&p, &char))
        print("p=",p," char is", [CHR] char); // print characters
    wend
    print("End of string");
endfunc

Note

The address of the pointer must be passed so the function can advance it if required.

str_GetByte

Get a byte to myvar. Similar to "PEEKB" in basic. It is not necessary for byte pointer ptr to be word aligned.

Syntax: str_GetByte(ptr);

Argument Descrption
&ptr Address of byte array or string

Returns: the byte value at pointer location.

Example:

var buffer[100]; // 200 character buffer for a source string
var n, p;

func main()
    to(buffer); print("Testing 1 2 3");
    p := str_Ptr(buffer); // get a byte pointer from a word region
    n := 0;
    while (n <= str_Length(buffer))
        print( [HEX2] str_GetByte(p + n++)," ");// print all the chars hex
        // values
    wend
endfunc

str_GetWord

Get a word to myvar. Similar to "PEEKW" in basic. It is not necessary for byte pointer ptr to be word aligned.

Syntax: str_GetWord(ptr);

Argument Descrption
&ptr Byte pointer

Returns: the word at pointer location.

Example:

var p; // string pointer
var buffer[10]; // array for 20 bytes

func main()
    p := str_Ptr (buffer); // raise a string pointer
    str_PutWord (p+3, 100); // 'poke' the array
    str_PutWord (p+9, 200);
    str_PutWord (p+12, 400);
    print( str_GetWord( p + 3), "\n" ); // 'peek' the array
    print( str_GetWord( p + 9), "\n" );
    print( str_GetWord( p + 12), "\n" );
endfunc

str_PutByte

Put a byte value into a string buffer at ptr. Similar to "POKEB" in basic. It is not necessary for byte pointer ptr to be word aligned.

Syntax: str_PutByte(ptr, val);

Argument Descrption
ptr Byte pointer to string
val Byte value to insert

Returns: None

Example:

var buffer[100];          // 200 character buffer for a source string
var p;                    // string pointer

func main()

p := str_Ptr(buffer);     // raise a string pointer so we can use the 
                          // string functions
str_PutByte(p + 3, 'A');  // store some values
str_PutByte(p + 4, 'B');  // store some values
str_PutByte(p + 5, 'C');  // store some values
str_PutByte(p + 7, 'D');  // store some values
str_PutByte(p + 7,  0);   // string terminator 
fprint(vars[0],"\n", vars[1],"\n", vars[2],"\n");  // print them out

p := p + 3;               // offset to where we placed the chars
fprint(&p, "%s\n" );      // print the result

// nb, also, understand that the core print service
// assumes a word aligned address so it starts at pos 4
// print( [STR] &buffer[2]); 

endfunc 

str_PutWord

Put a word value into a byte buffer at ptr, similar to "POKEW" in basic. It is not necessary for byte pointer ptr to be word aligned.

Syntax: str_PutWord(ptr, val);

Argument Descrption
ptr Byte pointer to string
val Value to store

Returns: None

Example:

var p;                       // string pointer
var numbers[10];             // array for 20 bytes
func main()

    p := str_Ptr (numbers);  // raise a string pointer

    str_PutWord (p+3, 100);  // 'poke' the array with some numbers
    str_PutWord (p+9, 200);
    str_PutWord (p+12, 400);

    print( str_GetWord( p + 3), "\n" );   // 'peek' the array
    print( str_GetWord( p + 9), "\n" );  
    print( str_GetWord( p + 12), "\n" );  

endfunc 

str_Match

Case Sensitive match. Compares the string at position ptr in a string buffer to the string str, skipping over any leading spaces if required. If a match occurs, ptr is advanced to the first position past the match, else ptr is not altered.

Syntax: str_Match(&ptr, *str);

Argument Descrption
ptr Address of byte pointer to string buffer
str Pointer string to match

Returns: 0 if no match, else advance ptr to the next position after the match and returns a pointer to the match position.

Example:

var buffer[100]; // 200 character buffer for a source string
var p, q; // string pointers
var n;

func main()

    to(buffer); print( " volts 240 " );   // string to parse
    p := str_Ptr(buffer);              // string pointer to be used
                                       // with string functions
    q := p;
    // match the start of the string with "volts"
    if ( n := str_Match( &p, "volts" ) )    
        str_Printf ( &p, "%s\n" );  // print remainder of string
    else
        print ( "not found\n" );
    endif
    print ( "startpos=" , q , "\nfindpos=" , n , "\nendpos=" , p );

    repeat
    forever
endfunc

Note

The address of the pointer must be passed so the function can advance it if required.

str_MatchI

Case Insensitive match. Compares the string at position ptr in a string buffer to the string str, skipping over any leading spaces if required. If a match occurs, ptr is advanced to the first position past the match, else ptr is not altered.

Syntax: str_MatchI(&ptr, *str);

Argument Descrption
ptr Address of byte pointer to string buffer
str Pointer string to match

Returns: 0 if no match, else advance ptr to the next position after the match and returns a pointer to the match position.

Example:

var buffer[100]; // 200 character buffer for a source string
var p, q; // string pointers
var n;

func main()
    // string to parse
    to(buffer); print( "The sun rises in the East" );   
    p := str_Ptr(buffer);           // string pointer to be used
                                    // with string functions
    q := p;
    // Will match if the string starts with "The", or "the"
    if ( n := str_MatchI( &p, "the" ) )                 
        str_Printf ( &p, "%s\n" );    // print remainder of string
    else
        print ( "not found\n" );
    endif
    print ( "startpos=" , q , "\nfindpos=" , n , "\nendpos=" , p );
    repeat
    forever
endfunc

Note

The address of the pointer must be passed so the function can advance it if required.

str_Find

Case Sensitive. Searches for string str in string buffer pointed to by ptr.

Syntax: str_Find(&ptr, *str);

Argument Descrption
ptr Byte pointer to string buffer
str String to find

Returns: 0 if not found, otherwise, the position of the find if successful.

Example:

var buffer[100]; // 200 character buffer for a source string
var p; // string pointer
var n;
var strings[4]; // for our test strings

func main()
    txt_Set ( FONT_ID, FONT2 );
    strings[0] := "useful" ;
    strings[1] := "string" ;
    strings[2] := "way" ;
    strings[3] := "class" ;
    to(buffer); print ( "and by the way, the string class is rather 
useful " );
    // raise a string pointer so we can use the string functions
    p := str_Ptr(buffer); 
    // offset into the buffer a little so we don't see word "way"
    p := p + 13; 
    print( "p=" , p , "\n\n" ); // show the start point of our search
    n := 0;
    while ( n < 4 )
        print( "\"" , [STR] strings[n] , "\" is at pos " , str_Find( &p 
, strings[n++] ) , "\n" );
    wend
    //note that p is unchanged
    print ( "\nNOTE: p is unchanged, p=" , p );
    repeat
    forever
endfunc

Note

The pointer ptr is not altered.

str_FindI

Case Sensitive. Searches for string str in string buffer pointed to by ptr.

Syntax: str_FindI(&ptr, *str);

Argument Descrption
ptr Byte pointer to string buffer
str String to find

Returns: 0 if not found, otherwise, the position of the find if successful.

Example:

var buffer[100]; // 200 character buffer for a source string
var p; // string pointer
var n;
var strings[4]; // for our test strings

func main()
    txt_Set ( FONT_ID, FONT2 );
    strings[0] := "USEFUL" ;
    strings[1] := "string" ;
    strings[2] := "way" ;
    strings[3] := "class" ;
    to(buffer); print ( "and by the way, the String Class is rather 
useful " );
    // raise a string pointer so we can use the string functions
    p := str_Ptr(buffer);           
    // offset into the buffer a little so we don't see word "way"
    p := p + 13;                    
    // show the start point of our search
    print( "p=" , p , "\n\n" );     
    n := 0;
    while ( n < 4 )
        print( "\"" , [STR] strings[n] , "\" is at pos " , str_FindI ( 
&p , strings[n++] ) , "\n" );
    wend
    //note that p is unchanged
    print ( "\nNOTE: p is unchanged, p=" , p ); 
    repeat
    forever
endfunc

Note

The pointer ptr is not altered.

str_Length

Returns the length of a string excluding terminator.

Syntax: str_Length(ptr);

Argument Descrption
ptr pointer to string buffer

Returns: string length

Example:

var a;
var b;
var c[40];    // 80 character buffer for a source string
var pa, pc;   //These will be String pointers to a and c[]

func main()

a := mem_Alloc( 200 ); // allocate a dynamic buffer full of random data
mem_Set (a, 'X', 200 );    // fill it full of 'X's 
pa := str_Ptr(a);          // raise a string pointer
str_PutByte(pa+20,0);      //Now stick a string terminator in the array 
                           //Change the 20 to be between 0 and 199
b := "A string constant" ; // b is a pointer to a string constant

to (c);  print ( "An 'ASCIIZ' string is terminated with a zero" ); 
pc := str_Ptr(c);          // raise a string pointer so we can use the
                           // string functions 
print ("a length:", str_Length(pa), "\n");  // show length of the
                                            // dynamic buffer
print ("b length:", str_Length(b),  "\n");  // show length of the
                                            // static string 
print ("c length:", str_Length(pc), "\n");  // show length of the
                                            // 're-directed' string 
mem_Free (a);    // test is over, free up the memory
repeat
forever
endfunc 

str_Printf

This function prints a formatted string from elements derived from a structured byte region. There is only one input argument, the byte region pointer ptr which is automatically advanced as the format specifier string is processed. The format string is similar to the C language, however, there are a few differences, including the addition of the indirection token * (asterix).

Syntax: str_Printf(&ptr, *format);

Argument Descrption
ptr Byte pointer to the input data (structure).
format Format string.

Format Specifiers:
%c - character
%s - string of characters
%d - signed decimal
%ld - long decimal
%u - unsigned decimal
%lu - long unsigned decimal
%x - hex byte
%X - hex word
%lX - hex long
%b - binary word
%lb - long binary word

* indirection prefix (placed after '%' to specify indirect addressing)

(number) width description (use between '%' and format specifier to set the field width).

Returns: the position of last extraction point. This is useful for processing by other string functions

Example:

var buffer[100];    // 200 character buffer for a source string
var p, q;           // string pointers
var n;
var m[20];          // for our structure example
var format;         // a pointer to a format string

func main()

var k;

// string print example
to (buffer); print ( "\nHELLO WORLD" );

q := str_Ptr (buffer); // raise a string pointer so we can use the 
                       // string functions
p := q;
str_Printf ( &p , "%8s" ); // only prints first 8 characters of                    
                           // string  

putch ('\n');              // new line

p := q;
k := str_Printf ( &p , "%04s" ); // prints 4 leading spaces before 
                                 // string  

putch ('\n');   // new line
print ( k );    // if required, the return value points to the last 
                // source position and is returned for processing by 
                // other string functions

// print structure elements example,  make a demo structure

n := 0;
m[n++] := "Mrs Smith" ;
m[n++] := 200 ;
m[n++] := 300 ;
m[n++] := 0xAA55 ;
m[n++] := 500 ;

// make a demo format control string

format := "%*s\n%d\n%d\n%016b\n%04X" ; // format string for printing 
                                       // structure m

// print the structure in the required format

p := str_Ptr (m);           // point to structure m
str_Printf (&p, format);    // use the format string to print the 
                            // structure

endfunc

Note

  • The address of the pointer must be passed so the function can advance it as required.
  • The format specifier string can be a string pointer, allowing dynamic construction of the printing format.
  • If (number) is preceded by 0, the result is Left-pads with zeroes (0) instead of spaces.

str_Cat

Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a new null-character is appended at the end of the new string formed by the concatenation of both in destination.

Syntax: str_Cat(&destination, &source);

Argument Descrption
destination Destination string address
source Source string address

Returns: pointer to the destination.

Example:

var buf[100]; // 200 character buffer for a source string

func main()
    var p ;
    to(buf) ;
    print("Hello ") ;
    p := str_Ptr(buf) ;
    str_Cat(p,"There"); // Will append "There" to the end of buf
    print([STR] buf) ;
    repeat
    forever
endfunc

str_CatN

The number of characters copied is limited by "count". The terminating null character in destination is overwritten by the first character of source, and a new null-character is appended at the end of the new string formed by the concatenation of both in destination.

Syntax: str_CatN(&ptr, str, count);

Argument Descrption
ptr Destination string address
str Source string address
count Number of characters to be concatenated

Returns: pointer to the destination.

Example:

var buf[100]; // 200 character buffer for a source string

func main()
    var p ;
    to(buf) ;
    print("Sun ") ;
    p := str_Ptr(buf) ;
    str_CatN(p,"Monday",3); // Concatenate "Mon" to the end of buf
    print([STR] buf) ;
    repeat
    forever
endfunc

str_ByteMove

Copy bytes from "src" to "dest", stopping only when "count" is exhausted. No terminator is appended, it is purely a byte copy, and any zeroes encountered will also be copied.

Syntax: str_ByteMove(src, dest, count);

Argument Descrption
src Points to byte aligned source
dest Points to byte aligned destination
count Number of bytes to transfer

Returns: a pointer to the end of the destination (which is "dest" + "count").

Example:

var src, dest, mybuf1[10], mybuf2[10];  // string pointers and two 20 byte buffers
to(mybuf1); putstr("TESTING 123");

src := strPtr(mybuf1);
dest := str_Ptr(mybuf2);
src += 6;  // move src pointer to "G 123"

str_ByteMove(src, dest, 6);     // move to second buffer (including the zero terminator)

putstr(mybuf2);     // print result

nextpos := str_ByteMove(s, d, 100);

str_Copy

Copy a string from "src" to "dest", stopping only when the end of source string "src" is encountered (0x00 terminator). The terminator is always appended, even if "src" is an empty string.

Syntax: str_Copy(dest, src);

Argument Descrption
dest Points to byte aligned destination
src Points to byte aligned source

Returns: a pointer to the 0x00 string terminator at the end of "dest" (which is "dest" + str_Length(src);).

Example:

nextplace := str_Copy(d, s);

str_CopyN

Copy a string from "src" to "dest", stopping only when "count" is exhausted, or end of source string "src" is encountered (0x00 string terminator). The terminator is always appended, even if "count" is zero, or "src" is a null string.

Syntax: str_CopyN(dest, src, count);

Argument Descrption
dest Points to byte aligned destination
src Points to byte aligned source
count Maximum number of bytes to copy

Returns: a pointer to the 0x00 string terminator at the end of "dest" (which is "dest" + str_Length(src);).

Example:

nextplace := str_CopyN(d, s, 100);

System Memory Functions

peekW

This function returns the 16-bit value that is stored at address.

Syntax: peekW(address);

Argument Descrption
address The address of a memory word. The address is usually a pre-defined system register address constant. See the address constants for all the system word sized registers in the System Registers Memory section.

Returns: The 16-bit value stored at address.

Example:

var myvar;
myvar := peekW(SYSTEM_TIMER_LO);

// This example places the low word of the 32 bit system timer in myvar.

pokeW

This function writes a 16-bit value to a location specified by address.

Syntax: pokeW(address, word_value);

Argument Descrption
address The address of a memory word. The address is usually a pre-defined system register address constant. See the address constants for all the system word sized registers in the System Registers Memory section.
word_value The 16-bit word_value will be stored at address.

Returns: TRUE if poke address was a legal address (usually ignored).

Example:

pokeW(TIMER2, 5000);

// This example sets TIMER2 to 5 seconds.

Text and String Functions

txt_MoveCursor

Moves the text cursor to a screen position set by line and column parameters. The line and column position is calculated, based on the size and scaling factor for the currently selected font. When text is outputted to screen it will be displayed from this position. The text position could also be set with gfx_MoveTo(...); if required to set the text position to an exact pixel location. Note that lines and columns start from 0. So, line 0, column 0 is the top left corner of the display.

Syntax: txt_MoveCursor(line, column);

Arguments Description
line Holds a positive value for the required line position.
column Holds a positive value for the required column position.

Returns: None

Example

txt_MoveCursor(4, 9);

// This example moves the text origin to the 5th line and the 10th column.

putch

putch prints single characters to the current output stream, usually the display.

Syntax: putch(char);

Arguments Description
char Holds a positive value for the required character.

Returns: None

Example

var v;
v := 0x39;
putch(v);           // print the number 9 to the current display location
putch('\n');        // newline

putstr

This function prints a string to the current output stream, usually the display. The argument can be a string constant, a pointer to a string, a pointer to an array, or a pointer to a data statement.

The output of putstr can be redirected to the communications port, the media, or memory using the to(...) function.

A string constant is automatically terminated with a zero. A string in a data statement is not automatically terminated with a zero.

All variables in 4DGL are 16-bit, if an array is used for holding 8-bit characters, each array element packs 1 or 2 characters.

Syntax: putstr(ponter);

Arguments Description
pointer A string constant or pointer to a string.

Returns: The pointer to the item that was printed.

Example

// Example #1 - print a string constant
putstr("HELLO\n"); //simply print a string constant at current origin
// Example #2 - print string via pointer
var p; // a var for use as a pointer
p := "String Constant\n"; // assign a string constant to pointer s
putstr(p); // print the string using the pointer
putstr(p+8); // print, offsetting into the string
// Example #3 - printing strings from data table
#DATA   
    byte message "Week\n",0
    word days sun,mon,tue,wed,thu,fri,sat // pointers to data items
    byte sun "Sunday\n\0"
    byte mon "Monday\n\0"
    byte tue "Tuesday\n\0"
    byte wed "Wednesday\n\0"
    byte thu "Thursday\n\0"
    byte fri "Friday\n\0"
    byte sat "Saturday\n\0"
#END

var n;
putstr(message);
n:=0;
while(n < 7)
    putstr(days[n++]);  // print the days
wend

putstrCentred

This function prints a string centred at position xc, yc.

Syntax: putstrCentred(xc, yc, string);

Arguments Description
xc Specifies the X-coordinate of the centre.
yc Specifies the Y-coordinate of the centre.
string A string constant or pointer to a string.

Returns: None

Example

putstrCentred(100, 100, "HELLO"); // print “HELLO” centered at 100,100

putnum

putnum prints a 16bit number in various formats to the current output stream, usually the display.

Number formatting bits supplied by format

numberFormating

Pre-Defined format constant quick reference

DEC DECZ DECZB
DEC1 DEC1Z DEC1ZB
DEC2 DEC2Z DEC2ZB
DEC3 DEC3Z DEC3ZB
DEC4 DEC4Z DEC4ZB
DEC5 DEC5Z DEC5ZB
UDEC UDECZ UDECZB
UDEC1 UDEC1Z UDEC1ZB
UDEC2 UDEC2Z UDEC2ZB
UDEC3 UDEC3Z UDEC3ZB
UDEC4 UDEC4Z UDEC4ZB
UDEC5 UDEC5Z UDEC5ZB
HEX HEXZ HEXZB
HEX1 HEX1Z HEX1ZB
HEX2 HEX2Z HEX2ZB
HEX3 HEX3Z HEX3ZB
HEX4 HEX4Z HEX4ZB
BIN BINZ BINZB
BIN1 BIN1Z BIN1ZB
BIN2 BIN2Z BIN2ZB
BIN3 BIN3Z BIN3ZB
BIN4 BIN4Z BIN4ZB
BIN5 BIN5Z BIN5ZB
BIN6 BIN6Z BIN6ZB
BIN7 BIN7Z BIN7ZB
BIN8 BIN8Z BIN8ZB
BIN9 BIN9Z BIN9ZB
BIN10 BIN10Z BIN10ZB
BIN11 BIN11Z BIN11ZB
BIN12 BIN12Z BIN12ZB
BIN13 BIN13Z BIN13ZB
BIN14 BIN14Z BIN14ZB
BIN15 BIN15Z BIN15ZB
BIN16 BIN16Z BIN16ZB

Syntax: putnum(format, value);

Arguments Description
format A constant that specifies the number format.
value The number to be printed.

Returns: The default width of the numeric field (digit count), usually ignored.

Example

var v;
v := 05678;
putnum(HEX, v);             // print the number as hex 4 digits
putnum(BIN, v);             //print the number as binary 16 digits

print

4DGL has a versatile print(...) statement for formatting numbers and strings. In it's simplest form, print will simply print a number as can be seen below:

myvar := 100;
print(myvar);

// This will print **100** to the current output device (usually the display in TEXT mode). 

Note

If you wish to add a string anywhere within a print(...) statement, just place a quoted string expression and you will be able to mix strings and numbers in a variety of formats. See the following example.

print("the value of myvar is :- ", myvar, "and its 8bit binary representation is:-", [BIN8]myvar);

(*) Refer the table in putnum(..) for all the numeric representations available.

The print(...) statement will accept directives passed in square brackets to make it print in various ways, for instance, if you wish to print a number in 4 digit hex, use the [HEX4] directive placed in front of the variable to be displayed within the print statement. See the following example.

print("myvar as a 4 digit HEX number is :- ", [HEX4]myvar);

Note

There are 2 print directives that are not part of the numeric set and will be explained separately. these are the [STR] and [CHR] directives.

The [STR] directive expects a string pointer to follow:

s := "Hello World"; // assign a string constant to s 
print("Var 's' points to a string constant at address", s ," which is", [STR] s);

The [CHR] directive prints the character value of a variable.

print("The third character of the string is '", [CHR] *(s+2));

also

print("The value of 'myvar' as an ASCII charater is '", [CHR] myvar);

Note

You can freely mix string pointers, strings, variables and expressions within a print statement. print(...) can also use the to(...) function to redirect it's output to a different output device other than the screen using the function (refer to the to(...) statement for further examples).

Syntax: print(...);

Returns: None

Example

/////////////////////
// DATA STATEMENT  //
/////////////////////

#DATA
    word myData
    myString1, Bert, Fred, main, myString2, baud, barney, 0x1111,0x2222,0x3333,0x4444

    byte myString1 "Data String OK\n\n",0
    byte myString2 "\"(and forward referenced!)\"\n\n",0
    word baud 150,300,600,1200,2400,9600
#END

// this constant is a forward reference
#constant barney 9876

func Fred(var str)
    print("string = ", [STR] str);
endfunc

func Bert(var p1, var p2, var p3)
    print("hello from Bert\np1=",p1,"\np2=",p2, "\np3=",p3,"\n");
    return "Bert was here\n";
endfunc

func main()
    var fn;        // a variable for a handle for the function

    txt_Set(FONT_ID, FONT1);

    fn := myData[1]; //Get function pointer from data statement index
    print( [STR] fn(100,200,300) );     
    // use it in a statement to prove engine ok

    fn := myData[2]; //Get function pointer from data statement index
    fn("ABC\n");     // execute the function

    // just shows where main lives
    print("\naddress of main = code[", myData[3],"]\n\n");      
    // remember - a var can be a handle, variable, pointer or vector
    print( [STR] myData[0]);   // pointer table data reference
    print( [STR] myData[4]);

    repeat forever

endfunc

to

to() sends the printed output to destinations other than the screen. Normally, print just sends its output to the display in TEXT mode which is the default, however, the output from print can be sent to 'streams', e.g. – COM0, COM1, an open FAT16 file with DSK, to raw media with MDA (media), or to the I2C ports with I2C.

The to(...) function can also stream to a memory array . Note that once the function has taken effect, the stream reverts back to the default stream which is TEXT as soon as putch, putstr, putnum, print, or str_Printf has completed its action.

The APPEND argument is used to append the printed output to the same place as the previous redirection. This is most useful for building string arrays, or adding sequential data to a media stream.

Predefined Name Constant putch, putstr, putnum, print, str_Printf redirection destination
DSK 0xF802 Output is directed to the most recently open file that has been opened in write mode.
COM0 0xFF04 Output is redirected to the COM0 (default serial) port.
COM1 0xFF08 Output is redirected to the COM1 port.
I2C 0xF820 Output is directed to the I2C port.
MDA 0xFF40 Output is directed to the SD/SDHC or FLASH media.
APPEND 0x0000 Output is appended to user array if previous redirection was to an array.
(memory pointer) Array Address Output is redirect to the memory pointer argument.

Warning

Becareful writing to a FAT16 formatted card without checking legal partitioned are, else the disk formatting will be destroyed.

Syntax: to(outstream);

Arguments Description
outstream A variable or constant specifying the destination for the putch, putstr, putnum, print and str_Printf functions.

Returns: None

Example

//==================================================
// Example #1 – putstr redirection
//==================================================
var buf[10];         // a buffer that will hold up to 20 bytes/chars

var s;                        // a var for use as a pointer
to(buf); putstr("ONE ");      // redirect putstr to the buffer
to(APPEND); putstr("TWO ");   // and add a couple more items
to(APPEND); putstr("THREE\n");
putstr(buf);                  // print the result  

while (media_Init()==0);      // wait if no SD/SDHC card detected
media_SetSector(0, 2);        // at sector 2
//media_SetAdd(0, 1024);      // (alternatively, use media_SetAdd(), 
                              // lower 9 bits ignored).
to(MDA); putstr("Hello World");   // now write a ascii test string
media_WriteByte('A');             // write a further 3 bytes
media_WriteByte('B'); 
media_WriteByte('C'); 
to(MDA); putstr(buf);         // write the buffer we prepared earlier
media_WriteByte(0);            // terminate with ASCII zero
media_Flush();                  
media_SetAdd(0, 1024);         // reset the media address
while(char:=media_ReadByte()) 
    to(COM0); putch(char); // print the stored string to the COM port
wend
repeat forever

charwidth

charwidth is used to calculate the width in pixel units for a character, based on the currently selected font. The font can be proportional or mono spaced. If the total width of the string exceeds 255 pixel units, the function will return the 'wrapped' (modulo 8) value.

Syntax: charwidth('char');

Arguments Description
char The ascii character for the width calculation.

Returns: The width of a single character in pixel units.

Example

//==================================================
// Example
//==================================================
str := "HELLO\nTHERE";   // note that this string spans 2 lines due
                         // to the \n.
width := strwidth(str);  // get the width of the string, this will
                         // also capture the height.
height := strheight();   // note, invoking strwidth also calcs height 
                         // which we can now read.
// The string above spans 2 lines, strheight(.) will calculate height
// correctly for multiple lines. 
len := strlen(str);      // the strlen() function returns the number 
                         // of characters in a string.
print("\nLength=",len);  // NB:- the \n in "HELLO\nTHERE" is counted 
                         // as a character.
txt_FontID(MS_SanSerif8x12); // select this font
w := charwidth('W');         // get a characters width 
h := charheight('W');        // and height 
txt_FontID(0);               // back to default font 
print ("\n'W' is " ,w, " pixels wide"); // show width of a character 
                                        // 'W' in pixel units.
print ("\n'W' is " ,h, " pixels high"); // show height of a character
                                        // 'W' in pixel units.

charheight

charheight is used to calculate the height in pixel units for a character, based on the currently selected font.

Syntax: charheight('char');

Arguments Description
char The ascii character for the height calculation.

Returns: The height of a single character in pixel units.

Example: See example in charwidth.

strwidth

strwidth returns the width of a zero terminated string in pixel units. Note that any string constants declared in your program are automatically terminated with a zero as an end marker by the compiler. Any string that you create in the DATA section or MEM section must have a zero added as a terminator for this function to work correctly.

Syntax: strwidth(pointer);

Arguments Description
pointer The pointer to a zero (0x00) terminated string.

Returns: The width of a string in pixel units, can be multi line.

Example: See example in charwidth.

strheight

strheight returns the height of a zero terminated string in pixel units. The strwidth function must be called first which makes available width and height. Note that any string constants declared in your program are automatically terminated with a zero as an end marker by the compiler. Any string that you create in the DATA section or MEM section must have a zero added as a terminator for this function to work correctly.

Syntax: strheight();

Returns: The height of a string in pixel units, can be multi line.

Example: See example in charwidth.

strlen

strlen returns the length of a zero terminated string in character units. Note that any string constants declared in your program are automatically terminated with a zero as an end marker by the compiler. Any string that you create in the DATA section or MEM section must have a zero added as a terminator for this function to work correctly.

Syntax: strlen(pointer);

Arguments Description
pointer The pointer to a zero (0x00) terminated string.

Returns: The length of a string in character units.

Example: See example in charwidth.

txt_Set

Given a function number and a value, set the required text control parameter, such as size, colour, and other formatting controls. This function is extremely useful in a loop to select multiple parameters from a data statement or a control array. Note also that each function available for txt_Set has a single parameter 'shortcut' function that has the same effect.

# Predefined Name Description Value
0 TEXT_COLOUR Set the text foreground colour. Colour 0-65535
Default = LIME
1 TEXT_HIGHLIGHT Set the text background colour. Colour 0-65535
Default = BLACK
2 FONT_ID Set the required font. See font table
Note:
The value could be the name of a custom font included in a users program in a data statement.
1 to 11 or (FONT_1 to FONT_11)
Default = FONT_3
3 TEXT_WIDTH Set the text width multiplier. Text will be printed magnified horizontally by this factor. 1 to 16
Default = 1
4 TEXT_HEIGHT Set the text height multiplier. Text will be printed magnified vertically by this factor. 1 to 16
Default = 1
5 TEXT_XGAP Set the pixel gap between characters. The gap is in pixel units. 0 to 32
Default = 0
6 TEXT_YGAP Set the pixel gap between lines. The gap is in pixel units. 0 to 32
Default = 0
7 TEXT_PRINTDELAY Set the delay between character printing to give a 'teletype' like effect. 0 to 255
Default = 0 msec
8 TEXT_OPACITY Selects whether or not the 'background' pixels are drawn. 0 or TRANSPARENT
1 or OPAQUE
Default = 1 (OPAQUE)
9 TEXT_BOLD Sets Bold Text mode for the next string or char. The feature automatically resets after printing using putstr or print has completed. 0 or 1 (OFF or ON )
10 TEXT_ITALIC Sets Italic Text mode for the next string or char. The feature automatically resets after printing using putstr or print has completed. 0 or 1 (OFF or ON )
11 TEXT_INVERSE Sets Inverse Text mode for the next string or char. The feature automatically resets after printing using putstr or print has completed. 0 or 1 (OFF or ON )
12 TEXT_UNDERLINED Sets Underlined Text mode for the next string or char. The feature automatically resets after printing using putstr or print has completed. 0 or 1 (OFF or ON )
13 TEXT_ATTRIBUTES Allows a combination of text attributes to be defined together by 'or'ing the bits together. The feature automatically resets after printing using putstr or print has completed.
Example:
txt_Set(TEXT_ATTRIBUTES, BOLD | INVERSE); // bold + inverse
Note:
bits 0-3 and 8-15 are reserved.
16 or BOLD
32 or ITALIC
64 or INVERSE
128 or UNDERLINED
14 TEXT_WRAP Sets the pixel position where text wrap will occur at RHS The feature automatically resets when screen mode is changed. If the value is set to 0, text wrap is turned off of the current screen.
Note:
The value is in pixel.
0 to n (OFF or Value)
Default = 0

Single parameter short-cuts for txt_Set() functions.

Function Syntax Function Action Value
txt_FGcolour(colour) Set the text foreground colour. Colour 0 - 65535
Default = LIME
txt_BGcolour(colour) Set the text background colour. Colour 0 - 65535
Default = BLACK

txt_FontID

Set the required font. See Font table.
Note:
The value could also be the name of a custom font included in a users program in a data statement, or the handle returned from file_LoadImageControl() for a uSD based font.
1 to 11 or (FONT_1 to FONT_11)
Default = FONT_3
txt_Width(multiplier) Set the text width multiplier. Text will be printed magnified horizontally by this factor. 1 to 16
Default = 1
txt_Height(multiplier) Set the text height multiplier. Text will be printed magnified vertically by this factor. 1 to 16
Default = 1
txt_Xgap(pixelcount) Set the pixel gap between characters. The gap is in pixel units. 0 to 32
Default = 0
txt_Ygap(pixelcount) Set the pixel gap between lines. The gap is in pixel units. 0 to 32
Default = 0
txt_Delay(millisecs) Set the delay between character printing to give a 'teletype' like effect. 0 to 255
Default = 0 msec
txt_Opacity(mode) Selects whether or not the 'background' pixels are drawn
(default mode is OPAQUE)
0 or TRANSPARENT
1 or OPAQUE
Default = 0
txt_Bold(mode) Sets Bold Text mode for the next string or char. The feature automatically resets after printing using putstr or print has completed. 0 or 1 (OFF or ON)
txt_Italic(mode) Sets Italic Text mode for the next string or char. The feature automatically resets after printing using putstr or print has completed. 0 or 1 (OFF or ON)
txt_Inverse(mode) Sets Inverse Text mode for the next string or char. The feature automatically resets after printing using putstr or print has completed. 0 or 1 (OFF or ON)
txt_Underlined Sets Underline Text mode for the next string or char. The feature automatically resets after printing using putstr or print has completed. 0 or 1 (OFF or ON)
txt_Attributes(value) Allows a combination of text attributes to be defined together by 'or'ing the bits together. The feature automatically resets after printing using putstr or print has completed.
Example:
txt_Set(TEXT_ATTRIBUTES, BOLD | INVERSE); // bold + inverse
Note: bits 0-3 and 8-15 are reserved.
txt_Wrap(value) Sets the pixel position where text wrap will occur at RHS. The feature automatically resets when screen mode is changed. If the value is set to 0, text wrap is turned off of the current screen.
Note:bits 0-3 and 8-15 are reserved.
16 or BOLD
32 or ITALIC
64 or INVERSE
128 or UNDERLINED

Syntax: txt_Set(function, value);

Arguments Description
functions The function number determines the required action for various text control functions. Usually a constant, but can be a variable, array element, or expression. There are pre-defined constants for each of the functions.
value A variable, array element, expression or constant holding a value for the selected function.

Returns: None

Timer Functions

sys_T

Returns the current value of the rolling 32bit system timer (1mse) LO word.

Syntax: sys_T();

Returns: The value of system timer. (LO Word)

Example

t := sys_T();

sys_T_HI

Returns the current value of the rolling 32bit system timer (1mse) HI word.

Syntax: sys_T_HI();

Returns: The value of system timer. (HI Word)

Example

t := sys_T_HI();

sys_SetTimer

Set a countdown on the selected timer or 'top-up' if required. There are 8 timers TIMER0 to TIMER7 which stop at the count of 0. Maximum timeout period is 65, 535 milliseconds or 65.535 seconds. A timer can be read with the sys_GetTimer() function.

Syntax: sys_SetTimer(timernum, value);

Arguments Description
timernum One of eight timers TIMER0 to TIMER7.
value Countdown period in milliseconds.

Returns: None

Example

sys_SetTimer(TIMER5, 3600); //Set Timer5 for 3.6 seconds.

sys_GetTimer

Returns 0 if timer has expired, or the current countdown value. There are 8 timers TIMER0 to TIMER7 which stop at the count of 0. Maximum timeout period is 65, 535 milliseconds or 65.535 seconds.

A timer can be set with the sys_SetTimer() function.

Syntax: sys_GetTimer(timernum);

Arguments Description
timernum One of eight timers TIMER0 to TIMER7.

Returns: 0 if timer has expired, or the current countdown value.

Example

t := sys_GetTimer(TIMER2); 

sys_SetTimerEvent

Set a function to be called for selected timer. When the timer reaches zero, the function is called. The called function must not have any parameters, and should not have a return value. This is necessary because the timer event is invoked asynchronously to the mainline program (i.e, it is not called in the normal way, so parameters and return values don’t apply).

sys_SetTimerEvent(timernum, 0) disables the timer event.

Note

When a child process is run using the file_run or file_exec function, or if a file was loaded with file_Loadfunction and is executed, the loaded process gets its own code and memory space, therefore, any timer that reaches zero that has a timer event attached in the parent code space, will fail and cause a crash as an attempt is made to force the program counter to some wild place in the child process - There are 2 ways to overcome this problem.

  1. If a child process will not be requiring the use of any timers or timer events, the parent program can simply use the sys_EventsPostpone() function before calling or entering the child process. Once the parent program regains control, the sys_EventResume() function will allow any events in the queue to then be processed. The side effect of this method is that several events may bank up, and will execute immediately once the sys_EventResume() takes place. This however disallows a child process to use any timer events in the sub program so method 2 is preferable in this case.
  2. The parent program can 'disconnect' the event(s) by setting it/them to zero prior to child process execution, or setting the associated timer to zero so the event wont fire. In either case, it is necessary to do the following: while(sys_EventQueue());

To ensure the event queue is empty prior to calling the child process. Note also that if just the timer is set to zero, the child process cannot use this timer. If the timer was now set to a value and the old event still existed, when the timer reaches zero the 'bad' parent address event will fire causing a crash.

The reverse situation also applies of course, the same level of respect is required if a child program needs to use any timer events. Method [1] (above) will not work as the events have been postponed, stopping the child process from using any timer events. If the child process did an sys_EventResume() in this case, everything would crash miserably. So the same applies, a child that uses any timer events must respect any timers that may be used by the parent, and a child must zero the sys_SetTimerEvent before returning to the parent.

sys_SetTimerEvent(timernum, 0) disables the timer event.

Syntax: sys_SetTimerEvent(timernum, function);

Arguments Description
timernum One of eight timers TIMER0 to TIMER7.
function Event Function to be queued.

Returns: Any previous event function address, or zero if there was no previous function.

Example

sys_SetTimerEvent(TIMER5, myfunc);

sys_EventQueue

Returns the max number of events that were pending in the event queue since the last call to this function. This can be used to assess event overhead burden, especially after or during a sys_EventsPostpone action.

Syntax: sys_EventQueue();

Returns: Number of events.

Example

tasks := sys_EventQueue(); //

sys_EventsPostpone

Postpone any events until the sys_EventResume function is executed. The event queue will continue to queue events, but no action will take place until a sys_EventResume function is encountered.

The queue will continue to receive up to 32 events before discarding any further events. This function is required to allow a sequence of instructions or functions to occur that would otherwise be corrupted by an event occurring during the sequence of instructions or functions.

A good example of this is when you set a position to print, if there was no way of locking the current sequence, an event may occur which does a similar thing, and a contention would occur - printing to the wrong position. This function should be used wisely, if any action that is required would take considerable time, it is better to disable any conflicting event functions with a bypass flag, then restart the conflicting event by re-issuing a timer value.

Syntax: sys_EventsPostpone();

Returns: None

Example

sys_EventsPostpone(); // postpone the event queue

sys_EventsResume

Resume any postponed events. The queue will try to execute any events that were incurred during the postponed period. Note that queued events are only checked for and executed at the end of each 4DGL instruction.

Syntax: sys_EventsResume();

Returns: None

Example

sys_EventsResume(); // resume the event queue

sys_DeepSleep

Deep Sleep is a sleep state that is ‘deeper’ than the regular Sleep (for most display modules) and therefore consumes less power. Some displays do not support being powered to a lower state, so sleep and deepsleep power consumption can sometimes be roughly the same.

Puts the display and processor into the lowest power mode for a period of time. If "units" is zero, the display goes into sleep mode forever and needs power cycling to re-initialize. If "units" is 1 to 65535, the display will sleep for that period of time, or will be woken when touch screen is touched. The function returns the count of "units" that are remaining when the screen was touched. When returning from deep sleep mode, some displays might lose their screen and/or need to be reinitialised with disp_Init().

Syntax: sys_DeepSleep(units);

Arguments Description
units Sleep timer units are approx 1 second. When in sleep mode, timing is controlled by an RC oscillator, therefore, timing is not totally accurate and should not be relied on for timing purposes.

Returns: Remaining time units when touch screen is touched, else returns zero.

Example

sys_DeepSleep(60); // Sleep for 1 minute

sys_Sleep

Regular sleep, which puts the display and processor into low power mode for a period of time. If "units" is zero, the display goes into sleep mode forever and needs power cycling to re-initialize. If "units" is 1 to 65535, the display will sleep for that period of time, or will be woken when touch screen is touched. The function returns the count of "units" that are remaining when the screen was touched. When returning from sleep mode, the display and processor are restored from low power mode.

Note

sys_Sleep() was found to have an issue in PmmC’s prior to R33, the units value was not always near 1 second. This has been corrected in PmmC R33.

Syntax: sys_Sleep(units);

Arguments Description
units Sleep timer units are approx 1 second. When in sleep mode, timing is controlled by an RC oscillator, therefore, timing is not totally accurate and should not be relied on for timing purposes.

Returns: Remaining time units when touch screen is touched, else returns zero.

Example

sys_Sleep(60); // Sleep for 1 minute

iterator

Sets the iterator size for the next postinc, postdec, preinc or predec by a specified value. The offset will return to 1 after the next operation.

Syntax: iterator_(offset);

Arguments Description
offset Offset size for the next ++ or - - command.

Returns: None

Example

t := iterator(10); // Set the iterator size to be 10

Touch Screen Functions

touch_DetectRegion

Specifies a new touch detect region on the screen. This setting will filter out any touch activity outside the region and only touch activity within that region will be reported by the status poll touch_Get() function.

Syntax: touch_DetectRegion(x1, y1, x2, y2);

Arguments Description
x1 specifies the horizontal position of the top left corner of the region.
y1 specifies the vertical position of the top left corner of the region.
x2 specifies the horizontal position of the bottom right corner of the region.
y2 specifies the vertical position of the bottom right corner of the region.

Returns: None

Example

gfx_Rectangle(100, 100, 201, 201, YELLOW);      // draw a rectangle with a yellow border
touch_DetectRegion(101, 101, 200, 200);         // limit touch detect region towithin the rectangle

touch_Set

Sets various Sets various Touch Screen related parameters.

mode = TOUCH_ENABLE (Mode 0) Enable Touch Screen.

touch_Set(TOUCH_ENABLE); - Enables and initialises Touch Screen hardware

mode = TOUCH_DISABLE (Mode 1) Disable Touch Screen.

touch_Set(TOUCH_DISABLE); - Disables the Touch Screen.

mode = TOUCH_REGIONDEFAULT (Mode 2) Default Touch Region.

touch_Set(TOUCH_REGIONDEFAULT); - This will reset the current active region to default which is the full screen area

Note

Touch Screen task runs in the background and disabling it when not in use will free up extra resources for 4DGL CPU cycles.

Syntax: touch_Set(mode);

Arguments Description
mode mode = TOUCH_ENABLE
mode = TOUCH_DISABLE
mode = TOUCH_REGIONDEFAULT

Returns: None

Example

touch_Set(TOUCH_DISABLE);  // Disable touch
touch_Set(TOUCH_ENABLE);   // Enable touch
touch_Set(TOUCH_ENABLE);   // Reset default touch region

touch_Get

Returns various Touch Screen parameters to caller.

Sometimes NOTOUCH can be returned when the touchscreen is touched and held (in between pressed and released). This occurs if the touch points are identical on two successive calls, because it does not qualify as MOVING, but it has not yet been RELEASED (but has already been PRESSED)

mode = TOUCH_STATUS (Mode 0) - Returns the various states of the touch screen

  • 0 = INVALID/NOTOUCH
  • 1 = TOUCH_PRESSED
  • 2 = TOUCH_RELEASED
  • 3 = TOUCH_MOVING

mode = TOUCH_GETX (Mode 1) - Returns the X coordinates of the touch reported by mode 0

mode = TOUCH_GETY (Mode 2) - Returns the Y coordinates of the touch reported by mode 0

Syntax: touch_Get(mode);

Arguments Description
mode mode = TOUCH_STATUS (Mode 0): Get Status
mode = TOUCH_GETX (Mode 1) : Get X coordinates
mode = TOUCH_GETY (Mode 2) : Get Y coordinates

Returns: The various states of the touch screen
0 = NOTOUCH
1 = TOUCH_PRESSED
2 = TOUCH_RELEASED
3 = TOUCH_MOVING

Example

state := touch_Get(TOUCH_STATUS);  // get touchscreen status
        x := touch_Get(TOUCH_GETX);
        y := touch_Get(TOUCH_GETY);

        if (state == TOUCH_PRESSED)   // see if Exit hit
            if ( x > 170 && y > 280 ) // EXIT button
                gfx_Cls();
                exit := -1;
            endif

            if (vertical)
                if ( x > 170 && (y > 240 && y < 270 ))// Horiz button
                    vertical := 0;
                    exit := 1;
                endif
            else
                if ( x > 170 && (y > 200 && y < 230 ))// Vert button
                    vertical := 1;
                    exit := 2;
                endif
            endif

        endif

Widget Functions

widget_Create

Creates a widget control capable of holding count elements and returns a handle for the control.

Syntax: widget_Create(count);

Arguments Description
count The number of elements in the widget control.

Returns: Widget control handle.

Example

var hndl;
hndl := widget_Create(1);

widget_Add

Add a widget ram entry "widget" into index "index" of the widget control referenced by "hndl".

Syntax: widget_Add(hndl, index, widget);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.
widget Pointer to RAM allocation of the entry widget.

Returns: None

Example

var hndl;
hndl := widget_Create(1);
widget_Add(hndl, 0, ILed1RAM);      // Add entry index 0 for Led

widget_Delete

Delete widget ram entry "index" from the widget control referenced by "hndl".

Syntax: widget_Delete(hndl, index);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.

Returns:

Example

var hndl;
hndl := widget_Create(1);
widget_Add(hndl, 0, ILed1RAM);      // Add entry index 0 for Led1
widget_Delete(hndl, 0);             // Remove entry index 0

widget_Realloc

Resizes a widget control "handle" to contain n entries, allowing it to be expanded or condensed. Doing this unnecessarily can lead to RAM fragmentation. It is much better to allocate widget controls once with the desired number of entries.

Syntax: widget_Realloc(handle, n);

Arguments Description
handle Handle of the widget control.
n New number of entries.

Returns: New handle to widget control.

Example

var hndl;
hndl := widget_Create(10);
widget_Add(hndl, 0, ILed1RAM);
widget_Add(hndl, 1, ILed2RAM);
widget_Add(hndl, 2, ILed3RAM);
hndl := widget_Realloc(hndl, 3);        // Reallocate widget control

widget_LoadFlash

Reads the flash control file to create a widget list.

Syntax: widget_LoadFlash(Extra);

Arguments Description
Extra The number of extra widget controls to be created beyond the count in flash memory.

Returns: a handle (pointer to the memory allocation) to the widget control list that has been created, otherwise, returns NULL if function fails.

Example

var hImagelist;
hImagelist := widget_LoadFlash(0);

widget_Show

Display a flash resident image entry.

Syntax: widget_Show(hndl, index);

Arguments Description
hndl Handle of the widget control
index Index of element in the widget control

Returns: TRUE if successful, return value usually ignored.

Example

var hndl;
hndl := widget_LoadFlash(0);
widget_Show(hndl, 0);

widget_SetWord

Set specified word in an image entry. This function requires that a widget control has been created with the widget_Create() function.

Predefined Name Value Description
WIDGET_XPOS 0 RAM xpos
WIDGET_yPOS 1 RAM ypos
WIDGET_WIDTH 2 RAM width, needed for touch.
WIDGET_HEIGHT 3 RAM height, needed for touch.
WIDGET_XOTHER 4 RAM xpos 'other' (Non Flash widgets only).
WIDGET_LO_WORD 4 Flash offset low word (External Flash widgets only).
WIDGET_YOTHER 5 RAM ypos 'other' (Non Flash widgets only).
WIDGET_HI_WORD 5 Flash offset high word (Flash widgets only).
WIDGET_FLAGS 6 RAM Flags.
WIDGET_TAG 7 RAM tag (user or FORM#).
WIDGET_TAG2 8 RAM tag2 (user or object << 8
WIDGET_VAL1 9 RAM current value.
WIDGET_DELAY 10 Inter frame delay (Flash widgets only).
WIDGET_FRAMES 11 Number of frames (Flash widgets only).

Syntax: widget_SetWord(hndl, index, offset, value)

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.
offset Offset of the required word in the widget entry.
value The word to be written to the entry.

Returns: TRUE if successful, return value usually ignored.

Example

#DATA
    word IGauge1 10, 10, 30, 160, 80, 0, 100, 0, 0, 0x18E3, 0x0280, LIME, 0x5280, YELLOW, 0x5000, RED, 51, 36, 0x0
#END

var IGauge1RAM WIDGET_RAM_SPACE

func main()
    var hndl;
    hndl := widget_Create(1);
    widget_Add(hndl, 0, IGauge1RAM);
    gfx_Gauge(50, IGauge1RAM , IGauge1);

    widget_SetWord(hndl, 0, WIDGET_XPOS, 45);
    gfx_Gauge(50, IGauge1RAM , IGauge1);

    repeat
    forever
endfunc

widget_GetWord

Returns specified word (0-14) from a widget entry. Refer to widget control entry offsets. This function requires that a widget control has been created with the widget_Create() function.

Widget Control entry offset

Predefined Name Value Description
WIDGET_XPOS 0 RAM xpos
WIDGET_yPOS 1 RAM ypos
WIDGET_WIDTH 2 RAM width, needed for touch.
WIDGET_HEIGHT 3 RAM height, needed for touch.
WIDGET_XOTHER 4 RAM xpos 'other' (Non Flash widgets only).
WIDGET_LO_WORD 4 Flash offset low word (External Flash widgets only).
WIDGET_YOTHER 5 RAM ypos 'other' (Non Flash widgets only).
WIDGET_HI_WORD 5 Flash offset high word (Flash widgets only).
WIDGET_FLAGS 6 RAM Flags.
WIDGET_TAG 7 RAM tag (user or FORM#).
WIDGET_TAG2 8 RAM tag2 (user or object << 8
WIDGET_VAL1 9 RAM current value.
WIDGET_DELAY 10 Inter frame delay (Flash widgets only).
WIDGET_FRAMES 11 Number of frames (Flash widgets only).

Syntax: widget_GetWord(hndl, index, offset);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.
offset Offset of the required word in the widget entry.

Returns: The specified word (0-14) from a widget entry.

Example

#DATA
    word Led1Info 5, 30, 103, 56, 0x2965, BLACK, 0xDEFB, 0xF800, 0x5800, 20,30, 10, 20, 1
#END

var Led1 Ram [WIDGET_RAM_SPACE];

func main()
    var hndl;
    var width;
    hndl := widget_Create(1);
    widget_Add(hndl, 0, Led1Ram);
    gfx_Led(0, Led1Ram, Led1Info);
    width := widget_GetWord(hndl, 0, WIDGET_ WIDTH);
    print(width); // Print widget width from RAM
    repeat
    forever
endfunc

widget_Setposition

Set the position of an entry in the widget control. This function requires that a widget control has been created with the widget_Create() function.

Syntax: widget_Setposition(hndl, index, xpos, ypos);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.
xpos x-coordinate of position.
ypos y-coordinate of position.

Returns: True if index was ok and function was successful.

Example

#DATA
word Led1Info 5,  5 , 103,  56, 0x2965, BLACK, 0xDEFB, 0xF800, 0x5800,  20,  30,  10,  20,   1
#END

var Led1Ram[WIDGET_RAM_SPACE];

func main()
    var hndl;
    hndl := widget_Create(1);
    widget_Add(hndl, 0, Led1Ram);
    gfx_Led(0, Led1Ram, Led1Info);
    pause(2000);
    gfx_Cls();
    widget_Setposition(hndl, 0, 50, 50); // Set new widget position
    gfx_Led(0, Led1Ram, Led1Info);
    repeat

    forever
endfunc

widget_Enable

Enable an item in a widget control. This function requires that a widget control has been created with the widget_Create() function.

Syntax: widget_Enable(hndl, index);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.

Returns: True if index was ok and function was successful.

Example

#DATA
word IILed1 5,  30, 103,  56, 0x2965, BLACK, 0xDEFB, 0xF800, 0x5800,  20,  30,  10,  20,   1
word IILed2 5,  90, 103,  56, 0x2965, BLACK, 0xDEFB, BLUE, 0x000B,  20,  30,  10,  20,   1
#END

var ILed1RAM[WIDGET_RAM_SPACE] ;
var ILed2RAM[WIDGET_RAM_SPACE] ;

func main()
    var hndl, i;
    hndl := widget_Create(2);
    widget_Add(hndl, 0, ILed1RAM);
    widget_Add(hndl, 1, ILed2RAM);

    repeat
        if (i == 0)
            widget_Disable(hndl, 0); // Disable LED 0
            widget_Enable(hndl, 1);  // Enable LED 1
        else
            widget_Disable(hndl, 1); // Disable LED 1
            widget_Enable(hndl, 0);  // Enable LED 0
        endif
        // Draw LED widgets
        widget_ClearAttributes(hndl, ALL, WIDGET_F_INITIALISED);
        gfx_Led(0, ILed1RAM, IILed1);
        gfx_Led(0, ILed2RAM, IILed2);
        pause(2000);
        gfx_Cls();
        i := !(i);
    forever
endfunc

widget_Disable

Disable an item in a widget control. This function requires that a widget control has been created with the widget_Create() function.

Syntax: widget_Disable(hndl, index);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.

Returns: True if index was ok and function was successful.

Example: See example in widget_Enable().

widget_SetAttributes

This function SETS one or more bits in the widget flags field of a widget control entry. "value" refers to various bits in the widget control entry (see widget attribute flags). A '1' bit in the "value" field SETS the respective bit in the widget flags field of the widget control entry.

Widget attribute flags to be used and maintained by widgets and touch processing:

WIDGET_F_TOUCH_ENABLE 0x8000 Set to disable touch for this image,
(default=1 for movie, 0 for image).
WIDGET_F_INTERNAL 0x4000 Internal use only (force redraw on next write).
WIDGET_F_INITIALISED 0x2000 Flag when ‘base gauge needle, etc.’ is done
WIDGET_F_UNDRAW_ONLY 0x1000 Set to prevent draw of new needle.
WIDGET_F_INPUT 0x0800 Set if this is an input (Used only with the IDE).
WIDGET_F_FLASH 0x0400 set if this is a flash based widget.
WIDGET_F_RESERVED 0x03c0 bits 9-6 reserved.

Syntax: widget_SetAttributes(hndl, index, value);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.
value The word to be written to the entry.

Returns: TRUE if successful, return value usually ignored.

Example

#DATA
    word Slider1Info 10, 10, 250, 40, 0, 0, 100, 0x1082, 0x0, 0x7E0, 30, 30, 2, 2, 10, 0x7E0, 5, 0x7E0, FONT3, 0xFFE0, 0x1082, 0x9CD3, GRAD_DOWN, 0x1082, 0x9CD3, GRAD_UP
#END

var Slider1Ram[10];

func main()
    var hndl;
    hndl := widget_Create(1);
    widget_Add(hndl, 0, Slider1Ram);
    widget_SetAttributes(hndl, 0, WIDGET_F_TOUCH_ENABLE);
    gfx_Slider5(frame, Slider1Ram, Slider1 Info);

    repeat
    // do something here
    forever
endfunc

widget_ClearAttributes

This function CLEARS one or more bits in the widget flags field of an image control entry. "value" refers to various bits in the widget control entry (see widget attribute flags). A '1' bit in the "value" field CLEARS the respective bit in the widget flags field of the image control entry.

Widget attribute flags to be used and maintained by widgets and touch processing:

WIDGET_F_TOUCH_ENABLE 0x8000 Set to disable touch for this image,
(default=1 for movie, 0 for image).
WIDGET_F_INTERNAL 0x4000 Internal use only (force redraw on next write).
WIDGET_F_INITIALISED 0x2000 Flag when ‘base gauge needle, etc.’ is done
WIDGET_F_UNDRAW_ONLY 0x1000 Set to prevent draw of new needle.
WIDGET_F_INPUT 0x0800 Set if this is an input (Used only with the IDE).
WIDGET_F_FLASH 0x0400 set if this is a flash based widget.
WIDGET_F_RESERVED 0x03c0 bits 9-6 reserved.

Syntax: widget_ClearAttributes(hndl, index, value);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.
value The word to be written to the entry.

Returns: TRUE if successful, return value usually ignored.

Example

#DATA
    word fLed1Info 5, 5 , 103, 56, 0x2965, BLACK, 0xDEFB, 0xF800, 0x5800, 20, 30, 10, 20, 1
#END

var Led1[WIDGET_RAM_SPACE];

func main()
    var hndl;
    hndl := widget_Create(10);
    widget_Add(hndl, 0, Led1);
    gfx_Led(0, Led1, fLed1Info);
    pause(2000);
    gfx_Cls();
    widget_ClearAttributes(hndl, 0, WIDGET_F_INITIALISED);
    gfx_Led(0, Led1, fLed1Info);

    repeat
    // do something here
    forever
endfunc

widget_Touched

This function requires that a widget control has been created with the widget_Create() function.

Returns index of the widget touched or returns -1 if no widget was touched.

If index is passed as -1 or ALL the function tests all widgets.

Syntax: widget_Touched(hndl, index);

Arguments Description
hndl Handle of the widget control.
index Index of element in the widget control.

Returns: -1 if image not touched, or returns index.

Example

if(state == TOUCH_PRESSED)
    n := widget_Touched(hndl, ALL);     //scan widget list, looking for a touch
    if(n != 1)
        print( n);                      // print index of widget touched
    endif
endif

widget_FontID

Set the required font.

Syntax: widget_FontID(id);

Arguments Description
id Text font ID for flash-based font.

Returns: id of previous font.

Example

widget_FontID(0);

System Registers Memory

The following tables outline in detail the PIXXI-28 and PIXXI-44 system registers and flags.

Label Address
DEC
Address
HEX
Usage
RANDOM_LO 32 0x20 random generator LO word
RANDOM_HI 33 0x21 random generator HI word
SYSTEM_TIMER_LO 34 0x22 1msec system timer LO word
SYSTEM_TIMER_HI 35 0x23 1msec system timer HI word
TIMER0 36 0x24 1msec user timer 0
TIMER1 37 0x25 1msec user timer 1
TIMER2 38 0x26 1msec user timer 2
TIMER3 39 0x27 1msec user timer 3
TIMER4 40 0x28 1msec user timer 3
TIMER5 41 0x29 1msec user timer 3
TIMER6 42 0x2A 1msec user timer 3
TIMER7 43 0x2B 1msec user timer 3
SYS_X_MAX 44 0x2C display hardware X res-1
SYS_Y_MAX 45 0x2D display hardware Y res-1
GFX_XMAX 46 0x2E width of current orientation
GFX_YMAX 47 0x2F height of current orientation
GFX_LEFT 48 0x30 image left real point
GFX_TOP 49 0x31 image top real point
GFX_RIGHT 50 0x32 image right real point
GFX_BOTTOM 51 0x33 image bottom real point
GFX_X1 52 0x34 image left clipped point
GFX_Y1 53 0x35 image top clipped point
GFX_X2 54 0x36 image right clipped point
GFX_Y2 55 0x37 image bottom clipped point
GFX_X_ORG 56 0x38 current X origin
GFX_Y_ORG 57 0x39 current Y origin
GFX_HILITE_LINE 58 0x3A current multi line button hilite line
GFX_LINE_COUNT 59 0x3B count of lines in multiline button
GFX_LAST_SELECTION 60 0x3C last selected line
GFX_HILIGHT_BACKGROUND 61 0x3D multi button hilite background colour
GFX_HILIGHT_FOREGROUND 62 0x3E multi button hilite background colour
GFX_BUTTON_FOREGROUND 63 0x3F store default text colour for hilite line tracker
GFX_BUTTON_BACKGROUND 64 0x40 store default button colour for hilite line tracker
GFX_BUTTON_MODE 65 0x41 store current buttons mode
GFX_TOOLBAR_HEIGHT 66 0x42 height above
GFX_STATUSBAR_HEIGHT 67 0x43 height below
GFX_LEFT_GUTTER_WIDTH 68 0x44 width to left
GFX_RIGHT_GUTTER_WIDTH 69 0x45 width to right
GFX_PIXEL_SHIFT 70 0x46 pixel shift for button depress illusion
GFX_VECT_X1 71 0x47 gp rect, used by multiline button to hilite required line
GFX_VECT_Y1 72 0x48
GFX_VECT_X2 73 0x49
GFX_VECT_Y2 74 0x4A
GFX_THUMB_PERCENT 75 0x4B size of slider thumb as percentage
GFX_THUMB_BORDER_DARK 76 0x4C darker shadow of thumb
GFX_THUMB_BORDER_LIGHT 77 0x4D lighter shadow of thumb
TOUCH_XMINCAL 78 0x4E touch calibration value
TOUCH_YMINCAL 79 0x4F touch calibration value
TOUCH_XMAXCAL 80 0x50 touch calibration value
TOUCH_YMAXCAL 81 0x51 touch calibration value
IMG_WIDTH 82 0x52 width of currently loaded image
IMG_HEIGHT 83 0x53 height of currently loaded image
IMG_FRAME_DELAY 84 0x54 if image, else inter frame delay for movie
IMG_FLAGS 85 0x55 bit 4 determines colour mode, other bits reserved
IMG_FRAME_COUNT 86 0x56 count of frames in a movie
IMG_PIXEL_COUNT_LO 87 0x57 count of pixels in the current frame
IMG_PIXEL_COUNT_HI 88 0x58 count of pixels in the current frame
IMG_CURRENT_FRAME 89 0x59 last frame shown
MEDIA_ADDRESS_LO 90 0x5A uSD byte address LO
MEDIA_ADDRESS_HI 91 0x5B uSD byte address HI
MEDIA_SECTOR_LO 92 0x5C uSD sector address LO
MEDIA_SECTOR_HI 93 0x5D uSD sector address HI
MEDIA_SECTOR_COUNT 94 0x5E uSD number of bytes remaining in sector
TEXT_XPOS 95 0x5F text current x pixel position
TEXT_YPOS 96 0x60 text current y pixel position
TEXT_MARGIN 97 0x61 text left pixel pos for carriage return
TXT_FONT_TYPE 98 0x62 font type, 0 = system font, else pointer to user font
TXT_FONT_MAX 99 0x63 max number of chars in font
TXT_FONT_OFFSET 100 0x64 starting offset (normally 0x20)
TXT_FONT_WIDTH 101 0x65 current font width
TXT_FONT_HEIGHT 102 0x66 current font height
GFX_TOUCH_REGION_X1 103 0x67 touch capture region
GFX_TOUCH_REGION_Y 104 0x68 touch capture region
GFX_TOUCH_REGION_X2 105 0x69 touch capture region
GFX_TOUCH_REGION_Y2 106 0x6A touch capture region
GFX_CLIP_LEFT_VAL 107 0x6B left clipping point (set with gfx_ClipWindow(...))
GFX_CLIP_TOP_VAL 108 0x6C top clipping point (set with gfx_ClipWindow(...))
GFX_CLIP_RIGHT_VAL 109 0x6D right clipping point (set with gfx_ClipWindow(...))
GFX_CLIP_BOTTOM_VAL 110 0x6E bottom clipping point (set with gfx_ClipWindow(...))
GFX_CLIP_LEFT 111 0x6F current clip value (reads full size if clipping turned off)
GFX_CLIP_TOP 112 0x70 current clip value (reads full size if clipping turned off)
GFX_CLIP_RIGHT 113 0x71 current clip value (reads full size if clipping turned off)
GFX_CLIP_BOTTOM 114 0x72 current clip value (reads full size if clipping turned off)
GRAM_PIXEL_COUNT_LO 115 0x73 LO word of count of pixels in the set GRAM area
GRAM_PIXEL_COUNT_HI 116 0x74 HI word of count of pixels in the set GRAM area
TOUCH_RAW_X 117 0x75 12-bit raw A2D X value from touch screen
TOUCH_RAW_Y 118 0x76 12-bit raw A2D Y value from touch screen
GFX_LAST_CHAR_WIDTH 119 0x77 calculated char width from last call to charWidth function
GFX_LAST_CHAR_HEIGHT 120 0x78 calculated height from last call to charHeight function
GFX_LAST_STR_WIDTH 121 0x79 calculated width from last call to strWidth function
GFX_LAST_STR_HEIGHT 122 0x7A calculated height from last call to strHeight function

Note

These registers are accessible with peekW and pokeW functions.

Runtime Errors

Runtime Errors Table

Error No. Meaning Category
1 Failed to receive 'L' during loading process from the IDE IDE
2 Did not receive valid header info from the IDE IDE
3 Header size does not match loader info IDE
4 Could not allocate enough memory for program IDE
5 Loader checksum error IDE
6 Did not receive header prior to 'L' command IDE
7 Header size entry does not match loader value IDE
8 Failed to load program from FLASH Internal
9 Could not allocate code segment File loader
10 Could not load function file from disk File loader
11 Bad header in program file File loader
12 Header in program file differs from file size File loader
13 Could not allocate global memory for program file File loader
14 Program File checksum error File loader
15 EVE Stack Overflow System
Error No. Meaning V1 V2
16 Unsupported PmmC function fnc 1st Arg
17 Illegal COM0 Event Function address addr (ignored)
18 Illegal COM1 Event Function address addr (ignored)
19 Bad txt_Set(...) command number command value
20 Bad gfx_Get(...) command number command (ignored)
21 Bad txt_Set(...) command number command value
22 Bad address for peekW or pokeW command (ignored)
23 Bad timer number for sys_SetTimer(..) or sys_GetTimer(..) tnum value
24 Bad timer number for sys_SetTimerFunction(...) tnum funcaddr
25 Total size exceeds Flash Size (ignored) (ignored)

Revision History

Document Revision

Revision Date Revision Content
1.0 - Initial Internal Release Version
1.1 18/06/2020 Initial Release Version
1.2 16/07/2020 Added crc_CSUM_8, gfx_GradientShape, gfx_GradientColor and gfx_GradTriangleFilled functions
Updated spi_Init so its application is clear
1.3 04/08/2020 Addition of flash_functions
1.4 07/10/2020 media_Init4() function added for 32MB SPI Flash memory support, and media_Init() updated
1.5 08/12/2020 Added note to img_File* functions regarding GCF and Flash only.
Fixed incorrect information on mem_Realloc function return, and ptr syntax.
1.6 21/12/2020 Added baud rate formula for calculating actual baud rate and error %. See setbaud() and com_SetBaud() functions.
Corrected setbaud() table, which had actual baud and error values which were incorrect.
1.7 14/07/2021 Updated the ‘value’ description for gfx_LedDigits
1.8 02/09/2022 Updated notes on multiple functions to distinguish which ones are Flash or uSD PmmC only functions.
Added intflash_ section and functions
1.9 06/10/2022 Added bus_In() and bus_Out(value) functions
1.10 14/02/2023 Modified for web-based documentation