Skip to content

DIABLO-16 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 DIABLO-16 Processor. This document should be used in conjunction with the 4DGL Programmers Reference Manual.

Internal Functions Summary

DIABLO-16 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);

Arguments Description
char Specifies the ASCII character for the test.

Return: 0 if character is not as ASCII digit, 1 if character is an ASCII digit.

Example

func main()
    var ch;
    var stat;
    gfx_Cls();
    txt_Set(FONT_ID, FONT2);
    print("Serial Input Test\n");
    print("Downloading prog to flash\n");
    print("Then use debbug terminal\n");

    to(COM0); print("serial input test:\n");

    // now just stay in a loop
    repeat                      // maybe replace

        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");
            if (isxdigit(ch)) print("Character is ASCII Hexadecimal");
            if (isupper(ch)) print("Character is ASCII uppercase letter");
            if (islower(ch)) print("Character is ASCII uppercase letter");
            if (isalpha(ch)) print("Character is an ASCII uppercase or lowercase");
            if (isalnum(ch)) print("Character is an ASCII Alphanumeric");
            if (isprint(ch)) print("Character is a printable ASCII");
            if (isspace(ch)) print("Character is a space type character");
        endif
    forever                     // this as well

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);

Arguments Description
char Specifies the ASCII character for the test.

Returns: 0 if character is not as ASCII hexadecimal digit, 1 if characted is an ASCII hexadecimal digit.

Example: Refer to isdigit Example

isupper

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

Syntax: isupper(char);

Arguments Description
char Specifies the ASCII character for the test.

Returns: 0 if character is not as ASCII upper case letter, 1 if characted is an ASCII upper case letter.

Example: Refer to isdigit Example

islower

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

Syntax: islower(char);

Arguments Description
char Specifies the ASCII character for the test.

Returns: 0 if character is not as ASCII lower case letter, 1 if characted is an ASCII lower case letter.

Example: Refer to isdigit Example

isalpha

Tests the character parameter and returns a 1 if the character is an ASCII lower or upper case letter else returns a 0. Valid range : "abcd....wxyz", “ABCD....WXYZ”

Syntax: isalpha(char);

Arguments Description
char Specifies the ASCII character for the test.

Returns: 0 if character is not as ASCII lower or upper case letter, 1 if characted is an ASCII lower or upper case letter.

Example: Refer to isdigit Example

isalnum

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

Syntax: isalnum(char);

Arguments Description
char Specifies the ASCII character for the test.

Returns: 0 if character is not as ASCII Alphanumeric character, 1 if characted is an ASCII Alphanumeric character.

Example: Refer to isdigit 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);

Arguments Description
char Specifies the ASCII character for the test.

Returns: 0 if character is not a printable ASCII character, 1 if characted is a printable ASCII character.

Example: Refer to isdigit 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);

Arguments Description
char Specifies the ASCII character for the test.

Returns: 0 if character is not a space type character, 1 if characted is a space type character.

Example: Refer to isdigit Example

toupper

Tests the character parameter and if the character is a lower cases letter, it returns the upper case equivalent else returns the passed char. Valid range: "abcd ... wxyz".

Syntax: toupper(char);

Arguments Description
char Specifies the ASCII character for the test.

Returns: The upper case equivalent else returns the passed char.

Example

func main()
    var ch, Upconvch, Loconvch, stat;
    gfx_Cls();
    txt_Set(FONT_ID, FONT2);
    print ("Serial Input Test\nDownload 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 a lower case letter it returns the upper case equivalent else returns the passed char. Valid range: "ABCD ... WXYZ".

Syntax: toupper(char);

Arguments Description
char Specifies the ASCII character for the test.

Returns: The lower case equivalent if characters are upper case else returns the passed char.

Example

Refer to toupper Example

LObyte

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

Syntax: LObyte(var);

Arguments 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-bits) of a 16-bit variable.

Syntax: HIbyte(var);

Arguments 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);

Arguments Description
var User variable.

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

Example

myvar := ByteSwap(myvar2);

NybleSwap

Returns the swapped lower bytes nybles, upper byte retained.

Syntax: NybleSwap(var);

Arguments Description
var User variable.

Returns: Returns the 16-bit variable with swapped lower nybles.

Example

myvar := ByteSwap(myvar2);

CRC Functions

The CRC functions are mainly designed for serial communications, but are implemented in such a way that they can be used to other things as well. The com_TXblock and com_RXblock commands can be used to assist with reading and writing comm ports, generating and checking CRCs with the minimum of user data manipulation.

crc_16

Calculates the Checksum CRC using the ‘standard’ 16-bit CRC algorithm. For the standard test string "123456789", crc_16 will return 0xBB3D. Note if you calculate all of the incoming data INCLUDING the CRC, the result should be 0x00

Syntax: crc_16(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 16-bit CRC.

Example

Crc := crc_16(str_Ptr(buf), 10);

crc_CCITT

Calculates the Checksum CRC as a ‘standard’ CRCITT checksum. For the standard test string "123456789", crc_CCITT with seed = 0 (XMODEM protocol) will return = 0x31C3, for seed = 0xFFFF, the result will be 0x29B1 and for seed = 0x1D0F, the result is 0xE5CC.

Syntax: crc_CCITT(buf, count, seed);

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

Returns: The generated CCITT CRC.

Example

Crc := crc_CCITT(str_Ptr(buf), 10, 0x0000);

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 0x0023. Note if you calculate all of the incoming data INCLUDING the CRC, the result should be 0x00

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

Crc := crc_CSUM_8(str_Ptr(buf), 10);

crc_MODBUS

Calculates the Checksum CRC as per the MODBUS standard.

For the standard test string "123456789", crc_MODBUS will return 0x4B37. Note if you calculate all of the incoming data INCLUDING the CRC, the result should be 0x00

Syntax: crc_MODBUS(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 MODBUS CRC.

Example

Crc := crc_MODBUS(str_Ptr(buf), 10);

Display I/O Functions

These functions allow direct display access for fast blitting operations.

disp_SetReg

Sets the Display driver IC register.

Syntax: disp_SetReg(register, data);

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

Returns: None

disp_setGRAM

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

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

Arguments Description
x1, y1 Top left of the GRAM window.
x2, y2 Bottom right of 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);

Arguments 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 data sheets for the display for more information. This function is used to extend the capabilities of the user code to gain access to the display hardware.

Syntax: disp_WriteControl(value);

Arguments 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 data sheets 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);

Arguments Description
value Specifies the value to be written to the display data register.

Returns: None

Example

disp_WriteWord(0x7FF0);

disp_ReadWord

Read a word from the display.

Syntax: disp_ReadWord();

Returns: 16-bit value in the register.

Example

var val

val := disp_ReadWord();

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.

Syntax: disp_Disconnect();

Returns: None

Note

disp_Init() should be used to reinitialise the display.

disp_Init

This function is used to initialise the display. This is useful in a number of situations, however mainly for the uLCD-xx-PTU modules which have the ability to 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. New in v0.7 PmmC

Syntax: disp_Init();

Returns: None

disp_BlipPixelsFromCOMn

This function writes the number of pixels defined by the last disp_setGRAM() call to the display from the specified com port. The function returns once all pixels have been written.

New in v1.1 PmmC

Syntax: disp_BlitPixelsFromCOM0(); or disp_BlitPixelsFromCOM1(); or disp_BlitPixelsFromCOM2(); or disp_BlitPixelsFromCOM3();

Return: None

FAT16 File Functions

file_Error

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

File Error Codes

Error Code Value Description
FE_OK 0 IDE function succesded
FE_IDE_ERROR 1 IDE command execution error
FE_NOT_PRESENT 2 CARD not present
FE_INVALID_MBR 4 MBR sector invalid signature
FE_PARTITION_TYPE 3 WRONG partition type, not FAT16
FE_INVALID_BR 5 Boot Record invalid signature
FE_DISK_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_DISK_FULL 13 All clusters in the 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();

Returns: Error Code

Example

e := file_Error(); // File Error

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. Filename must be 8.3 format. Long Filenames are not supported. TESTPR~1.4XE for example.

Syntax: file_Count(filename);

Arguments Description
filename Name of the file(s) for the search (passed as a string). 8.3 Format

Returns: Number of files that match the criteria.

Example

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

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. Filename must be 8.3 format. Long Filenames are not supported. TESTPR~1.4XE for example.

Syntax: file_Dir(filename);

Arguments Description
filename Name of the file(s) for the search (passed as a string). 8.3 Format

Returns: Number of files that match the criteria.

Example

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

file_FindFirst

Returns true if at least 1 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. Filename must be 8.3 format. Long Filenames are not supported. TESTPR~1.4XE for example.

Syntax: file_FindFirst(fname);

Arguments Description
fname Name of the file(s) for the search (passed as a string). 8.3 Format

Return: 1 If at least one file exists that satisfies the criteria. 0 If no file satisfies the criteria.

Example

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

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 occurrence will have already been found. Note that the stream behaviour is the same as file_Dir.

Syntax: file_FindNext();

Returns: 1 if more files exist that satisfy the criteria set in the file_FindFirst(fname). 0 if no more files satisfy the criteria set in the file_FindFirst(fname)

Example

while ((file_FindNext()))
    filecount++;
wend

file_Exists

Tests for the existence of the file provided with the search key. Returns TRUE if found. fname must be 8.3 format, and therefore in capital letters. TESTPR~1.4XE for example.

Syntax: file_Exists(fname);

Arguments Description
fname Name of the file(s) for the search (passed as a string). 8.3 Format

Return: 1 if File found. 0 if File not found.

Example

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

file_Close

Returns TRUE if file closed, FALSE if not.

Syntax: file_Close();

Arguments Description
fname the file handle that was created by file_Open("fname") which is now used as reference (handle) for "fname" for further file functions such as in this function to close the file.

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

Example

res := file_Close(hndl);

file_Open

Returns handle if file exists. The file "handle" that is created is now used as reference for "filename" for further file functions such as file_Close(handle), 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 (i.e. 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);

Arguments Description
fname Name of the file(s) for the search (passed as a string). 8.3 Format
mode FILE_READ ('r'), FILE_WRITE ('w') or FILE_APPEND ('a')

Returns: Handle if file exists. Sets internal file error number accordingly (0 if no errors).

Example

Note

  • 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.
  • Beginning with the v4.0 PmmC 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_Read

Reads the number of bytes specified by size from the file referenced by handle into a destination memory buffer. Destination is always a word pointer, as you can only read into RAM which is word addressable. If destination is zero, data is read direct to GRAM window.

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

Arguments Description
destination Destination memory buffer. Word Pointer.
size Number of bytes to be read
handle The handle that references the file to be read.

Returns: Number of characters read.

Example

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

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, e.g.:- 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);

Arguments Description
handle The handle that references 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

Returns: TRUE if ok, usually ignored.

Example

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

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, e.g.:- 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);

Arguments Description
handle The handle that references 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.

Returns: TRUE if ok, usually ignored.

Example:

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

file_Tell

Reads the 32-bit file pointer and stores it into 2 variables, HiWord and LoWord

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

Arguments Description
handle The handle that references 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

Returns: TRUE if ok, usually ignored.

Example:

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

file_Write

Writes the number of bytes specified by "size" from the source buffer into the file referenced by "handle". The source buffer is a byte/string pointer, as it can be written from program memory which is always byte addressable.

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

Arguments Description
source Source memory buffer. Byte/String Pointer.
size Number of bytes to be written.
handle The handle that references the file to write.

Returns: The number of bytes written.

Example

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

file_Size

Reads the 32-bit file size and stores it into 2 variables, HiWord and LoWord.

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

Arguments Description
handle The handle that references the file.
HiWord Contains the upper 16bits of the file size.
LoWord Contains the lower 16bits of the file size.

Returns: TRUE if ok, usually ignored.

Example

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

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);

Arguments Description
x X-position of the image to be displayed
y Y-position of the image to be displayed
handle The handle that references the file containing the image(s)

Returns: A copy of the file_Error() error code

Example

file_Image(x, y, handle) ;

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(...).

All image headers must start on a sector boundary.

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);

Arguments 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 The handle that references the file to store the image(s)

Returns: Zero (0) if function 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

The image will be sector aligned.

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);

Arguments Description
char Data byte about to be written.
handle The handle that references the file to be written to.

Returns: True if function succeeded

Example

file_PutC('A', hndl);

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);

Arguments Description
handle The handle that reference the file.

Returns: The next char from the file.

Example

mychar := file_GetC(hndl) ;

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);

Arguments Description
word Date about to be written.
handle The handle that reference the file to be written to.

Returns: True if function succeeded.

Example

file_putW(0x1234, hndl);

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);

Arguments Description
handle The handle that reference to the file.

Returns: The next word in the file.

Example

myword := file_GetW(hndl);

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);

Arguments Description
source A pointer to the string to be written. Word Pointer.
handle The handle that references the file to be written to.

Returns: The number of the characters written (excluding the null terminator).

Example

file_PutS(mystring, hndl);

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. The file must be previously opened with 'r' (read) mode.

file_GetS(...) will stop reading when any of the following conditions are true:

a. It has read n-1 bytes (one character is reserved for the null-terminator) b. It encounters a newline character (a line-feed in the compilers tested here) c. It reaches the end of file d. A read error occurs.

The file must be previously opened with 'r' (read) mode.

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

Arguments Description
string Destination buffer, Word Pointer.
size The maximum number of bytes to be read from the file.
handle The handle that references the file.

Returns: The number of characters read from file (excluding the null terminator)

Example

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

Note

Only reads up to "size-1" characters into "string".

file_Erase

This function erases a file on the disk.

Syntax: file_Erase(fname);

Arguments Description
fname Name of the file to be erased.

Returns: True (1) if successful, False (0) otherwise.

Example

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

file_Rewind

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

Syntax: file_Rewind(handle);

Arguments Description
handle The handle that references the file.

Returns: True (1) if successful, False (0) otherwise.

Example

res := file_Rewind(hSource);

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 parents global or local memory space. The reason for this is that DATA statements and static strings are contained in the parents CODE segment, and cannot be accessed by the child process.

The callers stack is shared by the loaded function, however any global variables in the loaded function are private to that function.

Syntax: file_LoadFunction(fname.4XE);

Arguments Description
fname.4XE Name of the 4DGL application program that is about to be loaded into RAM.

Returns: A pointer to the memory allocation where the function has been loaded from file which can be then used as a function call.

Example

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

file_Run

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

If arglistptr is 0, no arguments are passed, else arglistptr points to an array, the first element being the number of additional elements in the array which contain the arguments.

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 file_Exec and file_LoadFunction for functions that can pass by reference.

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

Syntax: file_Run(fname.4XE, arglistptr);

Arguments Description
fname.4XE name 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.

Returns: The value from main 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
//===================================================================

file_Exec

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

Returns like a function, current program calling program is kept active and control returns to it.

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.

func 'main' in the called program accepts the arguments.

This function is similar to file_LoadFunction(...), however, the function argument list is passed by pointer, and the memory consumed by the function is released as soon as the function completes.

Syntax: file_Exec(fname.4XE, arglistptr);

Arguments 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 or 0 if no arguments.

Returns: The value from main 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

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
//===================================================================

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 

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();

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

file_Rename

This function renames a file on the disk.

Syntax: file_Rename(oldname, newname);

Argument Description
oldname Name of the file to be renamed
newname Name of the file to be used as the new name

Returns: 1 if successful, 0 otherwise.

Example

res := file_Rename("myfile.txt", "myfile.bak");

Note

If the function fails, the appropriate error number is set in file_Error() if an invalid filename is specified, otherwise the cause will be a missing old-name or a pre-existing newname.

file_SetDate

This function sets the modified date and time on an open file handle. The file must be closed at some future time for the date and time to be flushed to disk.

Syntax: file_SetDate(handle, year, month, day, hour, minute, second) ;

Arguments Description
handle The handle that reference the file.
year The year the file was updated 1980-2099.
month The month the file was updated 1 - 12.
day The day the file was updated 1 - 31.
hour The hour the file was updated 0 - 23.
minute The minute the file was uupdated 0 - 59.
second The second the file was updated 0 - 59.

Returns: 1 if successful, 0 otherwise (Handle not valid, or Date/Time not valid).

Example

res := file_SetDate(hndl, 2014, 9, 15, 23, 58, 00);

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

Flash Memory Functions

flash_Bank

Identifies which flash bank the code is running from.

Syntax: flash_Bank();

Returns: The FLASH bank that code is currently running from, 0-5.

0: Flashbank_0
1: Flashbank_1
2: Flashbank_2
3: Flashbank_3
4: Flashbank_4
5: Flashbank_5

Example:

var bank;
bank := flash_Bank();

flash_Blit1

Blit an image to a GRAM window from FLASH storage. Image is stored in a linear fashion to suit the GRAM mechanism, palette is 2 x 16bit colours

Syntax: flash_Blit1(bank, offset, count, pallete2colour);

Arguments Description
bank Flash bank to load the image from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
offset Offset in to the Flash bank where image is stored.
count Total number of pixel in the image.
pallete2colour An array of 2 elements being the colors for the two possible colour values.

Returns: Actual count (normally same as count, will be lower if bank bounds exceeded)

Example

var actual_count;
var pixels := 2000;
// pallete should be defined as an array of 2 elements
// of 16bit color values
actual_count := flash_Blit1(FLASHBANK_2, 10, pixels, pallete);

flash_Blit2

Blit an image to a GRAM window from FLASH storage. Image is stored in a linear fashion to suit the GRAM mechanism, palette is 4 x 16bit colours.

Syntax: flash_Blit2(bank, offset, count, pallete4colour);

Arguments Description
bank Flash bank to load the image from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
offset Offset in to the Flash bank where image is stored.
count Total number of pixel in the image.
pallete4colour An array of 4 elements being the colors for the four possible colour values.

Returns: Actual count (normally same as count, will be lower if bank bounds exceeded)

Examples

var actual_count;
var pixels := 2000;
// pallete should be defined as an array of 4 elements
// of 16bit color values
actual_count := flash_Blit2(FLASHBANK_2, 10, pixels, pallete);

flash_Blit4

Blit an image to a GRAM window from FLASH storage. Image is stored in a linear fashion to suit the GRAM mechanism, palette is 16 x 16bit colours.

Syntax: flash_Blit4(bank, offset, count, pallete16colour);

Arguments Description
bank Flash bank to load the image from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
offset Offset in to the Flash bank where image is stored.
count Total number of pixel in the image.
pallete16colour An array of 16 elements being the colors for the sixteen possible colour values.

Returns: Actual count (normally same as count, will be lower if bank bounds exceeded)

Examples

var actual_count;
var pixels := 2000;
// pallete should be defined as an array of 16 elements
// of 16bit color values
actual_count := flash_Blit4(FLASHBANK_2, 10, pixels, pallete);

flash_Blit8

Blit an image to a GRAM window from FLASH storage. Image is stored 8-bits per pixel (332 format) in a linear fashion to suit the GRAM mechanism.

Syntax: flash_Blit8(bank, offset, count);

Arguments Description
bank Flash bank to load the image from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
offset Offset in to the Flash bank where image is stored.
count Total number of pixel in the image.

Returns: Actual count (normally same as count, will be lower if bank bounds exceeded)

Examples

var actual_count;
var pixels := 2000;
actual_count := flash_Blit8(FLASHBANK_2, 10, pixels);

flash_Blit16

Blit an image to a GRAM window from FLASH storage. Image is stored 16bits per pixel (565) in a linear fashion to suit the GRAM mechanism.

Syntax: flash_Blit16(bank, offset, count);

Arguments Description
bank Flash bank to load the image from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
-1 or ALL to select all the banks.
offset Offset in to the Flash bank where image is stored.
count Total number of pixel in the image.

Returns: Actual count (normally same as count, will be lower if bank bounds exceeded)

Examples

var actual_count;
var pixels := 2000;
actual_count := flash_Blit16(FLASHBANK_2, 10, pixels);

flash_Copy

Copies bytes from any flash locations to a user buffer. If the bank is read protected, 0 bytes will be read.

Syntax: flash_Copy(bank, ptr, dest, count);

Arguments Description
bank Flash bank to copy the data from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
-1 or ALL to select all the banks.
ptr Pointer to a location in the selected flash bank.
dest Pointer to the destination. The destination pointer is word aligned.
count Count of bytes to be transferred.

Returns: The count of the bytes transfered.

Example

var count;
var dest[100];
count := flash_Copy(FLASHBANK_2, 10, dest, 100);

flash_EraseBank

This function should be used with extreme caution. The selected bank will be completely erased regardless of FLASH_WRITE_PROTECT status if the confirmation value is set to hex 0xDEAD. If confirmation is any other value, a protected bank will not be erased, and function will return with 0 If the destination bank is the same as the execution bank, the processor will reset upon completion of erase. If the "bank" argument is set to ALL (-1) and confirmation is set to 0xDEAD, FLASHBANK_0 through FLASHBANK_5 are cleared.

Note

  • Use with caution, this is a good way to 'clean up' the entire flash when starting new projects.
  • Reset processor if program is erasing itself, or the ALL bank option is selected.

Syntax: flash_EraseBank(bank, confirmation);

Arguments Description
bank Flash bank to be erased.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
-1 or ALL to select all the banks.
confirmation 0xDEAD: The command will erase regardless or FLASH_WRITE_PROTECT status. For any other value, a protected bank will not be erased.

Returns: True if the function succeeded.

Example

if (flash_EraeBank(FLASHBANK_2, 0))
    print("Erased successfully.");
else
    print("Failed");
endif

flash_Exec

This function calls the main function in another bank. The main program in FLASH retains all memory allocations (e.g. file buffers, memory allocated with mem_Alloc etc.)

The called bank returns like a function, program in current bank is kept active and control returns to it. All memory allocated in the called bank should be freed before returning, or it will be lost.

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.

func 'main' in the called bank accepts the arguments.

Syntax: flash_Exec(flashbank, arglistptr);

Arguments Description
flashbank Name of the bank to be executed.
arglistptr Pointer to the list of arguments to pass to the selected bank or 0 if no arguments.

Returns: The value from main in the called bank.

Example

flash_Exec(FLASHBANK_1, 0);

flash_GetByte

Reads a single byte from any flash location. If the bank is read protected, only the first 2 bytes can be read.

0x55, 0xAA are the header signature bytes of a valid program.

Syntax: flash_GetByte(bank, ptr);

Arguments Description
bank Flash bank to get the byte from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
ptr Pointer to a location in the selected flash bank.

Returns: The byte value from the location.

Example

var byte_val;
byte_val := flash_GetByte(FLASHBANK_2, 10);

flash_GetWord

Reads a single word from any flash location. If the bank is read protected, only the first word can be read.

0x55AA is the header signature word of a valid program.

Snytax: flash_GetWord(bank, ptr);

Arguments Description
bank Flash bank to get the word from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
ptr Pointer to a location in the selected flash bank.

Returns: The word value from the location.

Example

var word_val;
word_val := flash_GetWord(FLASHBANK_2, 10);

flash_LoadFile

Copies a file from uSD to the required flashbank. The destination bank cannot be the execution bank, or a bank that is write protected.

Sytax: flash_LoadFile (bank, filename);

Arguments Description
bank Flash bank to load the file from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
filename Name of the file to be copied (passed as a string).

Returns: True if the function succeeded

Example

if (flash_LoadFile(FLASHBANK_2, "FILE.TXT"))
    print("File loaded to bank.");
else
    print("Failed");
endif

flash_putstr

Prints an ASCIIZ string from the Flash bank. Works the same as putstr, however, the source of the ASCIIZ string is in FLASH storage. Output may be redirected with the to(..) function. Bit15 of ptr is assumed 0.

Syntax: flash_putstr(bank, ptr);

Arguments Description
bank Flash bank to load the String from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
ptr Pointer to a NULL terminated string in the selected flash bank.

Returns: True if function succeeds, usually ignored. 0 if bank is read protected.

Example

if (flash_ putstr(FLASHBANK_2, 10))
    print("Success");
else
    print("Failed");
endif

flash_Run

Restarts the processor, running code from the required flash bank. Bank may be a variable, or one of the pre-defined constants.

Syntax: flash_Run(bank);

Arguments Description
bank Flash bank to load the program from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5

Returns: This function should not return as it restarts the processor and jumps to the required bank.

If it does return, - 1 indicates incorrect/invalid bank number. - 2 indicates no valid program in the selected bank.

Example

var status;
status := flash_Run (FLASHBANK_2, 10)
if (status == -1 || status == -2);  
    print("Failed");
endif

flash_WriteBlock

Copies a 2kbyte buffer to the required flashbank in block 0-15. The destination bank cannot be an execution bank, or a program bank that is write-protected.

Syntax: flash_WriteBlock(sourceptr, bank, page);

Arguments Description
sourceptr Source buffer to load the 2K bytes of data from.
bank Flash bank to write the block to.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
page Page number 0-15. Each page is 2K. The address of each block is 0, 2048, 4096 etc, determined by the page number 0-15.

Returns: True if the function succeeded.

Example

var buffer[100] := "4D Labs Semiconductors";
var status;
if (status := flash_WriteBlock(buffer, FLASHBANK_2, 1))
    print("Successfully written to bank");
endif

flash_FunctionCall

Calls the Flashbank passing index "index" as the first parameter.

Other parameters "State", "&FunctionRam", "&FunctionDef", "&FunctionDef" are passed. The second two parameters are passed "as is", since the third parameter is normally in flash and one banks flash is not accessible from another

"FunctionArgCount" constants are copied into a RAM array and passed to the Function. "FunctionStringMap" is a bit array of the indexes containing single and multiple strings offset by 8. e.g. 0x0100 means parameter 8 is a single string, 0x0002 means paramter 9 is an array of strings with parameter 8 containing the count.

Syntax: flash_FunctionCall(bank, idx, state, FncRam, FncDef, FncArgCnt, FncStrMap);

Arguments Description
bank Flash bank to write the block to.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
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

Returns: 0 if successful.

Example

flash_FunctionCall(bank, idx, state, FncRam, FncDef, FncArgCnt, FncStrMap);

flash_LoadSPIflash

Copies a file from uSD to the required flashbank. The destination bank cannot be the execution bank, or a bank that is write protected.

Syntax: flash_LoadSPIflash (bank, hndl, idx);

Arguments Description
bank Flash bank to load the file from.
0 or FLASHBANK_0
1 or FLASHBANK_1
2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
hndl The handle that references the file.
index Index of the entry in the handle.

Returns: True if the function succeeded

Example

result := flash_LoadSPIflash (FLASHBANK_2, "TETRIS10.EXE"); // load the file from disk into FLASHBANK_2

Floating Point Functions

flt_ADD

Performs floating point addition (A+B) and returns the value in the result register.

Syntax: flt_ADD(&result, &floatA, &floatB);

Arguments Description
&result Points to float result register.
&floatA Points to the float value A.
&floatB Points to the float value B.

Arguments may be a pointer to a float variable or a numeric text string. A string argument is converted at run-time by calling flt_Val for a string argument.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;         //landscape orientation
flt_VAL(floatA, "3.3");             // Convert a string ("3.3") to a floatA
flt_ITOF(floatB, 4);                //Convert integer "4" to float

flt_ADD(result, floatA, floatB);
gfx_MoveTo(0,0);
print("add: ");
flt_PRINT(result,"%.6f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_SUB

Performs floating point Subtraction (A-B) and returns the value in the result register.

Syntax: flt_SUB(&result, &floatA, &floatB);

Arguments Description
&result Points to float result register.
&floatA Points to the float value A.
&floatB Points to the float value B.

Arguments may be a pointer to a float variable or a numeric text string. A string argument is converted at run-time by calling flt_Val for a string argument.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;         //landscape orientation
flt_VAL(floatA, "3.3");             // Convert a string ("3.3") to a floatA
flt_ITOF(floatB, 4);                //Convert integer "4" to float

flt_SUB(result, floatA, floatB);
print("subtract: ");
flt_PRINT(result,"%.6f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_MUL

Performs floating point Multiplication (A * B) and returns the value in the result register.

Syntax: flt_MUL(&result, &floatA, &floatB);

Arguments Description
&result Points to float result register.
&floatA Points to the float value A.
&floatB Points to the float value B.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var Voltage[20];                        // string to store computed voltage
                                        // values
func main()
    var Vsteps;                         // variable to store conversion
                                        // results
    gfx_ScreenMode(LANDSCAPE) ;         // landscape orientation
    pin_Set( PIN_AN, PA0);              // set pin PA0 to be used as an
                                        // analogue input, standard mode
    repeat
        Vsteps := pin_Read(PA0) ;       // 12 bit analogue 0 to 4095
        gfx_MoveTo(0, 0) ;              // move o rigin to point 0, 108,
                                        //printing will start from this point
        print("steps: ", [DEC4Z]Vsteps);// print the number of steps
        getVoltage(Vsteps);             // compute the equivalent voltage
                                        //value of Vsteps
                                        // result is converted to a string
                                        //and stored in global variable Voltage
        gfx_MoveTo(0, 15) ;
        print("voltage: ");
        putstr(Voltage);                // print the computed equivalent
                                        //voltage onscree n
    forever
endfunc

func getVoltage(var reading)
    var nsteps[2];
    var Vref[2];
    var Nsteps[2];
    var Factor[2];
    var Result[2];
    flt_VAL(Vref, "3.3");               //Convert a string ("3.3") to a float
                                        // (Vref)   
    flt_ITOF(Nsteps, 4095);             //Convert an integer (4095) to a float
                                        //(Nstep)
    flt_DIV(Factor, Vref, Nsteps);      //Float divistion, Factor = Vref/Nsteps
    flt_ITOF(nsteps, reading);          //Convert the integer 'reading' to a
                                        //float 'nsteps'
    flt_MUL(Result, nsteps, Fa ctor);   //Float multiplication,
                                        //Result = nsteps * Factor
    to(Voltage); flt_PRINT(Result, "%.6f");//print formatted Result
                                        //to the global variable Voltage
endfunc

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_DIV

Performs floating point Division (A/B) and returns the value in the result register.

Syntax: flt_DIV(&result, &floatA, &floatB);

Arguments Description
&result Points to float result register.
&floatA Points to the float value A.
&floatB Points to the float value B.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

see the example in flt_MUL()

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_POW

Raises A to power B and returns the result value in the result register.

Syntax: flt_POW(&result, &floatA, &floatB);

Arguments Description
&result Points to float result register.
&floatA Points to the float value to raise.
&floatB Points to the float value for power.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_ITOF(floatA, 2); // Convert integer "2" to float
flt_ITOF(floatB, 8); // Convert integer "4" to float

flt_POW(result, floatA, floatB);
print("power: ");
flt_PRINT(result,"%.6f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_ABS

Calculates absolute value of the floating point value.

Syntax: flt_ABS(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value to get the Absolute of.

Return: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE); // landscape orientation

flt_ITOF(floatA, 124); //Convert integer " 124" to float
flt_ABS(result, floatA);

print("absolute value: ");
flt_PRINT(result,"%.2f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_CEIL

Rounds value up to the integer value. Removes fractional part, rounding up correctly.

Syntax: flt_CEIL(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value to integerize up.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_VAL(floatA,"99.678"); //Convertstring "99.678" to float
flt_CEIL(result, floatA);

print(" result : ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_FLOOR

Rounds value down to the integer value. Removes fractional part, rounding down correctly.

Syntax: flt_FLOOR(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value to integerize down.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_VAL(floatA,"99.678"); //Convert string "99.678" to float
flt_FLOOR(result, floatA);

print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_SIN

Calculates the SINE of float value in radians and returns the value in the result register.

Syntax: flt_SIN(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value angle (in radians) to get the SINE of.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_VAL(floatA,"1.5708"); //Convert string "1.5708" to float
flt_SIN(result, floatA);

print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_COS

Calculates the COSINE of float value in radians and returns the value in the result register.

Syntax: flt_COS(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value angle (in radians) to get the COSINE of.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_VAL(floatA,"3.1416"); //Convert string "3.1416" to float
flt_COS(result, floatA);

print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2]

flt_TAN

Calculates the TANGENT of float value in radians and returns the value in the result register.

Syntax: flt_TAN(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value angle (in radians) to get the TANGENT of.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_VAL(floatA,"3.1416"); //Convert string "3.1416" to float
flt_TAN(result, floatA);

print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_ASIN

Calculates the ARCSINE of float value and returns the angle in radians in the result register.

Syntax: flt_ASIN(&result, &floatval);

Arguments Description
&result Points to float result register. Result is in radians.
&floatval Points to the float value to get the ARCSINE of.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_VAL(floatA,"0.1234"); //Convert string "0.1234" to float
flt_ASIN(result, floatA);

print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_ACOS

Calculates the ARCCOS of float value and returns the angle in radians in the result register.

Syntax: flt_ACOS(&result, &floatval);

Arguments Description
&result Points to float result register. Result is in radians.
&floatval Points to the float value to get the ARCCOS of.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_VAL(floatA,"0.1234"); //Convert string "0.1234" to float
flt_ACOS(result, floatA);

print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_ATAN

Calculates the ARCTAN of float value and returns the angle in radians in the result register.

Syntax: flt_ATAN(&result, &floatval);

Arguments Description
&result Points to float result register. Result is in radians.
&floatval Points to the float value to get the ARCTAN of.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;     //landscape orientation

flt_VAL(floatA,"0.1234");       //Convert string "0.1234" to float
flt_ATAN(result, floatA);
print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_EXP

Calculates the Exponent of float value and returns the value in the result register.

Syntax: flt_EXP(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value to get the Exponent of.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;     //landscape orientation

flt_ITOF(floatA, 5);            //convert integer 5 to float
flt_EXP(result, floatA);        //result = e^5
print("result: ");
flt_PRINT(result,"%.4f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_LOG

Calculates the Natural Log of float value and returns the value in the result register.

Syntax: flt_LOG(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value to get the natural Log of.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation

flt_VAL(floatA,"2.718282"); //Convert string "2.718282" to float
flt_LOG(result, floatA);
print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_SQR

Calculates the square root of float value and returns the value in the result register.

Syntax: flt_SQR(&result, &floatval);

Arguments Description
&result Points to float result register.
&floatval Points to the float value to get the square root of.

Returns: A pointer to the float result register or zero if error occurs. Carry and overflow are not affected.

Example

var floatA[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;         //landscape orientation

flt_VAL(floatA,"16.0");             //Convert string "16.0" to float
flt_SQR (result, floatA);
print("result: ");
flt_PRINT(result,"%.5f");
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_LT

Compare A to B and returns true if A < B.

Syntax: flt_LT(&floatA, &floatB);

Arguments Description
&floatA Points to the float value A.
&floarB Points to the float value B.

Returns: True if A < B, false otherwise.

Example

var floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;         //landscape orientation
flt_VAL(floatA,"16.0");             //Convert string "16.0" to float
flt_VAL(floatB,"17.5");             //Convert string "17.5" to float

if(flt_LT(floatA, floatB))
    print("floatA is less than floatB\n");
endif

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_EQ

Compare A to B and returns true if equal.

Syntax: flt_EQ(&floatA, &floatB);

Arguments Description
&floatA Points to the float value A.
&floarB Points to the float value B.

Returns: True if A == B, false otherwise.

Example

var floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;             //landscape orientation
flt_VAL(floatA,"16.0");                 //Convert string "16.0" to float
flt_VAL(floatB,"16.0");                 //Convert string "16.0" to float

if(flt_EQ(floatA, floatB))
    print("floatA is equal to floatB\n");
else
    print("floatA is not equal to floatB\n");
endif

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_NE

Compare A to B and returns true if A != B.

Syntax: flt_NE(&floatA, &floatB);

Arguments Description
&floatA Points to the float value A.
&floarB Points to the float value B.

Returns: True if A != B, false otherwise.

Example

var
floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;                 //landscape orientation
flt_VAL(floatA,"16.0");                     //Convert string "16.0" to float
flt_VAL(floatB,"100.0");                    //Convert string "100.0" to float

if(flt_NE(floatA, floatB))
    print("floatA is not equal to floatB\n");
else
    print("floatA is equal to floatB\n");
endif

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_GT

Compare A to B and returns true if A > B.

Syntax: flt_GT(&floatA, &floatB);

Arguments Description
&floatA Points to the float value A.
&floarB Points to the float value B.

Returns: True if A > B, false otherwise.

Example

var floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;                 //landscape orientation

flt_VAL(floatA,"16.0");                     //Convert string "16.0" to float
flt_VAL(floatB,"100.0");                    //Convert string "100.0" to float

if(flt_GT(floatB, floatA))
    print("floatB is greater than floatA\n");
endif

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_GE

Compare A to B and returns true if A >= B.

Syntax: flt_GE(&floatA, &floatB);

Arguments Description
&floatA Points to the float value A.
&floarB Points to the float value B.

Returns: True if A >=B, false otherwise.

Example

var floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;                         //landscape orientation

flt_VAL(floatA,"16.0");                             //Convert string "16.0" to float
flt_VAL(floatB,"100.0");                            //Convert string "100.0" to float
if(flt_GE(floatB, floatA))
    print("floatB is greater than or equal to floatA\n");
endif

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_LE

Compare A to B and returns true if A <= B.

Syntax: flt_LE(&floatA, &floatB);

Arguments Description
&floatA Points to the float value A.
&floarB Points to the float value B.

Returns: True if A <= B, false otherwise.

Example

var floatA[2], floatB[2], result[2];
gfx_ScreenMode(LANDSCAPE) ;                         //landscape orientation

flt_VAL(floatA,"160.0");                            //Convert string "160.0" to float
flt_VAL(floatB,"100.0");                            //Convert string "100.0" to float
if(flt_LE(floatB, floatA))
    print("floatB is less than or equal to floatA\n");
endif

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_SGN

Examines sign of the float value and returns 0 if sign is positive or value equals zero. Returns 16bit integer -1 if float sign is negative.

Syntax: flt_SGN(&floatval);

Arguments Description
&floatval Points to the float value to examine the sign of.

Returns: 16bit integer -1 if float sign is negative, or zero if positive.

Example

var floatA[2];
gfx_ScreenMode(LANDSCAPE) ;              //landscape orientation

flt_VAL(floatA,"-100.0");               //Convert string " 100.0" to float
if(flt_SGN(floatA) ==-1)
    print("floatA is a negative value\n");
endif

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_FTOI

Converts a floating point number to a 16bit integer. The floating point number is rounded up or down accordingly.

Syntax: flt_FTOI(&floatval);

Arguments Description
&floatval Points to the float value to be converted to integer.

Returns: The integer value of the float.

Example

var floatA[2], result;
gfx_ScreenMode(LANDSCAPE) ; //landscape orientation
flt_VAL(floatA," 123.4567"); //Convert string " 123.4567" to float

result := flt_FTOI(floatA);
print("result: ", result,"\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_ITOF

Converts a 16bit signed integer value to a signed floating point number.

Syntax: flt_ITOF(&fresult, var16);

Arguments Description
&fresult Points to float result variable.
var16 a 16bit signed integer variable.

Returns: The pointer to the float result, normally ignored.

Example

var floatA[2];
gfx_ScreenMode(LANDSCAPE) ;     //landscape orientation 
flt_ITOF(floatA, 100);          //convert integer 100 to float

print("float value: ");
flt_PRINT(floatA,"%.6f");       //prints "100.000000" 
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_UITOF

Converts a 16bit unsigned integer value to a positive floating point number.

Syntax: flt_UITOF(&fresult, uvar16);

Arguments Description
&fresult Points to float result variable.
uvar16 A 16bit unsigned integer variable.

Returns: The pointer to the float result.

Example

var floatA[2];
gfx_ScreenMode(LANDSCAPE) ;     //landscape orientation
flt_UITOF(floatA, 50000);       //convert integer 50000 to float

print("float value: ");
flt_PRINT(floatA,"%.2f");       //prints "50000.00"
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_LTOF

Converts a 32bit signed integer value to a signed floating point number.

Syntax: flt_LTOF(&fresult, var32);

Arguments Description
&fresult Points to float result variable.
var32 A 32bit (long) signed variable.

Returns: The pointer to the float result.

Example

var floatA[2], long Int[2]; 
gfx_ScreenMode(LANDSCAPE) ;         //landscape orientation
umul_1616( longInt, 500, 2000);    //multiply 500 by 2,000, store
                                    //result (1,000,000) in longInt
flt_LTOF(floatA, longInt);          //convert 1,000,000 to a float value
print("float value: ");
flt_PRINT(floatA,"%.2f");           //prints "1000000.00"
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_ULTOF

Converts a 32bit unsigned integer value to a positive floating point number.

Syntax: flt_ULTOF(&fresult, uvar32);

Arguments Description
&fresult Points to float result variable.
uvar32 A 32bit (long) unsigned variable.

Returns: The pointer to the float result.

Example

var floatA[2], longInt[2], ptr;
gfx_ScreenMode(LANDSCAPE) ;             //landscape orientation
umul_1616(longInt, 50000, 50000);       //multiply 50,000 by 50,000
                                        //store result (2,500,000,000) in longInt
ptr := str_Ptr(longInt);                //create a string pointer for longInt
print("unsigned 32bit value: ");
str_Printf(&ptr,"%lu");                 //print the value of longInt
print("\n");

flt_ULTOF(floatA, longInt);             //convert longInt to a float value
print("float value: ");
flt_PRINT(floatA,"%.2f");               //prints "2500000000.00"
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_VAL

Converts the number string to a valid float value. Carry and overflow are not affected.

Syntax: flt_VAL(&fresult, numstring);

Arguments Description
&fresult Points to float result variable.
numstring A string constant or string variable that holds valid floating point number.The string argument can be a string constant, a pointer to a string variable, or a pointer to a data statement.The string may be a float, or a hex or binary integer value (no decimal point allowed). For hex or binary, the number is preceeded with 0x or 0b.

Returns: The pointer to the float result.

Example

See the example in section flt_ADD.

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_PRINT

Prints a floating point value in a set string format.

The string argument can be a string constant, a pointer to a string variable, or a pointer to a data statement. If it is zero or an empty string, the number is automatically formatted for the best presentation. The format string is similar to the C language, but only a single '%' may be used to print a single variable.

To format the output, refer to the following syntax:

format

flag Meaning
- Left justify.
+ Always display Sign.
space Display space if there is no sign.
0 Pad with leading zeros.

width specifies the number of characters used in total to display the value. Notice that the width includes the decimal point, and a - sign if there is one.

precision indicates the number of characters used after the decimal point.

specifier Meaning
f Float
e or E Float exponential Format.

Syntax: flt_PRINT(&fvalue, formatstring);

Arguments Description
&fresult Points to float result variable.
formatString zero, null string, of valid format string.

Returns: ‘0’ if successful.

Example

var floatA[2];
gfx_ScreenMode(LANDSCAPE) ;         //landscape orientation 
flt_ITOF(floatA, 5000);             //convert integer 5000 to float

print("float value: ");
print("\n");

//specify format 
print("         %f: ");
flt_PRINT(floatA,"%f");             //prints "5000.000000" 
                                    //default precision is six 0's after the decimal point
print("\n");

print("         %e: ");
flt_PRINT(floatA,"%e");             //prints "5.000000e+03" (float exponential format) 
                                    //default precision is six 0's after the decimal point
print("\n");

//specify precision
print("         %.2f: "); 
flt_PRINT(floatA,"%.2f");           //prints "5000.00"
print("\n");

print("         %.1e: "); 
flt_PRINT(floatA,"%.1e");           //prints "5.0e+03" (float exponential format)
print("\n");

//specify width and precision 
print("         %10.2f: ");
flt_PRINT(floatA,"%10.2f");         //prints " 5000.00", 
                                    //a total of 10 characters (including the decimal point)
                                    //left padded with 3 space characters 
print("\n");

print("     %10.2e: ");
flt_PRINT(floatA,"%10.2e");         //prints " 5.00e+03", 
                                    //a total of 10 characters (including the decimal point)
                                    //left padded with 2 space characters 
print("\n");

//specify flag, width, and precision
print(" %010.2f: "); 
flt_PRINT(floatA,"%010.2f");        //prints "0005000.00",
                                    //a total of 10 characters (including the decimal point) 
                                    //left padded with 3 0's
print("\n");

print(" %010.2e: ");
flt_PRINT(floatA,"%010.2e");        //prints "005.00e+03", 
                                    //a total of 10 characters (including the decimal point)
                                    //left padded with 2 0's 
print("\n");


print(" %+10.2f: "); 
flt_PRINT(floatA,"%+10.2f");        //prints " +5000.00",
                                    //a total of 10 characters (including the decimal point) 
                                    //sign is always displayed
                                    //left padded with 2 space characters 
print("\n");

print("%+010.2f: ");
flt_PRINT(floatA,"%+010.2f");       //prints "+005000.00", 
                                    //a total of 10 characters (including the decimal point)
                                    //left padded with 2 0's
print("\n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

flt_PRINTxy

Prints a floating point value in a set string format at the specified position.

The string argument can be a string constant, a pointer to a string variable, or a pointer to a data statement. If it is zero or an empty string, the number is automatically formatted for the best presentation. The format string is similar to the C language, but only a single '%' may be used to print a single variable.

For more information on the syntax of the format string, refer to section flt_PRINT (&fvalue, formatstring).

Syntax: flt_PRINTxy(x, y, &fvalue, formatstring);

Arguments Description
x The x position to start printing the number in.
y The y position to start printing the number in.
&fresult Points to float result variable.
formatstring zero, null string, of valid format string

Returns: ‘0’ if successfull.

Example

var floatA[2];
gfx_ScreenMode(LANDSCAPE) ;         //landscape orientation
flt_ITOF(floatA, 5000);             //convert integer 5000 to float

print("float value: ");
print("\n");

//specify format
gfx_MoveTo(36, 16);                 //move cursor to 36,16
txt_FGcolour(YELLOW);               //set text foreground color to yellow
print("%f: ");
txt_FGcolour(LIME);                 //set text foreground color to lime
flt_PRINTxy(68,16,floatA,"%f");     //prints "5000.000000" at 68,16
print("\n");

gfx_MoveTo(36, 32);                 //move cursor to 36,32
txt_FGcolour(YELLOW);               //set text foreground color to yellow
print("%e: ");
txt_FGcolour(LIME);                 //set text foreground color to lime
flt_PRINTxy(68,32,floatA,"%e");     //prints "5.000000e+03" at 68,32
print("\n");

//specify precision
gfx_MoveTo(20, 52);                 //move cursor to 20,52
txt_FGcolour(YELLOW);               //set text foreground color to yellow
print("%.2f: ");
txt_FGcolour(LIME);//set text foreground color to lime
flt_PRINTxy(68, 52, floatA,"%.2f");//prints "5000.00" at 68,52
print("\n");

gfx_MoveTo(20, 72);                 //move cursor to 20,72
txt_FGcolour(YELLOW);               //set text foreground color to yellow
print("%.1e: ");
txt_FGcolour(LIME);                 //set text foreground color to lime
flt_PRINTxy(68, 72, floatA,"%.1e"); //prints "5.0e+03" at 68,72
print( n");

Note

A float variable is a 2 word array, e.g. var myfloat[2].

General Purpose Functions

pause

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

Syntax: pause(time);

Arguments Description
time A value specifying the delay time in milliseconds.

Returns: None

Example

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

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 in result, else result is set to zero. 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 returned with zero.

Syntax: lookup8(key, byteConstList);

Arguments Description
key A byte value to search for in a fixed list of constants. The key argument can be a variable, array element, expression or constant.
byteConstList A comma separated list of constants and strings to be matched against key.

Returns: The index of the matching constant, otherwise zero.

Example

func main()
    var key, 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. The lookup8(...) functions 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 where ever 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, e.g. :

#constant HEXVALUES $"0123456789ABCDEF"

lookup16

Search a list of 16-bit constant values for a match with a search value key. If found, the index of the matching constant is returned in result, else result is set to zero. 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 returned with zero.

Arguments Description
key A byte value to search for in a fixed list of constants. The key argument can be a variable, array element, expression or constant.
wordConstList A comma separated list of constants to be matched against key.

Returns: The index of the matching constant, otherwise zero

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,

    if(r)
        print("\nSearch value 5000 nfound at index ", r);
    else
        putstr("\nValue not found");
    endif
        print("\nOk"); // all done
    repeat forever
endfunc

Note

The lookup16(...) functions offer a versatile way for returning an index for a given value. This is very useful for parameter input checking and where ever you need to check the validity of certain values. The entire search list field can be replaced with a single name by using the $ operator in constant, e.g.:

#constant LEGALVALS $5,10,20,50,100,200,500,1000,2000,5000,10000

GPIO Functions

pin_Set

There are pre-defined constants for mode and pin:

4D Pin Name (Predefined) PA0 PA1 PA2 PA3 PA4 PA5 PA6 PA7 PA8 PA9 PA10 PA11 PA12 PA13 PA14 PA15
DIABLO-16 Pin Number pin61 pin62 pin63 pin64 pin46 pin49 pin50 pin51 pin52 pin53 pin43 pin44 pin31 pin32 pin37 pin36
H1 pin Number pin 1 pin 3 pin 5 pin 7 pin 29 pin 27 pin 25 pin 23 pin 21 pin 19 pin 8 pin 6 pin 28 pin 30 pin 24 pin 26
4D Mode (Predefined) mode PA0 PA1 PA2 PA3 PA4 PA5 PA6 PA7 PA8 PA9 PA10 PA11 PA12 PA13 PA14 PA15
PIN_INP 0 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
PIN_INP_HI 1 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
PIN_INP_LO 2 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
PIN_OUT 3 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
PIN_OUT_OD 4 No No No No Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
PIN_AN 5 Yes Yes Yes Yes No No No No No No No No No No No No
PIN_ANAVG 6 Yes Yes Yes Yes No No No No No No No No No No No No

Syntax: pin_Set(mode, pin);

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

Returns: None

Example

pin_Set(PIN _INP , PA0 );       // set PA0 to be an in tput
pin_Set(PIN_AN , PA1 );         // set PA 1 to be an Analog input
pin_Set(PIN _INP_HI, PA4 );     // set PA4 to be an in tput with int. pullup
pin_Set(PIN_INP_LO, PA5);       // set PA5 to be an in tput with int. pulldown
pin_Set(PIN _OUT, PA10 );       // set PA10 to be used as an ou tput
pin_Set(PIN_OUT_OD, PA 14);     // set PA 1 4 to be an Open Drain Output
pin_Set(PIN _ANAVG, PA0 );      // set PA0 to be an Averaging Analog Input

Note

If using PIN_AN or PIN_ANAVG via the pin_Read() function, then if Touch is enabled this function should be called no more than once per millisecond, otherwise touch behaviour could be erratic.

pin_HI

Set any pin to the HI state, pin is automatically made an output. Pullup, Pulldown, and change notification will be disabled for the selected pin.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: pin_HI(pin);

Arguments Description
pin A value (usually a constant) specifying the pin number or a predefined pin name.

Returns: a Logic 1 (0x0001) if the pin number is legal.

Example

pin_ HI PA7 );  // output a Logic 1 on PA7 pin

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

pin_LO

Set any pin to the LOW state, pin is automatically made an output. Pullup, Pulldown, and change notification will be disabled for the selected pin.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: pin_LO(pin);

Arguments Description
pin A value (usually a constant) specifying the pin number or a predefined pin name.

Returns: A Logic 1 (0x0001) if the pin number is legal.

Example

pin_ LO (PA7);  // output a Logic 0 on PA7 pin

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

pin_Val

Outputs a logic state on a pin depending on the value of bit 0 of a variable. The pin is automatically made an output. Pullup, Pulldown, and change notification will be disabled for the selected pins.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: pin_Val(pin, value);

Arguments Description
pin A value (usually a constant) specifying the pin number or a predefined pin name.
value Bit 0 of value.

Returns: A Logic 1 (0x0001) if the pin number is legal.

Example

temp := 3
pin_Val(PA4 , temp); // output a Logic 3 on the PA 4 pin

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

pin_Read

Read a pin in various ways. If the pin is set to an input, read the state of the input pin. If set to an output, read the state of the output latch. If set to analogue, read the 12 bit analogue value.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

When using PIN_AN or PIN_ANAVG via the pin_Set command, then please note: If Touch is enabled this function should be called no more than once per millisecond, otherwise touch behaviour could be erratic.

PIN_AN > 15,000 reads/second
PIN_ANAVG ~3,000 reads/second

Syntax: pin_Read(pin);

Arguments Description
pin A value (usually a constant) specifying the pin number or a predefined pin name.

Returns: State of the pin a Logic 0 (0x0001) or 1 (0x0001) if the pin is set to digital input. State of the output latch, a Logic 0 (0x0001) or 1 (0x0001) if the pin is set to digital output. 12 bit analogue value if the pin is set to an analogue pin.

Example

pin_Set(PIN _AN , PA1 );        // set PA 1 to be used as an Analog input
ANval := pin_Read(PA1);         // Read the 12bit analog input

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

bus_Read

Read the 16-bit port regardless of pin configurations. If a pin is configured as input or analogue, 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.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: bus_Read();

Returns: The 16-bit value of the bus.

Example

var1 := bus_Read();     //Read the 16bit value off PA0 PA15 pins

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

bus_Read8

Returns the state of the bus as an 8bit value in to the lower byte of the assigned variable.

The BUS_RD pin set to LO, then, after a settling delay of approx 50nsec, the BUS is read into the lower 8-bits of the assigned variable (the upper 8-bits being set to 0) the BUS_RD pin is then set back to a HI level.

bus_Read8

Syntax: bus_Read8();

Returns: The state of the 8-bit bus as an 8bit value.

Example

var1 := bus_Read8();

The lower byte of var1 will get loaded with the state of the bus.

Note

The BUS_RD pin must be preset to the desired output state must the bus pins to ensure BUS write integrity.

BUS_RD is PA3

The 8-bit BUS pins 0 to 7 are PA4 to PA11.

bus_Write8

The lower 8-bits of arg1 are placed on the BUS, then, after a settling delay of approx 50nsec, the BUS_WR pin is strobed LO for approx 50nsec then set back HI. The upper 8-bits of arg1 are ignored.

bus_Write8

Syntax: bus_Write8(value);

Arguments Description
Value The lower 8-bits of value are sent to the 8-bit bus.

Returns: None

Example

var data1 ;
data1 := 0x05;
bus_Write8(data1);

Note

The BUS_WR pin pin must be preset to the desired output state as must the bus pins to ensure BUS write integrity.

BUS_WR is PA2

The 8-bit BUS pins 0 to 7 are PA4 to PA11

bus_SetPins

Any '1' bits in "value" sets the corresponding port pin to an output and forces its state to a '1'. The state of its previous open drain configuration is not altered. Any ‘0’ bits in "value" will not affect the pin. pullup, pulldown, and change notification will be disabled for the selected pins.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: bus_SetPins(value);

Arguments Description
Value A value (usually a constant) specifying the pin number. Bit 0 corresponds to PA0 through to bit9 which corresponds to PA9.

Returns: None

Example

var arg1;
arg1 := 0b0011010;          // set desired mask
bus_SetPins(arg1);          // set PA 1, PA3 and PA4 to output, making them HI

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

bus_ClearPins

Any '1' bits in "value" sets the corresponding port pin to an output and forces its state to a '0'. The state of its previous open drain configuration is not altered. Any ‘0’ bits in "value" will not affect the pin. pullup, pulldown, and change notification will be disable for the selected pins.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: bus_ClearPins(value);

Arguments Description
Value A value (usually a constant) specifying the pin number. Bit 0 corresponds to PA0 through to bit9 which corresponds to PA9.

Returns: None

Example

var arg1;
arg1 := M_PA1 | M_PA3 | M_PA4 ;     // set desired mask (same as
bus_ClearPins(arg1);                // set PA 1, PA3 and PA4 to output, making them LO

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

bus_SetChangeInterrupt

Any '1' bits in "portmask" marks that pin to generate an interrupt on change. A level change on that pin will cause "function" to be executed. If "function" is zero, the display may be put into sleep mode, and any change will cause a wakeup reset. Wakeup will always re-start code running in FLASHBANK_0 Bit 0 corresponds to PA0 through to bit15 which corresponds to PA15

Once armed, "function" will only be executed once, it is necessary to re-arm for any further events.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: bus_SetChangeInterrupt(function, portmask);

Arguments Description
function Event Function to be queued when an interrupt occurs.
portmask "portmask" marks that pin to generate an interrupt on change. A value (usually a constant) specifying the pin number or a predefined pin name.

Returns: The current state of the pins that are selected in "portmask". This can be saved and later used in "function" to see which pin(s) actually changed.

Example

bus_SetChangeInterrupt(scanKeypad, M_PA4 | M_PA5 | M_PA6 | M_PA7); // set PA4 to PA7 to interrupt on change

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

Qencoder1

Connect a quadrature encoder to a pair of pins, using the predefined 4D Pin Names in the table below, and the PHApin and PHBpin arguments in this function.

It is necessary to configure the pins first, depending on your requirements, e.g.

pin_Set(PIN_INP_HI, PA4); // PA4 as input, with pullup to Vcc

or maybe

pin_Set(PIN_INP, PA4); // PA4 as input, no pullup or pulldown

The position counter and delta can be read or written to at any time with peekW and pokeW using the following constants:

  • QEN1_COUNTER_LO
  • QEN1_COUNTER_HI
  • QEN1_DELTA (QEN1_DELTA is reset to 0 once it has been read.)
4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 No
PA15 36 No

Syntax: Qencoder1(PHApin, PHBpin, mode);

Arguments Description
PHApin Phase A input pin, 4D Pin Name reference – see table above.
PHBpin Phase B input pin, 4D Pin Name reference – see table above.
mode Not currently used, set to 0 only.

Returns: None

Example

var qen1Delta;
pin_Set(PIN_INP_HI, PA4);               // Set PA4 to be Input with Pullup 
pin_Set(PIN_INP_HI, PA5);               // Set PA5 to be Input with Pullup
Qencoder1(PA4, PA5, 0);                 // connect PA4 and PA5 pins to quadrature encoder module #1
qen1Delta := peekW(QEN1_DELTA);

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

Qencoder1Reset

Resets the Counters and Delta values for Encoder #1.

  • QEN1_COUNTER_LO is reset to zero.
  • QEN1_COUNTER_HI is reset to zero.
  • QEN1_DELTA is reset to zero.

Syntax: Qencoder1Reset();

Returns: None

Example

Qencoder1Reset(); // Reset the Counter and Delta values

Qencoder2

Connect a quadrature encoder to a pair of pins, using the predefined 4D Pin Names in the table below, and the PHApin and PHBpin arguments in this function.

It is necessary to configure the pins first, depending on your requirements, e.g.

pin_Set(PIN_INP_HI, PA 8 // PA 8 as input, with pullup to Vcc

or maybe

pin_Set(PIN_INP, PA 9 // PA 9 as input, no pullup or pulldown

The position counter and delta can be read or written to at any time with peekW and pokeW using the following constants:

  • QEN2_COUNTER_LO
  • QEN2_COUNTER_HI
  • QEN2_DELTA (QEN2_DELTA is reset to 0 once it has been read)
4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 No
PA15 36 No

Syntax: Qencoder2(PHApin, PHBpin, mode);

Arguments Description
PHApin Phase A input pin, 4D Pin Name reference – see table below.
PHBpin Phase B input pin, 4D Pin Name reference – see table below.
mode Not currently used, set to 0 only.

Returns: None

Example

var qen2Delta;
pin_Set(PIN_INP, PA8);          // Set PA8 to be Input pin_Set(PIN_INP, PA9); // Set PA9 to be Input
Qencoder2(PA8, PA9, 0);         // connect PA8 and PA9 pins to quadrature encoder module #2
pokeW(QEN2_COUNTER_HI) := 12;   // some ‘preset value’

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

Qencoder2Reset

Resets the Counters and Delta values for Encoder #2.

  • QEN2_COUNTER_LO is reset to zero.
  • QEN2_COUNTER_HI is reset to zero.
  • QEN2_DELTA is reset to zero.

Syntax: Qencoder2Reset();

Returns: None

Example

Qencoder2Reset(); // Reset the Counter and Delta values

pwm_Init

This PWM function enables a PWM output on the desired pin, based on the availability set out by the table below. Set the pin using the predefined 4D Pin Name into the pin argument, and select its mode and value, which are determined by:

PWM Mode Description
PWM_OFF Turn off the PWM (pin is left as Output)
PWM_PLAIN Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is ~70kHz. A value of 1 is not valid.
PWM_SERVO Servo PWM has a value which is between 100 and 200. This corresponds to 1.00 to 2.00ms. Please note values from 0 to 600 are valid (0-6ms) but should be used with caution. Repitition Rate is ~50Hz or 20ms.
PWN_BINARY Binary PWM which value is a number between 0 and 1024. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is ~68kHz. A value of 1 is not valid.
PWM_625HZ Plain PWM which corresponds to 62.5Hz, which takes a value from 0 to 160.
PWM_200HZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_500HZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_1KHZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_5KHZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_10KHZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_15KHZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_20KHZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_25KHZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_30KHZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.
PWM_35KHZ Plain PWM which value is a number between 0 and 1000. This corresponds to a 0.0 to 100.0% duty cycle. Raw Frequency is as specified.

The pwm_Init is non-blocking and the pwm continues until turned off.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 No
PA1 62 No
PA2 63 No
PA3 64 No
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 No
PA11 44 No
PA12 31 No
PA13 32 No
PA14 37 No
PA15 36 No

Syntax: pwm_Init(pin, mode, value);

Arguments Description
pin 4D Pin Name to enable the PWM on.
mode Modes for the PWM, see description below.
value Value determines Duty Cycle/Time Base depending on Mode, see below.

Returns: TRUE if the pin number is legal, usually ignored.

Example

pwm_Init(PA4, PWM_PLAIN, 676); //Sets Plain PWM of 67.7% on PA4 

pwm_Init(PA5, PWM_625HZ, 80); //Sets 62.5Hz PWM with 50% duty cycle 

pwm_Init(PA6, PWM_500HZ, 500); //Sets 500Hz PWM with 50% duty cycle

pin_Pulseout

This function will invert the state of an output for "value" milliseconds.

pin_Pulseout is a non-Blocking function, that is, code execution may continue while a pulse is occurring, and pulses can occur on multiple pins simultaneously.

pin_PulseoutB is a Blocking function, where program execution is suspended during pulse.

If not already an output, pin is automatically made a push/pull output, and the last state of its output latch will determine pulse polarity.

Its open drain state is not altered if the pin was already an output.

If pulseout is called while pulseout is still active, the pulse timer will simply be updated with the new "value" and the pulse will continue with the extended value.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 No
PA11 44 No
PA12 31 No
PA13 32 No
PA14 37 No
PA15 36 No

Syntax: pin_Pulseout(pin, value); or pin_PulseoutB(pin, value);

Arguments Description
pin 4D predefined Pin Name to enable Pulseout on.
value Length of pulse in milliseconds.

Returns: TRUE if the pin number is legal (usually ignored).

Example

pin_Pulseout(PA3, 105);     // create a Hi Pulse of 105ms on PA3
 
pin_set(PIN_OUT, PA1);      // set PA1 as an Output
pin_HI(PA1);                // set PA1 to output HI 
pin_Pulseout(PA1, 50);      // create a Lo pulse of 50ms on PA1

pin_Counter

Connect a counter to a pin to count transistions, and optionally call an event function when the 16bit counter wraps from 0xFFFF to zero.

The counter can be read or written to at any time with peekW and pokeW, therefore, the count may be set to 0xFFF0 for example, so that user function "OVFfuction" will be called after 16 pulses.

If "OVFfunction" is set to zero, only the counter will increment, and simply wrap back to zero from 0xFFFF. If "OVFfunction" points to a user function, wnen the event fires, pin_Counter will be disabled, and will need to be re-armed (ie '1shot' operation)

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 No
PA1 62 No
PA2 63 No
PA3 64 No
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 No
PA11 44 No
PA12 31 No
PA13 32 No
PA14 37 No
PA15 36 No

The pin may be configured as an input or output, the function behaves the same.

All six pin counters may be active simultaneously, and the maximum frequency of pin transitions should not exceed a few Khz in mode 1 and 2 and are usually used for simple process control counting.

Pin Counter MODE Description
COUNT_OFF (0) Disconnect the counter from the pin, "OVFfunction" is therefore ignored, and counting is inhibited.
COUNT_RISE (1) increment counter on every rising edge.
COUNT_FALL (2) increment on every falling edge.
COUNT_EDGE (3) increment on every rising and falling edge.

Syntax: pin_Counter(pin, mode, OVFfunction);

Arguments Description
pin 4D predefined Pin Name to enable pin counter on, see table below.
mode Counter mode, see table below.
OVFfunction Event function to be queued on overflow of counter.

Returns: None

Example

func main()
    pin_Set(PIN_INP, PA4);                      // external start event 
    repeat                                      // main loop
        if(pin_Read(PA4)) 
            pin_Counter(PA2, COUNT_RISE, userFunc);
        endif                                   
        // user code here
    forever 
endfunc

func userFunc()
    print("Hello World"); 
endfunc

ana_HS

Collects "samples" samples at "rate" frequency for 0 to 4 analogue pins and calls "userFunction" when done.

"rate" is samples represented as 1/100 samples per second, up to 250,000 reads/second across 1-4 channels. For example if you wish to sample at 5000 samples per second, you would set rate to be 50 as 5000 * 1/100 = 50.

Any unused IOx pins should have their buffer addresses (i.e. IO4buf) set to 0

For performance reasons samples are taken in chunks of 32, thus if you request 33 samples there will be a delay of 31 samples before "userFunction" is called

Syntax: ana_HS(rate, samples, IO1buf, IO2buf, IO3buf, IO4buf, userFunction);

Arguments Description
rate Number of samples per second, see rate commend below.
samples Number of samples to collect per analog channel.
IO1buf Buffer Address for first Analog Channel.
OI2buf Buffer Address for second Analog Channel.
IO3buf Buffer Address for third Analog Channel.
IO4buf Buffer Address for forth Analog Channel.
userFunction Function to call once all samples have been collected.

Returns: None

Example

var x[100];         // Buffer for IO1buf
var b[100];         // Buffer for IO2buf 
var c[100];         // Buffer for IO3buf

// 1000 samples a second, 10000 samples to be collected from 3 channels
ana_HS(1000, 10, a, b, c, 0, myFunc);

func myFunc()       
    //do something once samples collected
endfunc

Note

If Touch is enabled this function should be called no more than once per millisecond, otherwise touch behaviour could be erratic.

pin_PulseoutCount

This function will invert the state of an output at a "freq" freuency "count" times. This is a non-Blocking function, that is, code execution may continue while a pulse is occuring, and pulses can occur on multiple pins simultaneously. A function can be specified that will be called when all the pulses have been output. A maximum of 3 pulseoutCount activities can be active at any one point.

If not already an output, pin is automatically made a push/pull output, and the last state of its output latch will determine pulse polarity.

Its open drain state is not altered if the pin was already an output.

If pulseoutCount is called while pulseoutCount is active, the pulse counter will simply have the new count value added to it.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 No
PA1 62 No
PA2 63 No
PA3 64 No
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 No
PA11 44 No
PA12 31 No
PA13 32 No
PA14 37 No
PA15 36 No

Syntax: pin_PulseoutCount(pin, frequency, count, function);

Arguments Description
pin 4D predefined Pin Name to enable PulseoutCount on.
frequency The frequency to pulse the pin at (minimum 10Hz).
count The number of times to pulse the specified pin.
function Address of a function to be called at completion.

Returns: TRUE if the pin number is legal and the frequency is at least 10Hz and the maximum number of 3 simultaneous pulseoutCount pins is not exceeded.

Example

func pulseCompleted()
    // do something
endfunc

func main()

    pin_set(PIN_OUT, PA4);
    // ... user setup

    // start an alternating pulse w/ 5000 inversions at 100Hz
    pin_PulseoutCount(PA4, 100, 5000, pulseCompleted);
    // runs pulseCompleted when done
    // change pulseCompleted to 0 if not required

    repeat
        // ... user loop
    forever
endfunc

OW_Reset

Resets a ONEWIRE device and returns the status.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: OW_Reset(pin);

Arguments Description
pin 4D predefined Pin Name, see table above.

Returns: Reset, and returns the status of the ONEWIRE device, 0 = ACK, 1 = No Activity.

Example

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

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

OW_Read

Reads the 8-bit value from a 1-Wire devices register. (refer to Dallas 1wired documentation for further information)

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 No
PA15 36 No

Syntax: OW_Read(pin);

Arguments Description
pin 4D predefined Pin Name, see table above.

Returns: A word holding the lower 8-bits contain data bits received from the 1-Wire device.

Example

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

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

OW_Read9

Reads the 9 or more bit value from a 1-Wire devices register. (refer to Dallas 1wired documentation for further information)

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 No
PA15 36 No

Syntax: OW_Read9(pin);

Arguments Description
pin 4D predefined Pin Name, see table above.

Returns: A word holding 9 or more data bits received from the 1-Wire device.

Example

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

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

OW_Write

Writes the 8-bit data to 1-Wire devices register. (refer to Dallas 1wired documentation for further information)

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 No
PA15 36 No

Syntax: OW_Write(pin, data);

Arguments Description
pin 4D predefined Pin Name, see table above.
data The lower 8-bits of data are sent to the 1-Wire device.

Returns: None

Example

//===================================================================
// For this demo to work, a Dallas DS18B20 must be connected to
// PA0 AND POWERED FROM 3.3 to 5V.
// DS18B20 pin1 = Gnd / pin2 = data in/out / pin 3 = + 3.3 v
// Refer to the Dallas DS18B20 for further information
//===================================================================

func main()
    var temp_buf ;
    pause(1000);
    txt_MoveCursor(0,0);
    if(OW _Reset(PA0))                      // initialise and test
        print("No device detected");
        while(1);
    endif

    repeat
        txt_MoveCursor(0, 0);
        print ("result=", OW_Reset(PA0));
        OW_Write(PA0, 0xcc);                // sk ip ROM
        OW_Write(PA0, 0x44);                // start conversion
        OW_Reset(PA0);                      // reset
        OW_Write(PA0, 0xcc);                // skip ROM
        OW_Write(PA0, 0xBE);                // get temperature
        temp_buf := OW_Read(PA0);
        temp_buf += (OW_Read(PA0) << 8);
        txt_MoveCursor(1, 0);
        print ("temp_buf=0x", [HEX4] temp_buf);
    forever
endfunc

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

NP_Write

Writes a string of pixels to the NeoPixel array connected to the specified I/O Pin.

Due to the critical timing requirements of the NeoPixel, any interrupts should be stopped, or otherwise circumvented before this command is issued. Internally, the system Timer is disabled during this command.

Comms Interrupts should also be disabled by the user, otherwise errors may occur. A suitable workaround is to repeat the NP_Write until com_Count does not change during its execution.

Comms TX Buffers, if used, should be held.

Audio should be stopped or paused.

4D Pin Name (Predefined) DIABLO-16 Pin Number Availability
PA0 61 Yes
PA1 62 Yes
PA2 63 Yes
PA3 64 Yes
PA4 46 Yes
PA5 49 Yes
PA6 50 Yes
PA7 51 Yes
PA8 55 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note)
PA13 32 Yes (See Note)
PA14 37 Yes
PA15 36 Yes

Syntax: NP_Write(pin, data, size, Options, RepeatFirst, Repeat, RepeatLast);

Arguments Description
pin 4D predefined Pin Name, see table above.
data The address of the data to be sent.
size The size of the data to be sent, in Pixels.
Options The format of the data pixels, NP_565, NP_RGB or NP_XRGB.
RepeatFirst Number of times to repeat the first colour (0 means first colour is not considered 'special').
Repeat Number of times to repeat the colours between first and last.
RepeatLast Number of times to repeat the last colour (0 means last colour is not considered 'special')

Returns: TRUE if the pin number is legal (usually ignored).

Example

var data[4] := [RED, LIME, BLUE, WHITE] ; // send Red, Lime Blue, and white to the NeoPixel strip twice
NP_Write(PA0, data, 4, 0, 2, 0);
// send 2 x Red, Lime, Blue and 2 x White to the NeoPixel strip
NP_Write(PA0, data, 4, 2 , 1 , 2 );

Note

Some 4D Systems display modules utilise this pin for additional peripherals such as Resistive or Capacitive Touch. To ensure that the pin is available for use, refer to the appropriate product’s datasheet.

Graphics Functions

gfx_Cls

Clear the screen using the current background colour. gfx_Cls() command 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 clear screen is to draw a filled rectangle with the required background colour.

Syntax: gfx_Cls();

Returns: None

Example

gfx_BGcolour(DARKGRAY);
gfx_Cls();

// This example clears the entire display using colour DARKGRAY

gfx_ChangeColour

Changes all oldColour pixels to newColour within the clipping area.

Syntax: gfx_ChangeColour(oldColour, newColour);

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

Returns: 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

// This example prints a test string, forces the clipping area to the extent of the text that was printed then changes the background colour.

gfx_Circle

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

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

Arguments Description
x,y Specifies the centre of the circle.
rad Specifies the radius of the circle.
colour Specifies the colour of the circle.

Returns: None

Example

// assuming PEN_SIZE is OUTLINE
gfx_Circle(50,50,30, RED);

// This example draws a BLUE circle outline 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, rad, colour);

Arguments Description
x,y Specifies the centre of the circle.
rad Specifies the radius of the circle.
colour Specifies the fill colour of the circle.

Returns: None

Example

if(state == TOUCH_RELEASED)             // if there's a release;
    gfx_CircleFilled(x, y, 10, RED);    // we'll draw a solid red circle
                                        // of radius=10 on touch release
endif

Note

The PEN_SIZE is ignored, the circle is always drawn SOLID.

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);

Arguments 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.

Returns: None

Example

gfx_Line(100, 100, 10, 10, RED);

// This example draws a RED line from x1=10, y1=10 to x2=100, y2=100

gfx_Hline

Draws a fast horizontal line from x1 to x2 at vertical co-ordinate y using colour.

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

Arguments 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 horizontal line.

Returns: None

Example

gfx_Hline(50, 10, 80, RED); 

// This example draws a fast RED horizontal line at y=50, from x1=10 to x2=80

gfx_Vline

Draws a fast vertical line from y1 to y2 at horizontal co-ordinate x using colour.

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

Arguments 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 vertical line.

Returns: None

Example

gfx_Vline(20, 30, 70, RED);

// This example draws a fast RED vertical line at x=20, from y1=30 to y2=70

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);

Arguments 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.

Returns: None

Example

gfx_Rectangle(10, 10, 30, 30, GREEN);

// This example draws a GREEN rectangle from x1=10, y1=10 to x2=30, y2=30

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.

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.

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

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

Returns: None

Example

gfx_RectangleFilled(30,30,80,80, RED);

// This example draws a filled RED rectangle from x1=30,y1=30 to x2=80,y2=80

Note

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

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.

Rendering can be obtained with gfx_FillPattern(PATTRN); or gfx_FillPattern(OFF); for no fill pattern determined by ‘radius’.

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

Arguments 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 corner radius.This is the distance in pixels extending from the corners of the inner rectangle.
colour Specifies the colour of the rectangle.

Returns: 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. gfx_Polyline can be used to create complex raster graphics by loading the arrays from serial input or from MEDIA with very little code requirement.

This function is very similar to the Polygon function.

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

Arguments 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.

Returns: 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

// This example draws a simple scene

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. gfx_Polygon 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);

Arguments 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.

Returns: 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

// This example draws a simple polygon

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. Vertices must be specified in an anti-clockwise fashion.

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

Arguments 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.
colour Specifies the colour for the triangle.

Returns: None

Example

gfx_Triangle(10,10,30,10,20,30,CYAN);

// This example draws a CYAN triangular outline with vertices at 10,10 30,10 20,30

gfx_Dot

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

Syntax: gfx_Dot();

Returns: None

Example

gfx_MoveTo(40,50);
gfx_ObjectColour(0xRED);
gfx_Dot();

// This example draws a RED pixel at 40,50

gfx_Bullet

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

Syntax: gfx_Bullet(radius);

Arguments Description
radius Specifies the radius of the bullet.

Returns: 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);

Arguments Description
x_dest Specifies the addresses of the storage locations for the calculated Orbit X-coordinate.
y_dest Specifies the addresses of the storage locations for the calculated Orbit Y-coordinate.

Returns: None

Example

var targetX, targetY;
gfx_OrbitInit(&targetX, &targetY)

// This example sets the variables that will receive the result from a gfx_Orbit(..) function call

gfx_Orbit

Sets Prior to using this function, the destination address of variables for the calculated coordinates must be set using the gfx_OrbitInit(..) function. The gfx_Orbit(..) 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);

Arguments 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.

Returns: 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
gfx_CircleFilled(targetX,targetY,3,0xF800);     // mark the target point
                                                // with a RED circle

See example comments for explanation.

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);

Arguments Description
x,y Specifies the screen coordinates of the pixel.
colour Specifies the colour of the pixel.

Returns: None

Example

gfx_PutPixel(32, 32, 0xFFFF);

// This example draws a WHITE pixel at x=32, y=32

gfx_GetPixel

Reads the colour value of the pixel at position x,y.

Syntax: gfx_GetPixel(x, y);

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

Returns: The 8 or 16bit colour of the pixel (default 16bit).

Example

gfx_PutPixel(20, 20, 1234);
r := gfx_GetPixel(20, 20);
print(r);

// This example print 1234, the colour of the pixel that was previously placed.

gfx_MoveTo

Moves the origin to a new position.

Syntax: gfx_MoveTo(xpos, ypos);

Arguments Description
xpos Specifies the horizontal position of the new origin.
ypos Specifies the vertical position of the new origin.

Returns: None

Example

#inherit "4DGL_16bitColours.fnc"
func help()
    var x, y, state;

    print("TOUCHE 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 := tou ch_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, LIGHT GREEN);            // we'll draw a green pixel
        endif
    wend                                                // Repeat forever
endfunc

Note

This function sets the TEXT_MARGIN the x value, this is so you can easily left align text using \n. If you don’t want this, simply set TEXT_MARGIN to 0 using pokeW(TEXT_MARGIN,0).

gfx_MoveRel

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

Syntax: gfx_MoveRel(xoffset, yoffset);

Arguments Description
xoffset Specifies the horizontal offset of the new origin.
yiffset Specifies the vertical offset of the new origin.

Returns: None

Example

gfx_MoveTo(10, 20);
gfx_MoveRel(-5, -3);
gfx_Dot();

// This example draws a pixel using the current object colour at x=5, y=17

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();

Returns: The current X origin before the increment.

Example

var n;
gfx_MoveTo(20,20);
n := 96;

while (n--)
    gfx_ObjectColour(n/3);
    gfx_Bullet(2);
    gfx_IncX();
wend

// This example draws a simple rounded vertical gradient.

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();

Returns: The current Y origin before the increment.

Example

var n;
gfx_MoveTo(20,20);
n := 96;
while (n--)
    gfx_ObjectColour(n/3);
    gfx_LineRel(20, 0);
    gfx_IncY();
wend

// This example draws a simple horizontal gradient using lines.

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);

Arguments 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.

Returns: None

Example

gfx_MoveTo(10, 20);
gfx_LineTo(60, 70);

// This example draws a line using the current object colour between x1=10,y1=20 and x2=60,y2=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);

Arguments Description
xpos Specifies the horizontal end point of the line.
ypos Specifies the vertical end point of the line.

Returns: None

Example

gfx_LinePattern(0b1100110011001100);
gfx_MoveTo(10, 20);
gfx_LineRel(50, 50);

// This example draws a tessellated line using the current object colour between 10,20 and 50,50.

Note

The 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);

Arguments 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.

Returns: None

Example

gfx_MoveTo(40,40);
n := 10;
while (n--)
    gfx_BoxTo(50,50);
    gfx_BoxTo(30,30);
wend

// This example draws 2 boxes, anchored from the current origin.

gfx_SetClipRegion

Forces the clip region to the extent of the last text that was printed, or the last image that was shown.

Syntax: gfx_SetClipRegion();

Returns: None

Example

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);

Arguments 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.

Returns: 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);

Arguments 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.

Returns: None

Example

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

gfx_Button

Draws a 3-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);

Arguments Description
state 0 = Button pressed; 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.

Returns: 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, FONT_4, TEXTWIDTH, TEXTHEIGHT,"4DGL Demo");
    touch_Set(TOUCH_ENABLE);

    Repeat
        // Dr aw the Push Button (raised)
        gfx_Button(UP, LEFT, TOP, BLUE, RED, FONT 4, 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, FONT_4, TEXTWIDTH,TEXTHEIGHT, " PRESS ");
        // Wait until the button is pressed
        while(touch_Get(TOUCH_STATUS) != TOUCH_RELEASED );
    forever

endfunc

gfx_Button2

Draws a 3-dimensional Text Button at screen location defined by x, y parameters (top left corner). The size of the button is defined by the width and height parameters. The text is centred within those bounds. The button has square corners.

Syntax: gfx_Button2(mode, x, y, width, height, buttoncolour, textcolour, text);

Arguments Description
mode 0 = Button pressed; 1 = Button raised.
x, y Specifies the top left corner position of the button on the screen.
width Specifies the width of the button.
height Specifies the height of the button.
buttonColour Button colour.
txtColour Text Colour.
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.

Returns: None

Example

#constant LEFT 30
#constant TOP 150
#constant BWIDTH 50
#constant BHEIGHT 50
//----------------------------------------------------------------------------------------------
func main()
    touch_Set(TOUCH_ENABLE);

    repeat
        // Draw the Push Button (raised)
        gfx_Button2 (UP, LEFT, TOP, BWIDTH, BHEIGHT, BLUE, RED," 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 (
        gfx_Button2(DOWN , LEFT, TOP, BWIDTH, BHEIGHT, BLUE, RED," PRESS ");

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

    forever
endfunc

gfx_Button3

Draws a 3-dimensional Text Button at screen location defined by x, y parameters (top left corner). The size of the button is defined by the width and height parameters. The text is centred within those bounds. The button has rounded corners depending on gfx_BevelRadius().

Syntax: gfx_Button3(mode, x, y, width, height, buttoncolour, textcolour, text);

Arguments Description
mode 0 = Button pressed; 1 = Button raised.
x, y Specifies the top left corner position of the button on the screen.
width Specifies the width of the button.
height Specifies the height of the button.
buttonColour Button colour.
txtColour Text Colour.
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.

Returns: None

Example

#constant LEFT 30
#constant TOP 150
#constant BWIDTH 50
#constant BHEIGHT 50
//--------------------------------------------------------------------------------------------------------------------------------------
func main()

touch_Set(TOUCH_ENABLE);

repeat
    // Draw the Push Button (
    gfx_Button3 (UP, LEFT, TOP, BWIDTH, BHEIGHT, BLUE, RED," PRESS ");
    // set tou ch 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_Button3 (DOWN , LEFT, TOP, BWIDTH, BHEIGHT, BLUE, RED," PRESS ");
    // Wait until the button is pressed
    while(touch_Get(TOUCH_STATUS) != TOUCH_RELEASED );
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);

Arguments 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.

Returns: 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_RoundPanel

Draws a 3-dimensional rounded rectangular panel at a screen location defined by x, y parameters (top left corner). Width and height may be zero allowing the function to be used for rounded panels, rounded buttons, and circular buttons.

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

Syntax: gfx_RoundPanel(state, x, y, width, height, radius, bevelwidth, Colour);

Arguments Description
state 0 = recessed; 1 = raised. 2 = hide (draw object in background colour)
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.
radius Specifies the corner radius.
bevelwidth Set Panel bevel width 0-15 pixels.
colour Specifies the colour of the panel.

Return: None

Example

gfx_RoundPanel(PANEL_RAISED, 100, 100, 30, 20, GRAY);

gfx_Slider2

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

Selection rules:

  1. If width > height, slider is horizontal.
  2. If height <= width, slider is horizontal.
  3. 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)
  4. 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)
  5. 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_Slider2(mode, x1, y1, width, height, colour, scale, value);

Arguments Description
mode mode = 0 : Slider Indented, mode = 1 : Slider Raised, mode 2, Slider Hidden (background colour).
x1, y1 Specifies the top left corner position of the slider on the screen.
width Specifies the width of the slider on the screen.
height Specifies the height of the slider on the screen.
colour Specifies the colour of the Slider bar.
scale scale = n : sets the full scale range of the slider for the thumb from 0 to n.
value value = m : sets the relative position of the thumb 0 <= m <= n.

Returns: If the value parameter was a positive number (i.e:- value is a proportion of the scale parameter), the true (implied x-axis 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_Slider2(0,rSlider[0],rSlider[1], 100 ,50,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_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);

Arguments Description
xs, ys Specifies the horizontal 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.

Returns: None

Example

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

gfx_Slider

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

Selection rules:

  1. If x2-x1 > y2-y1 slider is assumed to be horizontal (ie: if width > height, slider is horizontal).
  2. If x2-x1 <= y2-y1 slider is assumed to be vertical (ie: if height <= width, slider is horizontal).
  3. 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).
  4. 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).
  5. 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);

Arguments Description
mode mode = 0 : Slider Indented, mode = 1 : Slider Raised, mode 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 scale = n : sets the full scale range of the slider for the thumb from 0 to n.
value if value positive, sets the relative position of the thumb on the slider bar, else set thumb to ABS position of the negative number.

Returns: If the value parameter was a positive number (i.e:- value is a proportion of the scale parameter), the true (implied x-axis 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_RGBto565

Returns the 16bit (RED: 5, GREEN: 6, BLUE: 5 format) colour value of a 24bit (RED: 8, GREEN: 8, BLUE: 8 format) colour.

Syntax: gfx_RGBto565(RED, GREEN, BLUE);

Arguments Description
RED 8bit colour value for RED.
GREEN 8bit colour value for GREEN.
BLUE 8bit colour value for BLUE.

Returns: The 16bit (RED: 5, GREEN: 6, BLUE: 5 format) colour value.

Example

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

gfx_332to565

Returns the 16bit (RED: 5, GREEN: 6, BLUE: 5 format) value of an 8bit (RED: 3, GREEN: 3, BLUE: 2 format) colour.

Syntax: gfx_332to565(COLOUR8BIT);

Arguments Description
COLOUR8BIT 8bit colour value. 3bits for RED, 3bits for GREEN, 2bits for BLUE.

Returns: The 16bit (RED: 5, GREEN: 6, BLUE: 5 format) value.

Example

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

gfx_565to332

Returns the 8bit (RED: 3, GREEN: 3, BLUE: 2 format) value of a 16bit (RED: 5, GREEN: 6, BLUE: 5 format) colour.

Syntax: gfx_565to332(COLOUR16BIT);

Arguments Description
COLOUR16BIT 16bit colour value. 5bits for RED, 6bits for GREEN, 5bits for BLUE.

Returns: The 8bit (RED: 3, GREEN: 3, BLUE: 2 format) value.

Example

var color332;
color332 := gfx_565to332(0x7F00); // Convert 16bit 565 color value to 8bit 332 color value

gfx_TriangleFilled

Draws a Solid triangle between vertices x1,y1 , x2,y2 and x3,y3 using the specified colour. Vertices must be specified in an anti-clockwise fashion.

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

Arguments 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.
colour Specifies the colour for the triangle.

Returns: None

Example

gfx_TriangleFilled(10,10,30,10,20,30,CYAN);

// This example draws a CYAN Solid triangle with vertices at 10,10 30,10 20,30

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);

Arguments 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.

Returns: 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

// This example draws a simple filled polygon.

gfx_Origin

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

Syntax: gfx_Origin(x, y);

Arguments Description
x, y Specifies the horizontal and vertical position of the top left corner of the clipping window.

Returns: None

Example

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

gfx_Get

Returns various graphics parameters to caller.

The following graphics parameters can be queried:

Mode Description
X_MAX Current orientations Max X Value (X_MAX)
Y_MAX Current orientations Max Y Value (Y_MAX)
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);

Arguments Description
mode Specifies graphics parameter to query.

Returns:

Mode Description
0 Returns the maximum horizontal value of the display.
1 Returns the maximum vertical value of the display.
2 Returns the left location of the last drawn object such as a slider or button or an image/video.
3 Returns the top location of the last drawn object such as a slider or button or an image/video.
4 Returns the right location of the last drawn object such as a slider or button or an image/video.
5 Returns the bottom location of the last drawn object such as a slider or button or an image/video.
6 Returns the internal X position that was set with gfx_MoveTo(x, y); or gfx_Set(X_ORG, pos);
7 Returns the internal Y position that was set with gfx_MoveTo(x, y); or gfx_Set(X_ORG, pos);

Example

var := gfx_Get(X_MAX);          //Returns the maximum horizontal resolution of the display
var := gfx_Get(0); 
var := gfx_Get(Y_MAX);          //Returns the maximum vertical resolution of the display
var := gfx_Get(1); 
var := 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.
var := gfx_Get(2); 
var := 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.
var := gfx_Get(3);

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);

Arguments 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.

Returns: None

Example

var n;
gfx_ClipWindow(10, 10, 50, 50 )
n := 50000;
while(n--)
    gfx_PutPixel(RAND()%100, RAND()%100, RAND());
wend
repeat forever

// This example will draw 50000 random colour pixels, only the pixels within the clipping area will be visible

gfx_Set

Given a function number and a value, set the required graphics control parameter, such as size, colour, and other parameters. (See the Single parameter short-cuts for the gfx_Set functions below). It is strongly recommended to use the pre-defined constants rather than the mode numbers.

Single parameter short-cuts for the gfx_Set functions

Predefined Name 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 Colour, 0-65535
OBJECT_COLOUR Generic colour for gfx_LineTo, gfx_LineRel, gfx_Dot, gfx_Bullet and gfx_BoxTo Colour, 0-65535
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. Colour, 0-65535
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) Colour, 0-65535
CONTRAST LCD MODULES:
contrast 0 = display OFF, 1-15 = contrast level (Actually backlight brightness)
0 or OFF
1 to 15 for levels
LINE_PATTERN Sets the line draw pattern for line drawing. If set to zero, lines are solid, else each '1' bit represents a pixel that is turned off.
Example:
gfx_Set(LINE_PATTERN, 0b1111000011110000); // draw dotted line
0 or OFF
1 to 0xFFFF
0 bits for pixels on
1 bits for pixels off
COLOUR_MODE Sets 8 or 16bit colour mode.
Function not available, fixed as 16bit mode.
0 or COLOUR16
1 or COLOUR8
BEVEL_WIDTH Set Button Bevel Width, 0 pixel to 15pixels. 0 None
1 to 15 pixels
BEVEL_SHADOW graphics button bevel shadow depth 0 None
1 to 15 pixels
X_ORIGIN sets the origin of drawn objects to a position other than 0,0
Y_ORIGIN sets the origin of drawn objects to a position other than 0,0
DISPLAY_PAGE Choose Page to be displayed. Applies to 4.3” products with a Solomon SSD1961 and SSD1961 Driver IC only, with a 4.3” display only, such as uLCD-43D/DT/DCT series and gen4-uLCD-43D/DT/DCT series of displays. Please refer to module datasheets for information on what SSD196x is present on your module. ** 0 or 1 for SSD1961
0, 1 or 2 for SSD1963
READ_PAGE Choose Page to be read. Applies to 4.3” products with a Solomon SSD1961 and SSD1961 Driver IC only, with a 4.3” display only, such as uLCD-43D/DT/DCT series and gen4-uLCD-43D/DT/DCT series of displays. Please refer to module datasheets for information on what SSD196x is present on your module. ** 0 or 1 for SSD1961
0, 1 or 2 for SSD1963
WRITE_PAGE Choose Page to be written. Applies to 4.3” products with a Solomon SSD1961 and SSD1961 Driver IC only, with a 4.3” display only, such as uLCD-43D/DT/DCT series and gen4-uLCD-43D/DT/DCT series of displays. Please refer to module datasheets for information on what SSD196x is present on your module. ** 0 or 1 for SSD1961
0, 1 or 2 for SSD1963

Single parameter short-cuts for the gfx_Set functions

Function Syntax Function Action Value
gfx_PenSize(mode) Set the draw mode for gfx_LineTo, gfx_LineRel, gfx_Dot, gfx_Bullet and gfx_BoxTo* 0 or SOLID
1 or OUTLINE
gfx_BGcolour(colour) Set the screen background colour Colour 0-65535
gfx_ObjectColour(colour) Generic colour for gfx_LineTo, gfx_LineRel, gfx_Dot, gfx_Bullet and gfx_BoxTo Colour 0-65535
gfx_Clipping(mode) Turns clipping on/off.
The clipping points are set with gfx_ClipWindow.
0 or 1 (ON or OFF)
gfx_TransparentColour(colour) Colour that needs to be made transparent. Colour, 0-65535
gfx_Transparency(mode) Turn the transparency ON or OFF. 0 or 1 (ON or OFF)
gfx_FrameDelay(delay) Set the inter frame delay for media_Video. 0 to 255msec
gfx_ScreenMode(mode) Graphics orientation LANDSCAPE, LANDSCAPE_R, PORTRAIT, PORTRAIT_R 1 or LANDSCAPE
2 or LANDSCAPE_R
3 or PORTRAIT
4 or PORTRAIT_R
gfx_OutlineColour(colour) Outline colour for rectangles and circles.(set to 0 for no effect) Colour 0-65535
gfx_Contrast(value) LCD MODULES:
contrast 0 = display OFF, 1-15 = contrast level (Actually backlight brightness)
0 or OFF
1 to 15 for levels
gfx_LinePattern(pattern) Sets the line draw pattern for line drawing. If set to zero, lines are solid, else each '1' bit represents a pixel that is turned off. See code examples for further reference.
Example:
gfx_Set(LINE_PATTERN, 0b1111000011110000);// draw dotted line
0 or OFF
1 to 0xFFFF
0 bits for pixels on
1 bits for pixels off
gfx_BevelRadius(radius) graphics button bevel radius 0 None
1 to 15 pixels
gfx_BevelWidth(mode) graphics button bevel width 0 None
1 to 15 pixels
gfx_BevelShadow(value) graphics button bevel shadow depth 0 None
1 to 15 pixels
gfx_Xorigin(offset) graphics X origin
gfx_Yorigin(offset) graphics Y origin

Syntax: gfx_Set(function, value);

Arguments Description
function The function number determines the required action for various graphics control functions. Usually a constant, but can be a variable, array element, or expression. There are pre-defined constants for each of the functions.
mode A variable, array element, expression or constant holding a value for the selected function.

Returns: None

Example

Note

Although it is often required to be able to set graphics functions with a single function call for graphics engine related functions, there is a complete set of single parameter shortcut functions that have exactly the same function as each of the gfx_Set modes and saves 1 parameter, i.e. uses less memory.

*pen size is set to OUTLINE for normal operation.

**SSD1961 has 2 Pages, SSD1963 has 3 pages.

gfx_Arc

Draws an arc at "xc":"yc" with radius "radius", starting at "startangle" and ending at "endangle". Colour is determined by current object colour.

Syntax: gfx_Arc(cx, cy, radius, step, startangle, endangle, mode);

Arguments Description
cx, cy Center of the arc.
radius Radius of the arc.
step Step is the stepping angle increment for the fineness of the arc.
startangle Starting angle of the arc.
endangle Ending angle of the arc.
mode mode = 0, outer circumference line only.
mode = 1, outer circumference and lines back to cx:cy.

Returns: None

Example

gfx_Arc(120, 150, 100, 1, 0, 90 ,0);
/*
* Draws an arc with 100 pixel radius with center at point (120,150)
* The arc starts from from 0 to 90 degree angle
* Lines from the ends of the arc to the center are not drawn.
*/

gfx_CheckBox

Draws a CheckBox at screen location defined by x,y arguments (top left corner).

Syntax: gfx_CheckBox(state, x, y, Width, Height, boxColour, textColour, text);

Arguments Description
state state = 1 = UNCHECKED : CheckBox Unchecked
state = 0 = CHECKED : Checkbox Checked
x, y Top left corner of the Checkbox.
width Width of the checkbox.
height Height of the checkbox.
boxColour Checkbox colour.
textCplour Text colour.
text The text is to the right of the checkbox and truncated if necessary

Returns: None

Example

gfx_CheckBox(1, 20, 20, 100, 25, BLUE , LIME , "4D Labs");
/*
* Draws a n UNCHECKED checkbox, top left corner at (20
* The checkbox has a width of 100 pixels to conta in ‘4D Labs’
*/

gfx_RadioButton

Draws a Radio-button at screen location defined by x,y arguments (top left corner).

Syntax: gfx_RadioButton(state, x, y, width, height, boxColour, textColour, text);

Arguments Description
state state = 1 = UNCHECKED : Radio-button Unchecked
state = 0 = CHECKED : Radio-button Checked
x,y Top left corner of the Radio-button.
width Width of the Radio-button.
height Height of the Radio-button.
boxColour Radio-button colour.
textColour Text colour.
text The text is to the right of the Radio-button and truncated if necessary

Returns: None

Example

gfx_RadioButton(0, 20, 20, 100, 25, BLUE, LIME, "4D Labs");
/*
* Draws a CHECKED radio button, top left corner at (20, 150)
* The radio button has a width of 100 pixels to contain ‘4D Labs'
*/

gfx_FillPattern

Selects a tessellating pattern for painting solid objects. ‘patptr’ points to a 8x8 tile for rendering filled areas. Rendering is turned off with gfx_FillPattern(0, mode); or gfx_FillPattern(OFF, mode);

‘mode’ maybe TRANSPARENT or OPAQUE (0 or 1), for OPAQUE mode, the current screen colour is used for the 'off' pixels, for transparent mode, the 'off' pixels are not drawn.

gfx_FillPattern affects all filled object, including polygons. There are 32 builtin patterns; these are obtained using the pre-defined constants FILLPATTERN_0 to FILLPATTERN_31. Note that the constants range from 0xFFE0 to 0xFFFF, any other value is assumed to be a pointer to a user’s 8 byte block pattern. Predefined constants are used to select the internal patterns, FILLPATTERN_0 through to FILLPATTERN_31

Syntax: gfx_FillPattern(patptr, mode);

Arguments Description
patptr 0 = 0ff, 0xFFE0 to 0xFFFF = builtin patterns, else patptr points to a users 8 byte pattern.
mode TRANSPARENT or OPAQUE (0 or 1)

Returns: The handle of the previous pattern.

Example

gfx_FillPattern(OFF, TRANSPARENT); // Turns OFF pattern rendering

gfx_FillPattern(FILLPATTERN_31, TRANSPARENT);
// Renders FILLPATTERN_31 in transparent mode for filled objects

gfx_FillPattern(FILLPATTERN_17, OPAQUE);
// Renders FILLPATTERN_17 in OPAQUE mode for filled objects

gfx_Gradient

Draws a graduated colour rectangle at the specified co-ordinate. Rendering can be obtained with gfx_FillPattern(PATTRN); or gfx_FillPattern(OFF); for no fill pattern.

Syntax: gfx_Gradient(style, x1, y1, x2, y2, color1, color2);

Arguments Description
style Specifies gradient style.
GRAD_DOWN gradient changes in the vertical direction
GRAD_RIGHT gradient change in the horizontal direction
GRAD_UP gradient changes in the vertical direction
GRAD_LEFT gradient change in the horizontal direction
GRAD_WAVE_VER gradient wave in the vertical direction
GRAD_WAVE_HOR gradient wave in the horizontal direction
x1, y1 Specifies top left corner of the rectangle.
x2, y2 Specifies bottom right corner of the rectangle.
color1 Specifies starting colour.
color2 Specifies ending colour.

Returns: None

Example

//Draw graduated colour rectangle
gfx_Gradient(GRAD_WAVE_HOR, 10, 10, 230, 160, BLACK, WHITE);

gfx_RoundGradient

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

X1 may equal X2, and Y1 = Y2 allowing the function to be used for rounded panels, rounded buttons, circular buttons.

Rendering can be obtained with gfx_FillPattern(PATTRN); or gfx_FillPattern(OFF); for no fill pattern.

Syntax: gfx_RoundGradient(style, x1, y1, x2, y2, radius, color1, color2);

Arguments Description
style Specifies gradient style.
GRAD_DOWN gradient changes in the vertical direction
GRAD_RIGHT gradient change in the horizontal direction
GRAD_UP gradient changes in the vertical direction
GRAD_LEFT gradient change in the horizontal direction
GRAD_WAVE_VER gradient wave in the vertical direction
GRAD_WAVE_HOR gradient wave in the horizontal direction
x1, y1 Specifies top left corner of the rectangle.
x2, y2 Specifies bottom right corner of the rectangle.
radius Specifies the corner radius.
color1 Specifies starting colour.
color2 Specifies ending colour.

Returns: None

Example

//Draw graduated colour rounded rectangle
gfx_RoundGradient(GRAD_WAVE_HOR, 10, 10,230, 160, 10, BLACK, WHITE);

gfx_PieSlice

Draws a pie slice (filled arc) at xc:yc with radius, starting at startangle and ending at endangle. Rendering can be obtained with gfx_FillPattern(PATTRN); or gfx_FillPattern(OFF); for no fill pattern.

Syntax: gfx_PieSlice(cx, cy, spread, radius, step, startangle, endangle, mode, colour);

Arguments Description
cx, cy Center of the slice.
spread Center offset: it is used to offset the centrepoint of the pieslice to shift a pie chart piece away from the centrepoint.
radius Radius of the Slice.
step Step is the stepping angle increment for the fineness of the slice.
startangle Starting angle of the slice.
endangle Ending angle of the slice.
mode mode = 0, no outline.
mode = 1, outer circumference line only.
mode = 2, outer circumference and slice lines.
colour Specifies colour of the colour of the PieSlice.

Returns: None

Example

gfx_PieSlice(120, 150, 0, 100, 1, 0, 90, 0, LIME);
/*
* Draws a filled arc, 100 pixel radius, center at point (120,150)
* The arc starts from from 0 to 90 degree angle
* Outlines are not drawn
*/

gfx_PointWithinBox

Returns true if last touch co-ordinates are within the box test area.

Syntax: gfx_PointWithinBox(x, y, &rect);

Arguments Description
x, y Coordinates
&rect An array of 4 vars, x1, y1, width, height.

Returns: True if last touch co-ordinates are within the box test area.

Example

var x, y;
var rect[4] := [0,0,480,320];
touch_Set(TOUCH_ENABLE);

repeat
    x := touch_Get(TOUCH_GETX);
    y := touch_Get(TOUCH_GETY);
    if (gfx_PointWithinBox(x,y,rect) == 1)
        txt_MoveCursor(0,0);
        print("X: ",[DEC]x, " Y: ", [DEC]y, " \nTOUCHED");
    endif
forever

gfx_PointWithinRectangle

Returns true if last touch co-ordinates are within the rectangle test area.

Syntax: gfx_PointWithinRectangle(x, y, &recta);

Arguments Description
x, y Coordinates
&recta An array of 4 vars, x1, y1, x2, y2.

Returns: True if last touch co-ordinates are within the rectangle test area.

Example

var x, y;
var rect[4] := [0,0,100,120];
touch_Set(TOUCH_ENABLE);

repeat
    x := touch_Get(TOUCH_GETX);
    y := touch_Get(TOUCH_GETY);
    if (gfx_PointWithin Rectangle (x,y,rect) == 1)
        txt_MoveCursor(0,0);
        print("X: ",[DEC]x, " Y: ", [DEC]y, " \nTOUCHED");
    endif
forever

gfx_readBresLine

Due to the fact that most LCDs are not double buffered, and memory is limited on small platforms, gfx_ReadBresLine offers a simple but powerful way of manipulating raster lines by storing all the pixels for an arbitrary line.

Typically, gfx_ReadBresLine is used when ‘rubber banding’ a rectangular area when dragging a marker rectangle, or drawing a needle on a pre-rendered meter or gauge image. The power of this function is further extended when used with the array math functions.

gfx_ReadBresLine reads an arbitrary line 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 when no longer required. Otherwise, "ptr" is expected to point to a correctly sized array.

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

Arguments Description
x1, y1 Line mapping start point.
x2, y2 Line mapping end point.
ptr If zero is passed, an array of the required size to map the line is created. If non zero, it is expected that this is a pointer to an array large enough to store each pixel that is read.

Returns: A pointer to the created array, or the users array. In the case of ptr=0 (creation of array), if there is insufficient memory to create the array, zero is returned.

Example

var array;
array := gfx_ReadBresLine(50,50,250,175,0);
// Copy the pixels of the line with endpoint at (50,50) and (250, 175)
// and saves it to the generated array. The address is then returned
// and saved to the variable 'array'

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

gfx_WriteBresLine(100,100,300,225,array);
// Copies the line to the new
// Endpoints are at (100,100) and (300,225)

Note

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

bytecount := (MAX(ABS(x2-x1), ABS(y2-y1) + 1) * 2;
// calc array size for mem_Alloc (which allocates byte storage)

wordcount := (MAX(ABS(x2-x1), ABS(y2-y1) + 1);
// calc array size for fixed word array (it’s much easier to let the function to do this calculation for you – if applicable)

gfx_WriteBresLine

Cast pixel values from array to arbitrary line.

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

Arguments Description
x1, y1 Line mapping start point.
x2, y2 Line mapping end point.
ptr Points to the array to be written.

Returns: None

Example: See gfx_ReadBresLine.

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.

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

Arguments Description
x1, y1 Top left corner of the rectangular area.
x2, y2 Bottom right corner of the rectangular area.
ptr If zero is passed, an array of the required size to map the line is created. If non zero, it is expected that this is a pointer to an array large enough to store each pixel that is read.

Returns: A pointer to the created aray, or the users array. In the case of ptr=0, if there is insufficient memory to create the array, zero is returned.

Example

var array;
array := gfx_Read GRAMarea (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)

Note

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

bytecount := ( (ABS(x2-x1)+1) * (ABS(y2-y1) + 1)) * 2; // calc array size for mem_Alloc (which allocates byte storage)
wordcount := ( (ABS(x2-x1)+1) * ABS(y2-y1)); // calc array size for fixed word array

gfx_WriteGRAMarea

Write an array back to the rectangular area.

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

Arguments 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.

Returns: None

Example: See gfx_ReadGRAMarea.

gfx_Surround

Draws an outline rectangle at the given co-ordinates with optional rounded corners determined by ‘rad1’. ‘rad2’ is added to ‘rad1’ to form the outer rounded rectangle. If ‘rad1’ is zero, the inner rectangle will have square corners.

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

Arguments 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 Inner corner radius.
rad2 Outer corner radius.
color The colour of the surround.

Returns: None

Example

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

gfx_Scope

Draws up to 4 waveforms from table(s) of vertices at the specified origin. Also useful for drawing line graphs.

X position is incremented each point by "Xstep" pixels. Values are skipped for negative values. Y values are derived from a Y buffer.
After the waveform is drawn, "newy" buffer is automatically copied to "oldy" buffer. Use 0 as the buffers for any unused waveforms.

Syntax: gfx_Scope(left, width, Yzero, N, Xstep, Yamp, colourbg, old_y1, new_y1, colour1, old_y2, new_y2, colour2, old_y3, new_y3, colour3, old_y4, new_y4, colour4);

Arguments Description
left The left margin of the Scope.
width The width of the Scope.
Yzero The y position that corresponds to a y value of zero, normally "Top" + "Height" for a graph, or "Top" + "Height"/2 for a scope.
N The number of elements in each buffer. This will need to be greater than "width" for negative "Xstep" values.
Xstep X position is incremented each point by "xstep" pixels.
Yamp Amplification in the Y direction, 100 is unity.
colourbg The color of the Scope’s Background.
oldy1..4 Buffer containing most recent set of points to be un-drawn.
newy1..4 Buffer containing new points to be drawn.
colour1..4 Colour of the waveform.

Returns: None

Example

gfx_RingSegment

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

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

Arguments Description
x, y Center
Rad1 Outer radius
Rad2 Inner radius
starta Start angle
enda End angle
colour Colour

Returns: None

Example

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

gfx_AngularMeter

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

#DATA
word Gauge1Info
    // Scale parameters
    90,                         // Range scale outer edge radius
    70,                         // Range scale inner edge radius
    20,                         // Number of partitions of marker ticks
    2,                          // Number of minor ticks before next major tick (0 to disable)
    17,                         // Length for major ticks radiating from scale outer edge
    5,                          // Length for minor ticks radiating from scale outer edge
    10,                         // Length for major ticks radiating from scale inner edge
    2,                          // Length for minor ticks radiating from scale inner edge
    1,                          // Tick width
    0xFFFF,                     // Tick color
    270,                        // Starting angle for range scale second ring section
    337,                        // Starting angle for range scale third ring section
    0xDF,                       // Range scale first ring section color
    0x3BF,                      // Range scale second ring section color
    0xF800,                     // Range scale third ring section color
    0,                          // Range scale section incremental step size
    10,                         // Total number of marker scale labels
    1,                          // Marker scale label font style
    0xFFFF,                     // Marker scale label text color
    15,                         // Marker scale label offset distance (relative to range scale midpoint)
    0,                          /* Labels */ // Pointer to label strings (Default is numeric is set to zero (0))
    (0 + 0 + 0 + 0),            // Gauge Options
    2,                          // Caption
    0xFFFF,                     // Caption text color
    -26,                        // Caption horizontal offset from rotation centre
    56,                         // Caption vertical offset from rotation centre
    Caption,                    // Caption text pointer

    // Gauge parameters common to needle
    10,                         // Top-Left X-position
    10,                         // Top-Left Y-position
    235,                        // Width
    197,                        // Height
    128,                        // Rotation centre X-position
    125,                        // Rotation centre Y-position
    0x0,                        // Background color (required for erasing needle path)
    135,                        // Starting angle
    405,                        // Ending angle
    0,                          // Minimum value
    100,                        // Maximum value

    // Needle parameters
    60,                         // Needle length
    NEEDLE_F_TRIANGLE,          // Needle style options
    0,                          // Needle offset distance from center
    6,                          // Needle width (Half value of overall needle thickness)
    30,                         // Needle tail length (Applicable only for double triangle style)
    0xFFFF,                     // Needle color
    6,                          // Needle Hub radius
    0xFFFF,                     // Needle Hub color
    2,                          // Needle Pin radius
    0xF800                      // Needle Pin color

byte Caption "Caption\0"                            // Caption string (Use null terminator "\0" to end string)
byte Labels "Text1\0Text2\0Text3\0Text4\0Text5\0"   // Label text strings (Use null terminator "\0" as separators)

#END 
ANGULAR_F_LABEL_STRINGS         //Set bit for swapping gauge direction
ANGULAR_F_BG_TRANSPARENT        //Set bit for toggling background transparency
ANGULAR_F_TICK_PCT_COLOUR       //Set bit for replacing tick color with range scale section colors
ANGULAR_F_TEXT_PCT_COLOUR       //Set bit for replacing marker label color with range scale section colors

Note

The angular meter function will require the gfx_Needle in order to function.

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

Arguments 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.

Returns: 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_Panel2

Draws a panel2 (groupbox) at screen location defined by x, y, width and height with left colour "cl" and right colour "cr"and option fill colour "cf".

w1 and w2 define the width of the outer and inner borders.

state = 0 : recessed
state = 1 : raised
state + PANEL2_FILLED : draws with fill color "cf"

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

Arguments Description
state Bevel direction (0 – Inwards, 1 – Outwards)
Additional bit for filling panel with fill color (0x8000 - PANEL2_FILLED).
x, y Top-Left X-position, Top-Left Y-position
width Panel width.
height Panel height.
w1 Outer bevel offset.
w2 Inner bevel offset.
cl Main bevel color.
cr Shadows bevel color.
cf Panel fill color.

Returns: None

Example

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

gfx_Needle

Draw a Needle as defined by NeedleDef (if required), using NeedleRam positioning at position value. See the reference for the NeedleDef values.

#DATA
    word NeedleInfo 10,             // Top-Left X-position
                    10,             // Top-Left Y-position
                    235,            // Width
                    197,            // Height
                    128,            // Rotation centre X-position
                    125,            // Rotation centre Y-position
                    0x0,            // Background color (required for erasing needle path)
                    135,            // Starting angle
                    405,            // Ending angle
                    0,              // Minimum value
                    100,            // Maximum value
                    60,             // Needle length
                    NEEDLE_F_LINE,  // Needle style options
                    0,              // Needle offset distance from center
                    6,              // Needle width (Half value of overall needle thickness)
                    30,             // Needle tail length (Applicable only for DoubleTriangle style)
                    0xFFFF,         // Needle color
                    6,              // Needle Hub radius
                    0xFFFF,         // Needle Hub color
                    2,              // Needle Pin radius
                    0xF800          // Needle Pin color
#END
NEEDLE_F_LINE                       //Line needle pointer
NEEDLE_F_RECTANGLE                  //Rectangular needle pointer
NEEDLE_F_POINTRECTANGLE             //Pointed rectangular needle pointer
NEEDLE_F_TRIANGLE                   //Triangular needle pointer
NEEDLE_F_DOUBLETRIANGLE             //Double ended triangular needle pointer
NEEDLE_F_ROUNDEDRECTANGLE           //Rounded corner rectangular needle pointer

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

Arguments 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.

Returns: 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

Note

The needle function can be used standalone without the angular meter function, but the angular meter function will require the needle function.

gfx_Dial

Draw a Dial as defined by DialDef (if required), using DialRam positioning at position value. See the reference for the DialDef values.

#DATA
    word Knob1Info 10,                      // Top-Left X-position
                    10,                     // Top-Left Y-position
                    152,                    // Width
                    129,                    // Height
                    87,                     // Knob centre X-position
                    80,                     // Knob centre Y-position
                    38,                     // Knob radius
                    135,                    // Rotation starting angle
                    405,                    // Rotation ending angle
                    0,                      // Minimum value
                    100,                    // Maximum value
                    0x0,                    // Background color
                    0x52AA,                 // Knob color
                    5,                      // Bevel thickness
                    0xB5B6,                 // Bevel gradient color 1 (Left side)
                    0x3186,                 // Bevel gradient color 2 (Right side)
                    200,                    // Starting angle for Partition 2
                    300,                    // Starting angle for Partition 3
                    0x280,                  // Partition 1 low color
                    0x528A,                 // Partition 2 low color
                    0x5800,                 // Partition 3 low color
                    0x7E0,                  // Partition 1 high color
                    0xFFE0,                 // Partition 2 low color
                    0xF800,                 // Partition 3 low color
                    12,                     // Indicator ticks offset distance
                    3,                      // Indicator size 1 (Radius/Width of circle, triangle or rectangle)
                    6,                      // Indicator size 2 (Length of line, triangle or rectangle)
                    0xF800,                 // Knob pointer color
                    3,                      // Knob pointer size 1 (Radius/Width of circle, triangle or rectangle)
                    30,                     // Knob pointer size 2 (Length of line, triangle or rectangle)
                    0xFFFF,                 // Knob indicator label text color
                    2,                      // Knob indicator label font style
                    22,                     // Knob indicator label offset distance
                    10,                     // Number of indicator labels
                    0,                      /*Labels*/ // Pointer to string indicator labels (Numeric labels if zero (0))
                    2,                      // Caption font style
                    0xFFFF,                 // Caption text color
                    -15,                    // Caption horizontal offset from knob centre
                    50,                     // Caption vertical offset from knob centre
                    Caption,                // Knob Caption text
                    (0 + 0 + 0)             // Option bits (See Widget Parameter Data Block Option Bits)
    byte Caption "KNOB\0" // Caption string (Use null terminator "\0" to end string)
    byte Labels "Text1\0Text2\0Text3\0Text4\0Text5\0" // Label text strings (Use null terminator "\0" as separators)
#END
DIAL_F_LABEL_STRINGS                //Set bit for dial indicator string (default is numeric)
DIAL_F_BG_TRANSPARENT               //Set bit for widget transparency
DIAL_F_HANDLE_CIRCLE                //Set bit for circular knob pointer style
DIAL_F_HANDLE_TRIANGLE              //Set bit for triangular knob pointer style
DIAL_F_HANDLE_RECTANGLE             //Set bit for rectangular pointer style
DIAL_F_HANDLE_LINE                  //Set bit for line pointer style
DIAL_F_INDICATOR_CIRCLE             //Set bit for circular dial indicator style
DIAL_F_INDICATOR_TRIANGLE           //Set bit for triangular dial indicator style
DIAL_F_INDICATOR_RECTANGLE          //Set bit for rectangular dial indicator style
DIAL_F_INDICATOR_LINE               //Set bit for line dial indicator style

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

Arguments 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.

Returns: 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_Gauge

Draw a Gauge as defined by GaugeDef (if required), using GaugeRam positioning at position value. See the reference for the GaugeDef values.

#DATA
    word Gauge1Info 10,             // Top-Left X-position
                    10,             // Top-Left Y-position
                    181,            // Gauge length
                    59,             // Gauge width
                    11,             // Number of Gauge bars
                    0,              // Minimum gauge value
                    100,            // Maximum gauge value
                    10,             // Bar thickness
                    5,              // Bar spacing
                    0x18E3,         // Inter 'bar' gap color
                    0x280,          // Partition 1 low colour
                    0x7E0,          // Partition 1 active colour
                    0x5280,         // Partition 2 low colour
                    0xFFE0,         // Partition 2 active colour
                    0xA000,         // Partition 3 low colour
                    0xF800,         // Partition 3 active colour
                    8,              // Partition 2 starting bar
                    5,              // Partition 3 starting bar
                    (0)             // Gauge Option bits
#END
GAUGE_F_TOPRIGHT                    //Set bit for swapping gauge direction to start from top or right side
GAUGE_F_HORZ                        //Horizontal orientation set bit (Default is Vertical)

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

Arguments 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.

Returns: 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

Note

For optimal appearance, calculate number of bars for given height first using this formula:

bars = ( (gauge height / 2) + (spacing / 2) + 1) / ( (bar thickness / 2) + (spacing / 2) + 2)

then calculate exact height given the calculated ticks:

height = bars * ( (bar thickness / 2) + (spacing / 2) +2) – (spacing / 2) - 1

gfx_LedDigits

Draw a series of 7 segment Led Digits as defined by LedDigitDef, using LedDigitRam positioning at position value. See the reference for LedDigitDef values.

#DATA
    word Digits1Info    10,                 // Top-Left X-position
                        10,                 // Top-Left Y-position
                        66,                 // Widget width (Used only for touch region)
                        106,                // Widget height (Used only for touch region)
                        2,                  // Number of digits
                        0,                  // Separator placement (To disable separator use -1)
                        0,                  // Spacing distance between each digits
                        5,                  // Digit size
                        0xFFFF,             // LED segment ON color
                        0x630C,             // LED segment OFF color
                        (0 + 0 + 0)         // Option bits (See Widget Parameter Data Block Option Bits)
#END
LEDDIGITS_F_GENERAL                         //Set bit for LED digit general format
LEDDIGITS_F_FIXED                           //Set bit for LED digit fixed format
LEDDIGITS_F_SCIENTIFIC                      //Set bit for LED digit scientific format
LEDDIGITS_F_INT16                           //Set bit for 16-bit Integer LED digit format
LEDDIGITS_F_INT32                           //Set bit for 32-bit Integer LED digit format
LEDDIGITS_F_FLOAT                           //Set bit for Float LED digit format
LEDDIGITS_F_UNSIGNED                        //Set bit for unsigned LED digit format
LEDDIGITS_F_SIGNED                          //Set bit for signed LED digit format
LEDDIGITS_F_LEADING0                        //Set bit for setting leading digits as zeroes
LEDDIGITS_F_LEADINGb                        //Set bit for setting leading digits as blanks
LEDDIGITS_F_DP_DOT                          //Set bit for using dots as separator
LEDDIGITS_F_DP_COMMA                        //Set bit for using commas as separator

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

Arguments Description
value For the int16 format, a value specifying the current frame of the widget. For other formats (Int32 and Float) are both 32-bits therefore value is the address of a two element array containing the value.
&LedDigitRam A pointer to a variable array for widget utilization.
&LedDigitDef A pointer to the Data Block holding the widget parameters.

Returns: 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. The value can be 0-9 (0-9), A-F (0x0a-0x0f), blank(0x10) and - (0x11). Or value with LEDDIGIT_F_SHOW_DP to show a decimal point, LEDDIGIT_F_DP_COMMA to make the Decimal point a comma and LEDDIGIT_F_DP_ON to turn the decimal point on LEDDIGIT_F_SET_SEGMENTS can be used to turn value into a series of bits to turn on individual segments e.g. LEDDIGIT_F_SET_SEGMENTS + 9 will turn on the top and bottom segments. Again 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);

Arguments Description
x, y x- and y-coordinates of position.
digitsize Size of digit.
oncolour Color when status is on.
offcolour Color when status is off.
value Value to show.

Returns: None

Example

gfx_LedDigit(10, 10 , 5 , YELLOW , LIME , 3);

gfx_Slider5

Draw a Slider as defined by SliderDef (if required), using SliderRam positioning at position value. See the reference for the SliderDef values

#DATA
    word Slider1Info    10,             // Top-Left X-position
                        10,             // Top-Left Y-position
                        250,            // Widget length
                        40,             // Widget width
                        (0 + 0 + 0),    // Option bits (See Widget Parameter Data Block Option Bits)
                        0,              // Minimum value
                        100,            // Maximum value
                        0x1082,         // Base color
                        0x0,            // Track fill color (from Right/Top to current position)
                        0x7E0,          // Track fill color (from Left/Bottom to current position)
                        30,             // Total Marker partition for Top/Left Side (0 for no ticks)
                        30,             // Total Marker partition for Bottom/Right Side (0 for no ticks)
                        2,              // Minor ticks between each major ticks T/L Side (0 for small ticks)
                        2,              // Minor ticks between each major ticks B/R Side (0 for small ticks)
                        10,             // Major tick length
                        0x7E0,          // Major tick color
                        5,              // Minor tick length
                        0x7E0,          // Minor tick color
                        FONT3,          // Value indicator font style
                        0xFFE0,         // Value indicator text color
                        0x1082,         // Slider knob bevel gradient color 1
                        0x9CD3,         // Slider knob bevel gradient color 2
                        GRAD_DOWN,      // Slider knob bevel gradient style
                        0x1082,         // Slider knob face gradient color 1
                        0x9CD3,         // Slider knob face gradient color 2
                        GRAD_UP         // Slider knob face gradient style
#END
SLIDER5_F_ORIENT_VERT                   //Set bit for vertical orientation
SLIDER5_F_TICKS                         //Set bit for enabling marker ticks*/
SLIDER5_F_VALUE_IND                     //Set bit for Enabling value indicator */
SLIDER5_F_PROGRESSBAR                   //Set bit for turning the slider into a gauge widget (Removes Knob)

Syntax: gfx_Slider5(va