Manual Workshop Comandos
Manual Workshop Comandos
Manual Workshop Comandos
DIABLO16
Embedded Graphics Processor
INTERNAL
FUNCTIONS
Document Revision: 2.10
Document Date: 1st February 2021
Table of Contents
1. 4DGL Introduction .................................................................................................. 15
2. Diablo16 Chip-Resident Functions Summary ........................................................... 16
2.1. GPIO Functions ................................................................................................................. 26
2.1.1 pin_Set(mode, pin) .................................................................................................... 27
2.1.2 pin_HI(pin) ................................................................................................................. 28
2.1.3 pin_LO(pin) ................................................................................................................ 29
2.1.4 pin_Val(pin) ............................................................................................................... 30
2.1.5 pin_Read(pin) ............................................................................................................ 31
2.1.6 bus_Read()................................................................................................................. 32
2.1.7 bus_Read8()............................................................................................................... 33
2.1.8 bus_Write8(value) ..................................................................................................... 34
2.1.9 bus_SetPins(value) .................................................................................................... 35
2.1.10 bus_ClearPins(value) ............................................................................................... 36
2.1.11 bus_SetChangeInterrupt (function, portmask) ....................................................... 37
2.1.12 Qencoder1(PHApin, PHBpin, mode)........................................................................ 38
2.1.13 Qencoder1Reset() ................................................................................................... 39
2.1.14 Qencoder2(PHApin, PHBpin, mode)........................................................................ 40
2.1.15 Qencoder2Reset() ................................................................................................... 41
2.1.16 pwm_Init(pin, mode, value) .................................................................................... 42
2.1.17 pin_Pulseout(pin, value).......................................................................................... 44
2.1.18 pin_Counter(pin, mode, OVFfunction) .................................................................... 45
2.1.19 ana_HS(rate, samples, IO1buf, IO2buf, IO3buf, IO4buf, userFunction).................. 47
2.1.20 pin_PulseoutCount(pin, frequency, count, function).............................................. 48
2.1.21 OW_Reset(pin) ........................................................................................................ 49
2.1.22 OW_Read(pin) ......................................................................................................... 50
2.1.23 OW_Read9(pin) ....................................................................................................... 51
2.1.24 OW_Write(pin, data) ............................................................................................... 52
2.1.25 NP_Write(pin, data, size, Options, RepeatFirst, Repeat, RepeatLast) .................... 54
2.2. System Memory Access Functions.................................................................................. 56
2.2.1 peekW(address) ........................................................................................................ 57
2.2.2 pokeW(address, word_value) ................................................................................... 58
2.3. Maths Functions ............................................................................................................... 59
2.3.1 ABS(value) ................................................................................................................. 60
2.3.2 MIN(value1, value2) .................................................................................................. 61
2.3.3 MAX(value1, value2) ................................................................................................. 62
2.3.4 SWAP(&var1, &var2) ................................................................................................. 63
2.3.5 SIN(angle) .................................................................................................................. 64
2.3.6 COS(angle) ................................................................................................................. 65
2.3.7 RAND() ....................................................................................................................... 66
1. 4DGL Introduction
The 4D-Labs family of embedded graphics processors (Goldelox, Picaso, Diablo16, PIXXI-28 and PIXXI-44) 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 Diablo16 Processor. This document
should be used in conjunction with the “4DGL-Programmers-Reference-Manual” document.
• ucmp_3232(&val1, &val2)
• gfx_Transparency(mode)
• gfx_FrameDelay(delay)
• gfx_ScreenMode(orientation)
• gfx_OutlineColour(colour)
• gfx_Contrast(value)
• gfx_LinePattern(pattern)
• gfx_BevelRadius (radius)
• gfx_BevelWidth(mode)
• gfx_BevelShadow(value)
• gfx_Xorigin(offset)
• gfx_Yorigin(offset)
• gfx_Arc(xc, radius, step, startangle, endangle, mode)
• gfx_CheckBox(state, x, y, width, height, boxColour, textColour, text)
• gfx_RadioButton(state, x, y, width, height, boxColour, textColour, text)
• gfx_FillPattern(patptr, mode)
• gfx_Gradient(style, x1, y1, x2, y2, colour1, colour2)
• gfx_RoundGradient(style, x1, y1, x2, y2, radius, colour1, colour2)
• gfx_PieSlice(cx, cy, spread, radius, step, startangle, endangle, mode)
• gfx_PointWithinBox(x, y, &rect)
• gfx_PointWithinRectangle(x, y, &recta)
• gfx_ReadBresLine(x1, y1, x2, y2, ptr)
• gfx_WriteBresLine(x1, y1, x2, y2, ptr)
• gfx_ReadGRAMarea(x1, y1, x1, y2, ptr)
• gfx_WriteGRAMarea(x1, y1, x2, y2, ptr)
• gfx_Surround(x1, y1, x2, y2, rad1, rad2, oct, colour)
• gfx_Scope(Left, Width, Yzero, n, Xstep, Yamp, Colourbg, &old_y1, &new_y1, Colour1, … &old_y4, &new_y4,
Colour4)
• gfx_RingSegment(x, y, Rad1, Rad2, starta, enda, colour)
• gfx_AngularMeter(value, &MeterRam, &MeterDef)
• gfx_Panel2(state, x, y, width, height, w1, w2, cl, cr, cf)
• gfx_Needle(value, &NeedleRam, &NeedleDef)
• gfx_Dial(value, &DialRam, &DialDef)
• gfx_Gauge(value, &GaugeRam, &GaugeDef)
• gfx_LedDigits(value, &LedDigitRam, &LedDigitDef)
• gfx_LedDigit(x, y, digitsize, oncolour, offcolour, value)
• gfx_Slider5(value, &SliderRam, &SliderDef)
• gfx_Switch(state, &SwitchRam, &SwitchDef)
• gfx_Button4(state, &gfx_ButtonRam, &gfx_ButtonDef)
• gfx_Led(state, &LedRam, &LedDef)
• gfx_Scale(&ScaleRam, &ScaleDef)
• gfx_RulerGauge(state, &RulerGaugeRam, &RulerGaugeDef)
• gfx_GradientShape(GradientRAM, HorzVert, OuterWidth, X, Y, W, H, TLrad, TRrad, BLrad, BRrad, Darken,
OuterColor, OuterType, OuterLevel, InnerColor, InnerType, InnerLevel, Split)
• gfx_GradientColor(Type, Darken, Level, H, Pos, Color)
• gfx_GradTriangleFilled(X0, Y0, X1, Y1, X2, Y2, SolidCol, GradientCol, GradientHeight, GradientY,
GradientLevel, Type)
• gfx_XYrotToVal(x, y, base, mina, maxa, minv, maxv)
• gfx_XYlinToVal(x ,y, base, minpos, maxpos, minv, maxv)
• widget_Realloc(handle, n)
• widget_GetWord(hndl, index, offset)
• widget_Setposition(hndl, index, xpos, ypos)
• widget_Enable(hndl, index)
• widget_Disable(hndl, index)
• widget_SetWord(hndl, index, offset, value)
• widget_SetAttributes(hndl, index, value)
• widget_ClearAttributes(hndl, index, value)
• widget_Touched(hndl, index)
• file_Unmount()
• file_PlayWAV
• file_Rename(oldname, newname)
• file_SetDate(handle, year, month, day, hour, minute, second)
• - file_CheckUpdate("Filename", "Options")
• flt_SQR(&result, &floatval)
• flt_LT(&floatA, &floatB)
• flt_EQ(&floatA, &floatB)
• flt_NE(&floatA, &floatB)
• flt_GT(&floatA, &floatB)
• flt_GE(&floatA, &floatB)
• flt_LE(&floatA, &floatB)
• flt_SGN(&floatval)
• flt_FTOI(&floatval)
• flt_ITOF(&fresult, &var16)
• flt_UITOF(&fresult, &uvar16)
• flt_LTOF(&fresult, &var32)
• flt_ULTOF(&fresult, &uvar32)
• flt_VAL(&float1, mystring)
• flt_PRINT(&fvalue, formatstring)
• flt_PRINTxy(x, y, &fvalue, formatstring)
Returns nothing
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 millsecond, otherwise touch behaviour could be eratic.
2.1.2 pin_HI(pin)
Syntax pin_HI(pin);
Arguments pin
pin A value (usually a constant) specifying the pin number or a predefined pin name.
The arguments can be a variable, array element, expression or constant.
Returns value
value Returns a Logic 1 (0x0001) if the pin number is legal.
Description 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.
Note 1: 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.
2.1.3 pin_LO(pin)
Syntax pin_LO(pin);
Arguments pin
pin A value (usually a constant) specifying the pin number or a predefined pin name.
The arguments can be a variable, array element, expression or constant.
Returns value
value Returns a Logic 1 (0x0001) if the pin number is legal.
Description 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.
Note 1: 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.
2.1.4 pin_Val(pin)
Returns value
value Returns a Logic 1 (0x0001) if the pin number is legal.
Description
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.
Example temp := 3;
pin_Val(PA4, temp); // output a Logic 3 on the PA4 pin
Note 1: 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.
2.1.5 pin_Read(pin)
Syntax pin_Read(pin);
Arguments pin
pin A value (usually a constant) specifying the pin number or a predefined pin name.
The arguments can be a variable, array element, expression or constant.
Returns value
value Returns state of the pin a Logic 0 (0x0001) or 1 (0x0001) if the pin is set to digital
input.
Returns state of the output latch, a Logic 0 (0x0001) or 1 (0x0001) if the pin is set to
digital output.
Returns 12 bit analogue value if the pin is set to an analogue pin.
Description 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.
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 millsecond, otherwise touch
behaviour could be eratic.
Note 1: 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.
2.1.6 bus_Read()
Syntax bus_Read();
Arguments none
Returns value
value Returns the 16 bit value of the bus.
Description 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.
Example var1 := bus_Read(); //Read the 16bit value off PA0-PA15 pins
Note 1: 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.
2.1.7 bus_Read8()
Syntax bus_Read8();
Arguments none
Returns value
value Returns the state of the 8 bit bus as an 8bit value.
Description 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.
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 lower byte of var1 will get loaded with the state of the bus.
2.1.8 bus_Write8(value)
Syntax bus_Write8(value);
Arguments value
value The lower 8 bits of value are sent to the 8 bit bus.
The argument can be a variable, array element, expression or constant.
Returns nothing
Description 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.
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
2.1.9 bus_SetPins(value)
Syntax bus_SetPins(value);
Arguments value
value A value (usually a constant) specifying the pin number. Bit 0 corresponds to PA0
through to bit9 which corresponds to PA9.
The arguments can be a variable, array element, expression or constant.
Returns Nothing
Description
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 disable for the selected pins.
Note 1: 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.
2.1.10 bus_ClearPins(value)
Syntax bus_ClearPins(value);
Arguments value
value A value (usually a constant) specifying the pin number. Bit 0 corresponds to PA0
through to bit9 which corresponds to PA9.
The arguments can be a variable, array element, expression or constant.
Returns Nothing
Description 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.
Note 1: 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.
Returns value
value Return 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
Description
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.
Note 1: 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.
Returns Nothing
Description 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.
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
Note 1: 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.
2.1.13 Qencoder1Reset()
Syntax Qencoder1Reset();
Arguments None
Returns Nothing
Returns Nothing
Description 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.
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
2.1.15 Qencoder2Reset()
Syntax Qencoder2Reset();
Arguments None
Returns Nothing
Returns Status Returns TRUE if the pin number is legal, usually ignored
Description 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:
The pwm_Init is non-blocking and the pwm continues until turned off
PA6 50 Yes
PA7 51 Yes
PA8 52 Yes
PA9 53 Yes
PA10 43 No
PA11 44 No
PA12 31 No
PA13 32 No
PA14 37 No
PA15 36 No
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(pin, value); or
Syntax
pin_PulseoutB(pin, value)
Description 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
occuring, and pulses can occur on multiple pins simultaneously.
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.
Returns Nothing
Description 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)
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 transistions
should not exceed a few Khz in mode 1 and 2 and are usually used for simple process control counting.
func userFunc()
print("Hello World");
endfunc
Returns Nothing
Description 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
Note: If Touch is enabled this function should be called no more than once per millsecond, otherwise
touch behaviour could be eratic.
func myFunc()
//do something once samples collected
Endfunc
Returns TRUE if the pin number is legal and the frequency is at least 10Hz and the maximum number
Returns
of 3 simlutaneous pulseoutCount pins is not exceeded
Description
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.
2.1.21 OW_Reset(pin)
Syntax OW_Reset(pin);
Arguments pin
pin 4D predefined Pin Name, see table below.
The arguments can be a variable, array element, expression or constant.
Returns result
result Reset, and returns the status of the ONEWIRE device
0 = ACK
1 = No Activity
(refer to Dallas 1wired documentation for further information)
Note 1: 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.
2.1.22 OW_Read(pin)
Syntax OW_Read(pin);
Arguments pin
Pin 4D predefined Pin Name, see table below.
The arguments can be a variable, array element, expression or constant.
Returns value
value A word holding the lower 8 bits contain data bits received from the 1-Wire device.
Note 1: 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.
2.1.23 OW_Read9(pin)
Syntax OW_Read9(pin);
Arguments pin
Pin 4D predefined Pin Name, see table below.
The arguments can be a variable, array element, expression or constant.
Returns value
value A word holding 9 or more data bits received from the 1-Wire device.
Description 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) Diablo16 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 52 Yes
PA9 53 Yes
PA10 43 Yes
PA11 44 Yes
PA12 31 Yes (See Note 1)
PA13 32 Yes (See Note 1)
PA14 37 No
PA15 36 No
Note 1: 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.
Returns Nothing
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.3v
// 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); // skip 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 1: 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.
Returns value
value Returns TRUE if the pin number is legal (usually ignored)
Description 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.
Note 1: 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.
2.2.1 peekW(address)
Syntax peekW(address);
Arguments address
address The address of a memory word. The address is usually a pre-defined system register
address constant, (see the address constants for all the system word sized registers
in section 3).
The arguments can be a variable, array element, expression or constant.
Returns word_value
word_value The 16 bit value stored at address.
Note: that the txt_Set variables (0-15) and gfx_set variables (16-31) can also be accessed with peekW
and pokeW.
This example places the low word of the 32 bit system timer in myvar.
Returns None
Note: that the txt_Set variables (0-15) and gfx_set variables (16-31) can also be accessed with peekW
and pokeW.
2.3.1 ABS(value)
Syntax ABS(value);
Arguments value
value A variable, array element, expression or constant.
The arguments can be a variable, array element, expression or constant.
Returns value
value Returns the absolute value.
Returns value
value The smaller of the two values.
Description This function returns the the smaller of value1 and value2.
Returns value
value The larger of the two values.
Returns nothing
Description Given the addresses of two variables (var1 and var2), the values at these addresses are swapped.
This example swaps the values in number1 and number2. After the function is executed, number1
will hold 66, and number2 will hold 33.
2.3.5 SIN(angle)
Syntax SIN(angle);
Arguments angle
angle The angle in degrees. (Note: The input value is automatically shifted to lie within 0-
359 degrees)
The arguments can be a variable, array element, expression or constant.
Returns result
result The sine in radians of an argument specified in degrees. The returned value range is
from 127 to -127 which is a more useful representation for graphics work. The real
sine values vary from 1.0 to -1.0 so appropriate scaling must be done in user code as
required.
2.3.6 COS(angle)
Syntax COS(angle);
Arguments angle
angle The angle in degrees. (Note: The input value is automatically shifted to lie within 0-
359 degrees)
The arguments can be a variable, array element, expression or constant.
Returns result
result The cosine in radians of an argument specified in degrees. The returned value range
is from 127 to -127 which is a more useful representation for graphics work. The real
sine values vary from 1.0 to -1.0 so appropriate scaling must be done in user code as
required.
2.3.7 RAND()
Syntax RAND();
Arguments none
Returns value
value Returns a pseudo random signed number ranging from -32768 to +32767 each time the
function is called. The random number generator may first be seeded by using the
SEED(number) function. The seed will generate a pseudo random sequence that is
repeatable. You can use the modulo operator (%) to return a number within a certain
range, eg n := RAND() % 100; will return a random number between -99 and +99. If you
are using random number generation for random graphics points, or only require a
positive number set, you will need to use the ABS function so only a positive number is
returned, eg: X1 := ABS(RAND() % 100); will set co-ordinate X1 between 0 and 99.
Note that if the random number generator is not seeded, the first number returned after
reset or power up will be zero. This is normal behavior.
Description This function returns a pseudo random signed number ranging from -32768 to +32767
Example SEED(1234);
print(RAND(),", ",RAND());
Returns value
value A random number between low and high limits.
The arguments can be a variable, array element, expression or constant.
Description Returns a random number between low and high limits such that low <= N < high The random number
generator may first be seeded by using the SEED(number) function.
Note: The lower limit is inclusive, but the upper limit is exclusive.
Note: If the random number generator is not seeded, the first number returned after reset or power
up will be the low number in the range. This is normal behaviour.
Example SEED(1234);
print(RAND(),", ",RAND());
2.3.9 SEED(number)
Syntax SEED(number);
Arguments number
number Specifies the seed value for the pseudo random number generator.
The arguments can be a variable, array element, expression or constant.
Returns nothing
Description This function seeds the pseudo random number generator so it will generate a new repeatable
sequence. The seed value can be a positive or negative number.
Example SEED(-50);
print(RAND(),", ",RAND());
2.3.10 SQRT(number)
Syntax SQRT(number);
Arguments number
number Specifies the positive number for the SQRT function.
The arguments can be a variable, array element, expression or constant.
Returns value
value This function returns the integer square root which is the greatest integer less than or
equal to the square root of number.
This example returns 161 in variable myvar which is the integer square root of 26000.
2.3.11 OVF()
Syntax OVF();
Arguments none
Returns value
value The high order 16 bits from certain math and shift functions.
Description This function returns the high order 16 bits from certain math and shift functions. It is extremely
useful for calculating 32 bit address offsets for MEDIA access.
It can be used with the shift operations, addition, subtraction, multiplication and modulus operations.
This example will print 0x05F5E100 to the display , which is 100,000,000 in hexadecimal
2.3.12 CY()
Syntax CY();
Arguments none
Returns Status
Status Returns Status of carry, 0 or 1.
Description This function returns the carry status of an unsigned overflow from any 16 or 32bit additions or
subtractions.
2.3.13 EVE_SP()
Syntax EVE_SP();
Arguments None
Returns value
value Returns the current stack level.
Description Used for debugging to assess the current stack level, mainly for checking stack leaks.
2.3.14 EVE_SSIZE()
Syntax EVE_SSIZE();
Arguments None
Returns value
value Returns the stack size.
Description Used to get the current stack size. Mainly for debugging purposes.
Example print(EVE_SSIZE());
Prints stack size on the screen.
Returns value
value Returns 1 on 32bit unsigned overflow (carry). Carry flag is also set on 32bit unsigned
overflow and can be read with the CY() function.
Description Performs an unsigned addition of 2 x 32bit values placing the 32bit result in a 2 word array.
Returns Value
Value Returns 1 on 32bit unsigned overflow (carry). Carry flag is also set on 32bit unsigned
overflow and can be read with the CY() function.
Description Performs an unsigned subtraction of 2 x 32bit values placing the 32bit result in a 2 word array.
Returns Pointer
Pointer Returns a pointer to the 32bit result. Carry and overflow are not affected.
Description Performs an unsigned multiply of 2 x 16bit values placing the 32bit result in a 2 word array.
Returns Pointer
Pointer Returns a pointer to the 32bit result. Carry and overflow are not affected.
Description Performs an unsigned division of 2 x 32bit values placing the 32bit result in a 2 word array.
Note: A division by zero will result is 0xFFFFFFFF
Returns value
value 0 if equal
1 if val1 > val2
-1 if val1 < val2
valA[0] := 0;
valA[1] := 0xFFFF;
valB[0] := 0;
valB[1] := 0xEFFF;
Returns nothing
Moves the text cursor to a screen position set by line and column parameters. The line and column
position is calculated, based on the size and scaling factor for the currently selected font. When text
is outputted to screen it will be displayed from this position. The text position could also be set with
gfx_MoveTo(...); if required to set the text position to an exact pixel location. Note that lines and
Description columns start from 0. So, line 0, column 0 is the top left corner of the display.
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).
This example moves the text origin to the 5th line and the 10th column.
2.4.2 putch(char)
Syntax putch(char);
Arguments char
Returns nothing
Description putch prints single characters to the current output stream, usually the display.
Example var v;
v := 0x39;
putch(v); // print the number 9 to the current display location
putch('\n'); // newline
Returns nothing
Example var v;
v := 0x39;
putchXY(10, 20, v); // print the number 9 to x,y (10,20)
putch('\n'); // newline
2.4.4 putstr(pointer)
Syntax putstr(string);
Arguments string
string A string constant, a word pointer to a string, a pointer to an array, or a pointer to a
data statement. Note that for a byte aligned RAM string you need to use str_Printf
Returns source
source Returns the pointer to the item that was printed.
Description putstr and, similarly print([STR] x); operate on constant strings in Flash, or word aligned strings in
RAM.
putstr prints a string to the current output stream, usually the display.
Note: The string constants and data statement pointers are byte aligned.
Note: putstr is more efficient than print for printing single strings.
Note: The output of putstr can be redirected to the communications port, the media, or memory
using the to(...); function.
A string constant is automatically terminated with a zero.
A string in a data statement is not automatically terminated with a zero.
All variables in 4DGL are 16bit, if an array is used for holding 8 bit characters; each array element
packs 1 or 2 characters.
Example //==================================================
// Example #1 – print a string constant
//==================================================
//==================================================
// Example #2 – print string via pointer
//==================================================
var p; // a var for use as a pointer
p := "String Constant\n"; // assign a string constant to pointer s
putstr(p); // print the string using the pointer
putstr(p+8); // print, offsetting into the string
//==================================================
// Example #3 – printing strings from data table
//==================================================
#DATA
byte message "Week",0
word days sun,mon,tue,wed,thu,fri,sat // pointers to data items
byte sun "Sunday\n\0"
byte mon "Monday\n\0"
byte tue "Tuesday\n\0"
byte wed "Wednesday\n\0"
byte thu "Thursday\n\0"
byte fri "Friday\n\0"
byte sat "Saturday\n\0"
#END
var n;
putstr
n:=0;
while(n < 7)
putstr(days[n++]); // print the days
wend
Returns nothing
Example //==================================================
// Example #1 – print a string constant
//==================================================
//==================================================
// Example #2 – print string via pointer
//==================================================
var p; // a var for use as a pointer
p := "String Constant\n"; // assign a string constant to pointer s
putstr(p); // print the string using the pointer
putstr(5, 10, p+8); // print at 5,10, offsetting into the string
//==================================================
// Example #3 – printing strings from data table
//==================================================
#DATA
byte message "Week",0
word days sun,mon,tue,wed,thu,fri,sat // pointers to data items
byte sun "Sunday\0"
byte mon "Monday\0"
byte tue "Tuesday\0"
byte wed "Wednesday\0"
byte thu "Thursday\0"
byte fri "Friday\0"
byte sat "Saturday\0"
#END
var n; n:=0;
while(n < 7)
putstrXY(0, n+10, days[n++]); // print the days
wend
Returns nothing
Note: The string constants and data statement pointers are byte aligned.
Argume
format, value
nts
format A constant that specifies the number format.
value The number to be printed.
bit 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
| | | | \___ ___/ \__ __/ \_____ _____/
| | | | V V V
| | | | | | |
| | | | | | |
| | | | (nb 0 = 16) | |____BASE (usually 2, 10 or 16)
| | | | displayed |
| | | | digit qty |
| | | | |___reserved
| | | |
| | | |
| | | |______ 1 = leading zeros included
| | | 0 = leading zeros suppressed
| | |
| | |_______ 1 = leading zero blanking
| | 0 = Show Zeros
| |
| |_____ sign bit (0 = signed, 1 = unsigned)
|
|______ 1 = space before unsigned number
0 = no space
DEC DECZ DECZB UDEC UDECZ UDECZB HEX HEXZ HEXZB BIN BINZ BINZB
DEC1 DEC1Z DEC1ZB UDEC1 UDEC1Z UDEC1ZB HEX1 HEX1Z HEX1ZB BIN1 BIN1Z BIN1ZB
DEC2 DEC2Z DEC2ZB UDEC2 UDEC2Z UDEC2ZB HEX2 HEX2Z HEX1ZB BIN2 BIN2Z BIN2ZB
DEC3 DEC3Z DEC3ZB UDEC3 UDEC3Z UDEC3ZB HEX3 HEX3Z HEX1ZB BIN3 BIN3Z BIN3ZB
DEC4 DEC4Z DEC4ZB UDEC4 UDEC4Z UDEC4ZB HEX4 HEX4Z HEX1ZB BIN4 BIN4Z BIN4ZB
Returns field
field Returns the the default width of the numeric field (digit count), usually ignored.
Descript
putnum prints a 16bit number in various formats to the current output stream, usually the display.
ion
Example var v;
v := 05678;
putnum(HEX, v); // print the number as hex 4 digits
putnum(BIN, v); // print the number as binary 16 digits
2.4.8 print(...)
Syntax print(...);
Returns nothing
Description 4DGL has a versatile print(...) statement for formatting numbers and strings. In it's simplest form,
print will simply print a number as can be seen below:
myvar := 100;
print(myvar);
This will print 100 to the current output device (usually the display in TEXT mode). Note that if you
wish to add a string anywhere within a print(...) statement, just place a quoted string expression and
you will be able to mix strings and numbers in a variety of formats. See the following example.
print("the value of myvar is :- ", myvar, "and its 8bit binary representation is:-", [BIN8]myvar);
* Refer the the table in putnum(..) for all the numeric representations available.
The print(...) statement will accept directives passed in square brackets to make it print in various
ways, for instance, if you wish to print a number in 4 digit hex, use the [HEX4] directive placed in front
of the variable to be displayed within the print statement. See the following example.
print("myvar as a 4 digit HEX number is :- ", [HEX4]myvar);
Note that there are 2 print directives that are not part of the numeric set and will be explained
separately. these are the [STR] and [CHR] directives.
Note that you can freely mix string pointers, strings, variables and expressions within a print
statement. print(...) can also use the to(...) function to redirect it's output to a different output device
other than the screen using the function (refer to the to(...) statement for further examples).
#DATA
word myData
myString1, Bert, Fred, main, myString2, baud, barney,
0x1111,0x2222,0x3333,0x4444
func main()
var fn; // a variable for a handle for the function
txt_Set(FONT_ID, FONT_1);
repeat forever
endfunc
2.4.9 to(outstream)
Syntax to(outstream);
Arguments outstream
outstream A variable or constant specifying the destination for the putch, putstr, putnum,
print and str_Printf functions.
Returns nothing
Description to() sends the printed output to destinations other than the screen. Normally, print just sends its
output to the display in TEXT mode which is the default, however, the output from print can be sent
to 'streams', eg – COM0, COM1, COM2, or COM3, an open FAT16 file with DSK, to raw media with
MDA (media), or to the I2C ports with I2C1, I2C2 or I2C3.
The to(...) function can also stream to a memory array . Note that once the to(...) function has taken
effect, the stream reverts back to the default stream which is TEXT as soon as putch, putstr, putnum,
print, or str_Printf has completed its action.
The APPEND argument is used to append the printed output to the same place as the previous
redirection. This is most useful for building string arrays, or adding sequential data to a media stream.
Example //==================================================
// Example #1 – putstr redirection
//==================================================
var buf[10]; // a buffer that will hold up to 20 bytes/chars
2.4.10 charwidth('char')
Syntax charwidth('char');
Arguments 'char'
'char' The ascii character for the width calculation.
Returns width
width Returns the width of a single character in pixel units.
Description charwidth is used to calculate the width in pixel units for a character, based on the currently selected
font.
Example //==================================================
// Example
//==================================================
str := "HELLO\nTHERE"; // note that this string spans 2 lines due
// to the \n.
width := strwidth(str); // get the width of the string, this will
// also capture the height.
height := strheight(); // note, invoking strwidth also calcs height
// which we can now read.
// The string above spans 2 lines, strheight(.) will calculate height
// correctly for multiple lines.
len := strlen(str); // the strlen() function returns the number
// of characters in a string.
print("\nLength=",len); // NB:- the \n in "HELLO\nTHERE" is counted
// as a character.
txt_FontID(MS_SanSerif8x12); // select this font
w := charwidth('W'); // get a characters width
h := charheight('W'); // and height
txt_FontID(0); // back to default font
print ("\n'W' is " ,w, " pixels wide"); // show width of a character
// 'W' in pixel units.
print ("\n'W' is " ,h, " pixels high"); // show height of a character
// 'W' in pixel units.
2.4.11 charheight('char')
Syntax charheight('char');
Arguments 'char'
'char' The ascii character for the height calculation.
Returns width
width Returns the height of a single character in pixel units.
Description charheight is used to calculate the height in pixel units for a character, based on the currently selected
font.
2.4.12 strwidth(pointer)
Syntax strwidth(pointer);
Arguments pointer
pointer The pointer to a zero (0x00) terminated string.
'pointer' may be a constant or pointer to word aligned variable.
Returns width
width Returns the width of a string in pixel units, can be multi line.
Description strwidth returns the width of a zero terminated string in pixel units. Note that any string constants
declared in your program are automatically terminated with a zero as an end marker by the compiler.
Any string that you create in the DATA section or MEM section must have a zero added as a terminator
for this function to work correctly.
2.4.13 strheight()
Syntax strheight();
Arguments none
Returns height
height Returns the height of a string in pixel units, can be multi line.
Description strheight returns the height of a zero terminated string in pixel units. The strwidth function must be
called first which makes available width and height. Note that any string constants declared in your
program are automatically terminated with a zero as an end marker by the compiler. Any string that
you create in the DATA section or MEM section must have a zero added as a terminator for this
function to work correctly.
2.4.14 strlen(pointer)
Syntax strlen(pointer);
Arguments pointer
pointer The pointer to a zero (0x00) terminated string.
Returns length
length Returns the length of a string in character units.
Description strlen returns the length of a zero terminated string in character units. Note that any string constants
declared in your program are automatically terminated with a zero as an end marker by the compiler.
Any string that you create in the DATA section or MEM section must have a zero added as a terminator
for this function to work correctly.
Returns count
count Returns count of characters in the set.
Description After selecting a Unicode image control with txt_FontID, this function is called to set the required
font within the Unicode set. The file "Unicode.inc" contains wrappers for this function, and it is not
normally called directly.
Returns nothing
Description Given a function number and a value, set the required text control parameter, such as size, colour,
and other formatting controls. This function is extremely useful in a loop to select multiple parameters
from a data statement or a control array. Note also that each function available for txt_Set has a single
parameter 'shortcut' function that has the same effect.
(see the Single parameter short-cuts for the txt_Set functions next page)
function value
# Predefined Name Description
0 TEXT_COLOUR Set the text foreground colour Colour 0-65535
Default = LIME
1 TEXT_HIGHLIGHT Set the text background colour Colour 0-65535
Default = BLACK
2 FONT_ID Set the required font.
System_5x7 1 or FONT_1
System_8x8 2 or FONT_2
System_8x12 3 or FONT_3
System_12x16 4 or FONT_4
MS_SanSerif8x12 5 or FONT_5
dejaVuSans9pt 6 or FONT_6
dejaVuSansBold9pt 7 or FONT_7
dejaVuSansCondensed9pt 8 or FONT_8
System_3x6 9 or FONT_9
plotted 10 or FONT_10
EGA 8x12 font 11 or FONT_11
Note: The value could be the name of a custom font included Default = FONT_3
in a users program in a data statement.
3 TEXT_WIDTH Set the text width multiplier. Text will be printed magnified 1 to 16
horizontally by this factor Default = 1
4 TEXT_HEIGHT Set the text height multiplier. Text will be printed magnified 1 to 16
vertically by this factor. Default = 1
5 TEXT_XGAP Set the pixel gap between characters. The gap is in pixel units 0 to 32
Default = 0
6 TEXT_YGAP Set the pixel gap between lines. The gap is in pixel units. 0 to 32
Default = 0
7 TEXT_PRINTDELAY Set the delay between character printing to give a 'teletype' 0 to 255
like effect. Default = 0msec
8 TEXT_OPACITY Selects whether or not the 'background' pixels are drawn 0 or TRANSPARENT
(default mode is OPAQUE) 1 or OPAQUE
Default = 0
9 TEXT_BOLD Sets Bold Text mode for the next string or char. The feature 0 or 1 (OFF or ON)
automatically resets after printing using putstr or print has
completed.
10 TEXT_ITALIC Sets Italic Text mode for the next string or char. The feature 0 or 1 (OFF or ON)
automatically resets after printing using putstr or print has
completed.
11 TEXT_INVERSE Sets Inverse Text mode for the next string or char. The feature 0 or 1 (OFF or ON)
automatically resets after printing using putstr or print has
completed.
12 TEXT_UNDERLINED Sets Underlined Text mode for the next string or char. The 0 or 1 (OFF or ON)
feature automatically resets after printing using putstr or print
has completed.
13 TEXT_ATTRIBUTES Allows a combination of text attributes to be defined together 16 or BOLD
by 'or'ing the bits together. The feature automatically resets 32 or ITALIC
after printing using putstr or print has completed. 64 or INVERSE
128 or UNDERLINED
Example:
txt_Set(TEXT_ATTRIBUTES, BOLD | INVERSE); // bold + inverse
Note: The value could also be the name of a custom font Default = FONT_3
included in a users program in a data statement, or the handle
Returns font
font Returns the current font before the change.
Description Enables the usage of fonts stored in banks. See the FontInBankTest and
BookAntiqua2032FontsInBank1 samples. If a single font is the only thing in a bank its address will be
7, otherwise look in the .lst file from the compile to find the address of the font. Assuming there is
space available multiple fonts can be stored in the same bank.
Example txt_FontBank(FONTBANK_1, 7) ;
Returns field
field Returns the the default width of the numeric field (digit count), usually ignored.
Description putnumXY prints a 16bit number in various formats to the current output stream, usually the display
at the specified position. The Formats are the same as for the putnum command
Example var v;
v := 05678;
putnumXY(0, 0, HEX, v); // print the number as hex 4 digits
putnumXY(0, 20, BIN, v); // print the number as binary 16 digits
2.5.1 isdigit(char)
Syntax isdigit(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
0: Character is not as ASCII digit
Status
1: Character is an ASCII digit.
Description Tests the character parameter and returns a 1 if the character is an ASCII digit else returns a 0.
Valid range: "0123456789".
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
endfunc;
2.5.2 isxdigit(char)
Syntax isxdigit(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
0: Character is not as ASCII hexadecimal digit
Status
1: Character is an ASCII hexadecimal digit.
Description Tests the character parameter and returns a 1 if the character is an ASCII hexadecimal digit else returns
a 0.
Valid range: "0123456789ABCDEF".
2.5.3 isupper(char)
Syntax isupper(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
0: Character is not an ASCII upper case letter.
Status
1: Character is an ASCII upper case letter.
Description 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".
2.5.4 islower(char)
Syntax islower(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
0: Character is not an ASCII lower case letter
Status
1: Character is an ASCII lower case letter.
Description 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".
2.5.5 isalpha(char)
Syntax isalpha(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
0: Character is not as ASCII lower or upper case letter.
Status
1: Character is an ASCII lower or upper case letter..
Description 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”
2.5.6 isalnum(char)
Syntax isalnum(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
0: Character is not as ASCII Alphanumeric character.
Status
1: Character is an ASCII Alphanumeric character.
Description 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”
2.5.7 isprint(char)
Syntax isprint(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
0: Character is not a printable ASCII character.
Status
1: Character is a printable ASCII character.
Description Tests the character parameter and returns a 1 if the character is a printable ASCII character else
returns a 0.
Valid range : 0x20... 0x7F
2.5.8 isspace(char)
Syntax isspace(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
0: Character is not a space type character.
Status
1: Character is a space type character.
Description 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.
2.5.9 toupper(char)
Syntax toupper(char);
Arguments char
char Specifies the ASCII character for the test.
Returns char
“ABCD...WXYZ”: If character is lower case letter.
char
char: If character is not a lower case letter.
Description 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".
ch := serin();
if (ch != -1)
print( [CHR] ch ); // if a key was received from PC,
// 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;
2.5.10 tolower(char)
Syntax tolower(char);
Arguments char
char Specifies the ASCII character for the test.
Returns Status
“abcd...wxyz”: If character is upper case letter.
Status
char: If character is not a upper case letter...
Description 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".
2.5.11 LObyte(var)
Syntax LObyte(var);
Arguments var
var User variable.
Returns byte
byte Returns the lower byte (lower 8 bit) of a 16 bit variable.
2.5.12 HIbyte(var)
Syntax Hibyte(var);
Arguments var
var User variable.
Returns byte
byte Returns the upper byte (upper 8 bits) of a 16 bit variable.
2.5.13 ByteSwap(var)
Syntax ByteSwap(var);
Arguments var
var User variable.
Returns value
value Returns the endian swapped value of a 16 bit variable.
Description Returns the swapped upper and lower bytes of a 16 bit variable.
2.5.14 NybleSwap(var)
Syntax NybleSwap(var);
Arguments var
var User variable.
Returns value
value Returns the 16 bit variable with swapped lower nybles
Description Returns the swapped lower bytes nybles, upper byte retained
• gfx_TransparentColour(colour)
• gfx_Transparency(mode)
• gfx_FrameDelay(delay)
• gfx_ScreenMode(orientation)
• gfx_OutlineColour(colour)
• gfx_Contrast(value)
• gfx_LinePattern(pattern)
• gfx_BevelRadius(radius)
• gfx_BevelWidth(mode)
• gfx_BevelShadow(value)
• gfx_Xorigin(offset)
• gfx_Yorigin(offset)
• gfx_Arc(xc, radius, step, startangle, endangle, mode)
• gfx_CheckBox(state, x, y, width, height, boxColour, textColour, text)
• gfx_RadioButton(state, x, y, width, height, boxColour, textColour, text)
• gfx_FillPattern(patptr, mode)
• gfx_Gradient(style, x1, y1, x2, y2, colour1, colour2)
• gfx_RoundGradient(style, x1, y1, x2, y2, radius, colour1, colour2)
• gfx_PieSlice(cx, cy, spread, radius, step, startangle, endangle, mode)
• gfx_PointWithinBox(x, y, &rect)
• gfx_PointWithinRectangle(x, y, &recta)
• gfx_ReadBresLine(x1, y1, x2, y2, ptr)
• gfx_WriteBresLine(x1, y1, x2, y2, ptr)
• gfx_ReadGRAMarea(x1, y1, x1, y2, ptr)
• gfx_WriteGRAMarea(x1, y1, x2, y2, ptr)
• gfx_Surround(x1, y1, x2, y2, rad1, rad2, oct, colour)
• gfx_Scope(Left, Width, Yzero, n, Xstep, Yamp, Colourbg, &old_y1, &new_y1, Colour1, … &old_y4,
&new_y4, Colour4)
• gfx_RingSegment(x, y, Rad1, Rad2, starta, enda, colour)
• gfx_AngularMeter(value, &MeterRam, &MeterDef)
• gfx_Panel2(state, x, y, width, height, w1, w2, cl, cr)
• gfx_Needle(value, &NeedleRam, &NeedleDef)
• gfx_Dial(value, &DialRam, &DialDef)
• gfx_Gauge(value, &GaugeRam, &GaugeDef)
• gfx_LedDigits(value, &LedDigitRam, &LedDigitDef)
• gfx_LedDigit(x, y, digitsize, oncolour, offcolour, value)
• gfx_Slider5(value, &SliderRam, &SliderDef)
• gfx_Switch(state, &SwitchRam, &SwitchDef)
• gfx_Button4(state, &gfx_ButtonRam, &gfx_ButtonDef)
• gfx_Led(state, &LedRam, &LedDef)
• gfx_Scale(&ScaleRam, &ScaleDef)
• gfx_RulerGauge(value, &RulerGaugeRam, &RulerGaugeDef)
• gfx_GradientShape(GradientRAM, HorzVert, OuterWidth, X, Y, W, H, TLrad, TRrad, BLrad, BRrad,
Darken, OuterColor, OuterType, OuterLevel, InnerColor, InnerType, InnerLevel, Split)
• gfx_GradientColor(Type, Darken, Level, H, Pos, Color)
• gfx_GradTriangleFilled(X0, Y0, X1, Y1, X2, Y2, SolidCol, GradientCol, GradientHeight, GradientY,
GradientLevel, Type)
• gfx_XYrotToVal(x, y, XYROT_EAST, starta, enda, minv, maxv)
• gfx_XYlinToVal(x, y, base, minpos, maxpos, minv, maxv)
2.6.1 gfx_Cls()
Syntax gfx_Cls();
Arguments none
Returns nothing
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
Description
• 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.
Example gfx_BGcolour(DARKGRAY);
gfx_Cls();
oldColour Specifies the sample colour to be changed within the clipping window.
Specifies the new colour to change all occurrences of old colour within the clipping
newColour
window.
The arguments can be a variable, array element, expression or constant
Returns nothing
Description Changes all oldColour pixels to newColour within the clipping area.
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.
Returns nothing
Description Draws a circle with centre point x1, y1 with radius r using the specified colour.
NB: 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.
This example draws a BLUE circle outline centred at x=50, y=50 with a radius of 30 pixel units.
Returns nothing
Description 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.
NB:- The PEN_SIZE is ignored, the circle is always drawn SOLID.
Returns nothing
Description 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.
This example draws a RED line from x1=10, y1=10 to x2=100, y2=100
Returns nothing
Description Draws a fast horizontal line from x1 to x2 at vertical co-ordinate y using colour.
This example draws a fast RED horizontal line at y=50, from x1=10 to x2=80
Returns nothing
Description Draws a fast vertical line from y1 to y2 at horizontal co-ordinate x using colour.
This example draws a fast RED vertical line at x=20, from y1=30 to y2=70
Returns nothing
Description Draws a rectangle from x1, y1 to x2, y2 using the specified colour. The line may be tessellated with
the gfx_LinePattern(...) function.
NB: 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.
This example draws a GREEN rectangle from x1=10, y1=10 to x2=30, y2=30
Returns nothing
Description 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.
Returns nothing
Description 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.
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.
Returns nothing
Description 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.
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;
// 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
// 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
Returns nothing
Description 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.
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
Returns nothing
Description 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.
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
2.6.14 gfx_Dot()
Syntax gfx_Dot();
Arguments none
Returns nothing
Description Draws a pixel at the current origin using the current object colour.
Example gfx_MoveTo(40,50);
gfx_ObjectColour(0xRED);
gfx_Dot();
2.6.15 gfx_Bullet(radius)
Syntax gfx_Bullet(radius);
Arguments radius
Returns nothing
Description Draws a circle or 'bullet point' with radius r at at the current origin using the current object colour.
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(...).
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 nothing
Description 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.
This example sets the variables that will receive the result from a gfx_Orbit(..) function call
distance Specifies the distance from the origin to the remote point in pixel units.
The arguments can be a variable, array element, expression or constant
Returns nothing
Note: result is stored in the variables that were specified with the gfx_OrbitInit(..) function.
Description 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.
Arguments x, y, colour
x, y Specifies the screen coordinates of the pixel.
Returns nothing
2.6.19 gfx_GetPixel(x, y)
Arguments x, y
x, y Specifies the screen coordinates of the pixel colour to be returned.
Returns colour
colour The 8 or 16bit colour of the pixel (default 16bit).
This example print 1234, the colour of the pixel that was previously placed.
Returns nothing
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).
func help()
var x, y, state;
print("TOUCHE ME");
while(1)
state := touch_Get(TOUCH_STATUS); // Look for touch activity
x := touch_Get(TOUCH_GETX); // Grab x and the
y := touch_Get(TOUCH_GETY); // y coordinates of the touch
Returns nothing
Description Moves the origin to a new position relative to the old position.
This example draws a pixel using the current object colour at x=5, y=17
2.6.22 gfx_IncX()
Syntax gfx_IncX();
Arguments none
Returns old_origin
old_origin Returns the current X origin before the increment.
Description 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.
Example var n;
gfx_MoveTo(20,20);
n := 96;
while (n--)
gfx_ObjectColour(n/3);
gfx_Bullet(2);
gfx_IncX();
wend
2.6.23 gfx_IncY()
Syntax gfx_IncY();
Arguments none
Returns old_Yorigin
old_Yorigin Returns the current Y origin before the increment.
Description 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.
Example var n;
gfx_MoveTo(20,20);
n := 96;
while (n--)
gfx_ObjectColour(n/3);
gfx_LineRel(20, 0);
gfx_IncY();
wend
ypos Specifies the vertical position of the line end as well as the new origin.
The arguments can be a variable, array element, expression or constant
Returns nothing
Description 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.
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.
Returns nothing
Description 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.
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: that gfx_LinePattern(0); must be used after this to return line drawing to normal solid lines.
Arguments x2, y2
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.
The arguments can be a variable, array element, expression or constant
Returns nothing
Description 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.
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.
Example gfx_MoveTo(40,40);
n := 10;
while (n--)
gfx_BoxTo(50,50);
gfx_BoxTo(30,30);
wend
2.6.27 gfx_SetClipRegion()
Syntax gfx_SetClipRegion();
Arguments none
Returns nothing
Description Forces the clip region to the extent of the last text that was printed, or the last image that was shown.
Returns nothing
Description 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
Example gfx_Ellipse(200,80,5,10,YELLOW);
Returns nothing
Description Plots a solid coloured Ellipse on the screen at centre x,y with xradius = xrad and yradius = yrad.
Example gfx_EllipseFilled(200,110,10,5,GREEN);
Returns nothing
Description 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.
//-------------------------------------------------------------------
func main()
touch_Set(TOUCH_ENABLE);
repeat
// Draw 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));
endfunc
Returns nothing
Description 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.
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));
endfunc
Returns nothing
Description 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 gfx_BevelRadius().
//-------------------------------------------------------------------
func main()
touch_Set(TOUCH_ENABLE);
repeat
// Draw the Push Button (raised)
gfx_Button3(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));
endfunc
Returns nothing
Description 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.
func main()
// Draw a panel
gfx_Panel(RAISED, LEFT, TOP, WIDTH, HEIGHT, GRAY);
repeat forever
endfunc
Returns nothing
Description 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.
If the value parameter was a positive number (i.e:- value is a proportion of the scale parameter), the
true (implied x or y axis) position of the thumb is returned.
Returns
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.
Description 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:
1a] if width > height, slider is horizontal
2a] 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)
2b] If value is negative, thumb is driven to the graphics position set by the ABSolute of value value.
(used to set thumb to its actual graphical position (usually by touch screen)
3] 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 .
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
Returns nothing
Description 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.
If the value parameter was a positive number (i.e:- value is a proportion of the scale parameter), the
true (implied x or y axis) position of the thumb is returned.
Returns
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.
Description 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:
1a] if x2-x1 > y2-y1 slider is assumed to be horizontal (ie: if width > height, slider is horizontal)
1b] if x2-x1 <= y2-y1 slider is assumed to be vertical (ie: if height <= width, slider is horizontal)
2a] 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)
2b] If value is negative, thumb is driven to the graphics position set by the ABSolute of value value.
(used to set thumb to its actual graphical position (usually by touch screen)
3] 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 .
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
Returns Returns the 16bit (RED: 5, GREEN: 6, BLUE: 5 format) colour value.
Description Returns the 16bit (RED: 5, GREEN: 6, BLUE: 5 format) colour value of a 24bit (RED: 8, GREEN: 8, BLUE:
8 format) colour.
2.6.39 gfx_332to565(COLOUR8BIT)
Syntax gfx_332to565(COLOUR8BIT);
Arguments COLOUR8BIT
COLOUR8BIT 8bit colour value. 3bits for RED, 3bits for GREEN, 2bits for BLUE.
Description Returns the 16bit (RED: 5, GREEN: 6, BLUE: 5 format) value of an 8bit (RED: 3, GREEN: 3, BLUE: 2
format) colour
2.6.40 gfx_565to332(COLOUR)
Syntax gfx_565to332(COLOUR);
Arguments COLOUR16BIT
COLOUR16BIT 16bit colour value. 5bits for RED, 6bits for GREEN, 5bits for BLUE.
Description Returns the 8bit (RED: 3, GREEN: 3, BLUE: 2 format) value of a 16bit (RED: 5, GREEN: 6, BLUE: 5 format)
colour.
var color332;
color332 := gfx_565to332(0x7F00);
// Convert 16bit 565 color value to 8bit 332 color value
Returns nothing
Description 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.
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
Returns nothing
Description 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.
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
2.6.43 gfx_Origin(x, y)
Arguments x, y
x, y Specifies the horizontal and vertical position of the top left corner of the clipping window.
Returns nothing
Description Sets relative screen offset for horizontal and vertical for the top left corner for graphics objects.
2.6.44 gfx_Get(mode)
Syntax gfx_Get(mode);
Arguments mode
mode mode = 0 : Current orientations Max X Value (X_MAX)
mode = 1 : Current orientations Max Y Value (Y_MAX)
mode = 2 : Left location of Object
mode = 3 : Top location of Object
mode = 4 : Right location of Object
mode = 5 : Bottom location of Object
mode = 6 : Get current internal X position
mode = 7 : Get current internal Y position
Mode0
Returns the maximum horizontal value of the display.
Mode1
Returns the maximum vertical value of the display.
Mode2
Returns the left location of the last drawn object such as a slider or button or an image/video.
Mode3
Returns the top location of the last drawn object such as a slider or button or an image/video.
Returns Mode4
Returns the right location of the last drawn object such as a slider or button or an image/video.
Mode5
Returns the bottom location of the last drawn object such as a slider or button or an image/video.
Mode6
Returns the internal X position that was set with MoveTo(x, y); or gfx_Set(X_ORG, pos);
Mode7
Returns the internal Y position that was set with 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);
Returns nothing
Description 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).
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
Returns nothing
Description 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.
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.
function value
Predefined Name Description
PEN_SIZE Set the draw mode for gfx_LineTo, gfx_LineRel, gfx_Dot, 0 or SOLID
gfx_Bullet and gfx_BoxTo (default mode is OUTLINE) 1 or OUTLINE
nb:- pen size is set to OUTLINE for normal operation
BACKGROUND_COLOUR Set the screen background colour Colour, 0-65535
OBJECT_COLOUR Generic colour for gfx_LineTo(...), gfx_LineRel(...), gfx_Dot(), Colour, 0-65535
gfx_Bullet(...) and gfx_BoxTo(...)
CLIPPING Turns clipping on/off. 1 or 0 (ON or OFF)
The clipping points are set with gfx_ClipWindow(...) and
must be set first.
TRANSPARENT_COLOUR Colour that needs to be made transparent. Colour, 0-65535
TRANSPARENCY Turn the transparency ON or OFF. Transparency is 1 or 0 (ON or OFF)
automatically turned OFF after the next image or video
command.
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 Colour, 0-65535
(set to 0 for no effect)
CONTRAST LCD MODULES: 0 or OFF
contrast 0 = display OFF, 1-15 = contrast level (Actually 1 to 15 for levels
backlight brightness)
LINE_PATTERN Sets the line draw pattern for line drawing. If set to zero, lines 0 or OFF
are solid, else each '1' bit represents a pixel that is turned off. 1 to 0xFFFF
Returns Nothing
Description Draws an arc at "xc":"yc" with radius "radius", starting at "startangle" and ending at "endangle".
Colour is determined by current object colour.
Returns Nothing
Description Draws a CheckBox at screen location defined by x,y arguments (top left corner).
Example gfx_CheckBox(1, 20, 20, 100, 25, BLUE, LIME, "4D Labs");
/*
* Draws an UNCHECKED checkbox, top left corner at (20,150)
* The checkbox has a width of 100 pixels to contain ‘4D Labs’
*/
Returns Nothing
Description Draws a Radio-button at screen location defined by x,y arguments (top left corner).
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’
*/
Returns pointer
pointer Returns the handle of the previous pattern
Description Selects a tessellating pattern for painting solid objects. ‘patptr’ points to an 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
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
Returns Nothing
Returns Nothing
X1 may equal X2, and Y1 = Y2 allowing allowing the function to be used for rounded panels, rounded
buttons, circular buttons.
2.6.53 gfx_PieSlice(cx, cy, spread, radius, step, startangle, endangle, mode, colour)
Syntax gfx_PieSlice(cx, cy, spread, radius, step, startangle, endangle, mode, colour);
Returns Nothing
Description Draws a pie slice (filled arc) at xc:yc with radius radius, starting at startangle and ending at endangle.
Rendering can be obtained with gfx_FillPattern(PATTRN); or gfx_FillPattern(OFF); for no fill pattern.
Arguments x, y, &rect
x, y Coordinates
&rect An array of 4 vars, x1, y1, width, height.
Returns status
status Returns true if last touch co-ordinates are within the box test area.
Description 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
Arguments x, y, &recta
x, y Coordinates
Returns status
status Returns true if last touch co-ordinates are within the rectangle test area.
Description 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_PointWithinRectangle(x,y,rect) == 1)
txt_MoveCursor(0,0);
print("X: ",[DEC]x, " Y: ", [DEC]y, " \nTOUCHED");
endif
forever
Returns value
A pointer to the created array, or the users array. In the case of ptr=0 (creation of
value
array), if there is insufficient memory to create the array, zero is returned.
Description Due to the fact that most LCD displays 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 guage image. The power of this
function is further extended when used with the array math functions.
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)
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 coordinates,
// Endpoints are at (100,100) and (300,225)
Returns Nothing
Returns value
A pointer to the created aray, or the users array. In the case of ptr=0, if there is
value
insufficient memory to create the array, zero is returned.
Description 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.
Note: If an array is supplied, its size must be large enough, and may
be 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_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)
Returns Nothing
x2, y2 Specifies the bottom right corner position of the surround on the screen.
Returns nothing
Description 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.
2.6.61 gfx_Scope(Left, Width, Yzero, n, Xstep, Yamp, Colourbg, old_y1, new_y1, Colour1, …
old_y4, new_y4, Colour4)
gfx_Scope(left, width, Yzero, N, Xstep, Yamp, colourbg, old_y1, new_y1, colour1, old_y2, new_y2,
Syntax
colour2, old_y3, new_y3, colour3, old_y4, new_y4, colour4);
left, width, Yzero, N, Xstep, Yamp, colourbg, old_y1, new_y1, colour1, old_y2, new_y2, colour2,
Arguments
old_y3, new_y3, colour3, old_y4, new_y4, colour4
Left The left margin 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.
Returns nothing
Description 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.
Example
colour Colour
Returns nothing
Description Draw a Segment of a ring at x, y from rad1 to rad2 starting at starta to enda in colour.
// 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
Note: The angular meter function will require the gfx_Needle in order to function.
Returns nothing
Description 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 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
Returns nothing
Description 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"
Note: The needle function can be used standalone without the angular meter function, but the angular meter
function will require the needle function.
Returns nothing
Description Draw a Needle as defined by NeedleDef (if required), using NeedleRam positioning at position
value. See the reference for the NeedleDef values
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
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
Returns nothing
Description 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, 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)
func main()
gfx_Dial(frame, Knob1Ram, Knob1Info); // Dial 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
Returns nothing
Description 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, 10, 181, 59, 11, 0, 100, 10, 5, 0x18E3, 0x280, 0x7E0,
func main()
gfx_Gauge(frame, Gauge1Ram, Gauge1Info); // Gauge Internal Widget
repeat forever
endfunc
Returns nothing
Description 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, 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
Returns nothing
Description 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 eg 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.
Returns nothing
Description 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, 10, 250, 40, (0 + 0 + 0), 0, 100, 0x1082, 0x0, 0x7E0,
30, 30, 2, 2, 10, 0x7E0, 5, 0x7E0, FONT3, 0xFFE0, 0x1082, 0x9CD3, GRAD_DOWN,
0x1082, 0x9CD3, GRAD_UP
func main()
gfx_Slider5(frame, Slider1Ram, Slider1Info); // Slider Internal Widget
gfx_Slider5(frame, Gauge1Ram, Gauge1Info); // Gauge Internal Widget
repeat forever
endfunc
byte Button1LabelOn "ON\0" // Button label string (Use null terminator "\0" to end string)
byte Button1LabelOff "OFF\0" // Button label string (Use null terminator "\0" to end string)
#END
Returns nothing
Description Draw a Switch as defined by SwitchDef (if required), using SwitchRam positioning at position value.
See the reference for the SwitchDef values
#END
Returns nothing
Description Draw a Button as defined by ButtonDef (if required), using ButtonRam positioning at position value.
See the reference for the ButtonDef values.
#DATA
word Button1Info 0, 0, 50, 0x9CD3, 0x5ACB, GRAD_WAVE_VER, 0x8800, 0xF800,
0xDEDB, 0x2104, GRAD_DOWN, GRAD_UP, 0x6B6D, 0, 0xBDD7, 0x2965, GRAD_DOWN
word Button2Info 10, 120, 50, 0x9CD3, 0x5ACB, GRAD_WAVE_VER, 0x8800, 0xF800,
0xDEDB, 0x2104, GRAD_DOWN, GRAD_UP, 0x6B6D, ButtonText, 0xFFFF, 0x0, FONT1,
1
func main()
gfx_Button4(state, Button1Ram, Button1Info); // Button with braille
gfx_Button4(state, Button2Ram, Button2Info); // Button with text
repeat forever
endfunc
#DATA
Returns nothing
Description Draw a Led as defined by LedDef (if required), using LedRam positioning in state state. See the
reference for the LedDef values.
#DATA
word Led1Info 10, 10, 113, 96, 0x2965, 0x0, 0xFFFF, 0xF800, 0x5800, 35,
40, 20, 30, 1
#END
func main()
gfx_Led(state, Led1Ram, Led1Info); // LED Internal Widget
repeat forever
endfunc
Returns nothing
Description Draw a Scale as defined by ScaleDef, setting LedRam for use in touch processing. See the reference
for the ScaleDef values. If touch processing is not required 0 may be used as the ScaleRam
parameter.
#DATA
word Image1Info 36, 10, 197, 0, 100, 5, 10, 2, 5, 0xFFFF, 0x0, 0xFFFF,
FONT3, 0, (SCALE_CENTRE | SCALE_TICKS_BOTH | SCALE_VERT | SCALE_END_ALIGN |
SCALE_SHOW_ZERO)
#END
func main()
gfx_Scale(ImageRAM1, Image1Info); // Scale object
repeat forever
endfunc
Returns nothing
Description Draw a RulerGauge as defined by RulerGaugeDef (if required), using RulerGaugeRam positioning at
position value. See the reference for the RulerGaugeDef values.
#DATA
word Gauge1Info 10, 10, 250, 52, 100, 6, 5, 10, 20, 50, 75, 0x3A08, 0x1F,
0xFD20, 0xF800, 0xFFFF, RULERGAUGE_TICKS_BOTTOM
#END
func main()
gfx_RulerGauge(value, Gauge1Ram, Gauge1Info); // Gauge Internal
Widget
repeat forever
endfunc
X x co-ordinate
Y y co-ordinate
W Width
H Height
0 - no split
1 – top
2 - bottom
Returns nothing
Description Given the parameters, adjust the input color to produce the output color.
2.6.78 gfx_GradTriangleFilled(X0, Y0, X1, Y1, X2, Y2, SolidCol, GradientCol, GradientHeight,
GradientY, GradientLevel, Type)
gfx_GradTriangleFilled(X0, Y0, X1, Y1, X2, Y2, SolidCol, GradientCol, GradientHeight, GradientY,
Syntax
GradientLevel, Type)
Arguments X0, Y0, X1, Y1, X2, Y2, SolidCol, GradientCol, GradientHeight, GradientY, GradientLevel, Type
X0 First triangle point x coordinate
SolidCol Colour that will be used if the Solid or Gradient parameter is set to 0
GradientCol Colour that will be used if the Solid or Gradient parameter is set to 1
GradientHeight Height of the area that the gradient will be calculated. Can be larger than the
triangle
GradientY Position on the Y axis that the gradient will be calculated from with respect to
triangle position
GradientLevel Level of gradient applied
Returns nothing
Example gfx_GradTriangleFilled(10, 10, 10, 100, 100, 100 ,YELLOW, DARKKHAKI, 100,
10, 30, 1);
2.6.79 gfx_XYrotToVal(x,y,base,mina,maxa,minv,maxv)
Syntax gfx_XYrotToVal(x,y,base,mina,maxa,minv,maxv)
Arguments x,y,base,mina,maxa,minv,maxv
x Relative x-coordinate (x-coordinate – x-center)
base Base can be XYROT_EAST, used for internal widgets, or XYROT_SOUTH, used for
GCI widgets.
mina Start angle (Clockwise from 0 angle)
Description Convert a rotational angle into a value. Calculates a position for a rotary input starting at mina and
continuing to maxa. both angles must be greater than 0.
Example gfx_XYrotToVal(x,y,XYROT_EAST,starta,enda,minv,maxv)
2.6.80 gfx_XYlinToVal(x,y,base,minpos,maxpos,minv,maxv)
Syntax gfx_XYlinToVal(x,y,base,minpos,maxpos,minv,maxv)
Arguments x,y,base,minpos,maxpos,minv,maxv
x Relative x-coordinate (x-coordinate – x-center)
base Base can be XYLIN_X, to use the x value for calculations, or XYLIN_Y, to use the y
value.
mina Start position
maxa End position
minv Minimum value
maxv Maximum value
Description Convert a linear position into a value Calculates a position for a linear input starting at minpos and
continuing to maxpos.
Example gfx_XYlinToVal(x,y,XYLIN_X,startp,endp,minv,maxv)
• widget_Create(count)
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
• Error! Reference source not found.
2.7.1 widget_Create(count)
Syntax widget_Create(count)
Arguments count
count The number of elements in the widget control
Returns hndl
hndl Widget control handle.
Description Creates a widget control capable of holding count elements and returns a handle for the control.
Returns nothing
Description Add a widget ram entry "widget" into index "index" of the widget control referenced by "hndl".
Returns nothing
Description Delete widget ram entry "index" from the widget control referenced by "hndl".
2.7.4 widget_Realloc(handle, n)
Syntax widget_Realloc(handle, n)
Arguments handle, n
handle Handle of the widget control
Returns hndl
hndl Returns new handle to widget control
Description Resizes a widget control "handle"to contain n entries, allowing it to be expanded or condensed.
Doing this unnecessarily can lead to RAM fragmentation. It is much better to allocate widget controls
once with the desired number of entries.
Returns value
value Returns the specified word (0-14) from a widget entry.
Description Returns specified word (0-14) from a widget entry. Refer to widget control entry offsets. This
function requires that a widget control has been created with the widget_Create() function.
Example #DATA
word Led1Info 5, 30, 103, 56, 0x2965, BLACK, 0xDEFB, 0xF800, 0x5800, 20,
30, 10, 20, 1
#END
var Led1Ram[WIDGET_RAM_SPACE];
func main()
var hndl;
var width;
hndl := widget_Create(1);
widget_Add(hndl, 0, Led1Ram);
gfx_Led(0, Led1Ram, Led1Info);
width := widget_GetWord(hndl, 0, WIDGET_WIDTH);
print(width); // Print widget width from RAM
repeat
forever
endfunc
Returns status
status Returns true if index was ok and function was successful.
Description Set the position of an entry in the widget control. This function requires that a widget control has
been created with the widget_Create() function.
Example #DATA
word Led1Info 5, 5 , 103, 56, 0x2965, BLACK, 0xDEFB, 0xF800, 0x5800, 20,
30, 10, 20, 1
#END
var Led1Ram[WIDGET_RAM_SPACE];
func main()
var hndl;
hndl := widget_Create(1);
widget_Add(hndl, 0, Led1Ram);
gfx_Led(0, Led1Ram, Led1Info);
pause(2000);
gfx_Cls();
widget_Setposition(hndl, 0, 50, 50); // Set new widget position
gfx_Led(0, Led1Ram, Led1Info);
repeat
forever
endfunc
Returns status
status Returns true if index was ok and function was successful.
Description Enable an item in a widget control. This function requires that a widget control has been created
with the widget_Create() function.
Example #DATA
word IILed1 5, 30, 103, 56, 0x2965, BLACK, 0xDEFB, 0xF800, 0x5800, 20,
30, 10, 20, 1
word IILed2 5, 90, 103, 56, 0x2965, BLACK, 0xDEFB, BLUE, 0x000B, 20,
30, 10, 20, 1
#END
var ILed1RAM[WIDGET_RAM_SPACE] ;
var ILed2RAM[WIDGET_RAM_SPACE] ;
func main()
var hndl, i;
hndl := widget_Create(2);
widget_Add(hndl, 0, ILed1RAM);
widget_Add(hndl, 1, ILed2RAM);
repeat
if (i == 0)
widget_Disable(hndl, 0); // Disable LED 0
widget_Enable(hndl, 1); // Enable LED 1
else
widget_Disable(hndl, 1); // Disable LED 1
widget_Enable(hndl, 0); // Enable LED 0
endif
// Draw LED widgets
widget_ClearAttributes(hndl, ALL, WIDGET_F_INITIALISED);
gfx_Led(0, ILed1RAM, IILed1);
gfx_Led(0, ILed2RAM, IILed2);
pause(2000);
gfx_Cls();
i := !(i);
forever
endfunc
Returns status
status Returns true if index was ok and function was successful.
Description Disable an item in a widget control. This function requires that a widget control has been created
with the widget_Create() function.
Returns status
status Returns TRUE if successful, return value usually ignored
Description Set specified word in an image entry. This function requires that a widget control has been created
with the widget_Create() function.
Example #DATA
word IGauge1 10, 10, 30, 160, 80, 0, 100, 0, 0, 0x18E3, 0x0280, LIME, 0x5280,
YELLOW, 0x5000, RED, 51, 36, 0x0
#END
func main()
var hndl;
hndl := widget_Create(1);
widget_Add(hndl, 0, IGauge1RAM);
gfx_Gauge(50, IGauge1RAM, IGauge1);
Returns status
status Returns TRUE if successful, return value usually ignored.
Description This function SETS one or more bits in the widget flags field of a widget control entry. "value" refers
to various bits in the widget control entry (see widget attribute flags). A '1' bit in the "value" field
SETS the respective bit in the widget flags field of the widget control entry.
Widget attribute flags to be used and maintained by widgets and touch processing:
Example #DATA
word Slider1Info 10, 10, 250, 40, 0, 0, 100, 0x1082, 0x0, 0x7E0, 30, 30, 2,
2, 10, 0x7E0, 5, 0x7E0, FONT3, 0xFFE0, 0x1082, 0x9CD3, GRAD_DOWN, 0x1082,
0x9CD3, GRAD_UP
#END
var Slider1Ram[10];
func main()
var hndl;
hndl := widget_Create(1);
widget_Add(hndl, 0, Slider1Ram);
widget_SetAttributes(hndl, 0, WIDGET_F_TOUCH_ENABLE);
gfx_Slider5(frame, Slider1Ram, Slider1Info);
repeat
// do something here
forever
endfunc
Returns status
status Returns TRUE if successful, return value usually ignored.
Description This function CLEARS one or more bits in the widget flags field of an image control entry. "value"
refers to various bits in the widget control entry (see widget attribute flags). A '1' bit in the "value"
field CLEARS the respective bit in the widget flags field of the image control entry.
Widget attributes flags to be used and maintained by widgets and touch processing:
Example #DATA
word fLed1Info 5, 5 , 103, 56, 0x2965, BLACK, 0xDEFB, 0xF800, 0x5800, 20,
30, 10, 20, 1
#END
var Led1[WIDGET_RAM_SPACE];
func main()
var hndl;
hndl := widget_Create(10);
widget_Add(hndl, 0, Led1);
gfx_Led(0, Led1, fLed1Info);
pause(2000);
gfx_Cls();
widget_ClearAttributes(hndl, 0, WIDGET_F_INITIALISED);
gfx_Led(0, Led1, fLed1Info);
repeat
// do something here
forever
endfunc
Returns status
status Returns -1 if image not touched, or returns index
Description This function requires that a widget control has been created with the widget_Create() function.
Returns index of the widget touched or returns -1 if no widget was touched.
Returns nothing
Returns value
value The LO word of the 32 bit pixel count is returned.
Prepares the GRAM area for user access. The lower 16bits of the pixel count in the selected area is
Description 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.
2.8.3 disp_WrGRAM(colour)
Syntax disp_WrGRAM(colour);
Arguments colour
colour Pixel color to be populated.
Returns nothing
Data can be written to the GRAM consecutively using this function once the GRAM access window
Description
has been setup.
disp_WrGRAM(0xFFF0);
Example
2.8.4 disp_WriteControl(value)
Syntax disp_WriteControl(value);
Arguments value
value Specifies the 16 bit value to be written to the display control register.
The arguments can be a variable, array element, expression or constant
Returns nothing
Sends a 16 bit value to the display bus. Refer to individual data sheets for the display for more
Description information. This function is used to extend the capabilities of the user code to gain access to the
display hardware.
disp_WriteControl(0x0FFA);
Example
2.8.5 disp_WriteWord(value)
Syntax disp_WriteWord(value);
Arguments value
value Specifies the value to be written to the display data register.
The arguments can be a variable, array element, expression or constant
Returns nothing
Sends a 16 bit value to the display bus. Refer to individual data sheets for the display for more
Description information. This function is used to extend the capabilities of the user code to gain access to the the
display hardware.
disp_WriteWord(0x7FF0);
Example
2.8.6 disp_ReadWord()
Syntax disp_ReadWord();
Arguments nothing
Returns value
value Returns 16 bit value in the register.
var val;
Example val := disp_ReadWord();
2.8.7 disp_Disconnect()
Syntax disp_Disconnect();
Arguments none
Returns nothing
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.
Description
Note: disp_Init() should be used to reinitialise the display.
New in v0.7 PmmC
2.8.8 disp_Init()
Syntax disp_Init();
Arguments none
Returns nothing
2.8.9 disp_BlitPixelsFromCOMn()
disp_BlitPixelsFromCOM0(); or
disp_BlitPixelsFromCOM1(); or
disp_BlitPixelsFromCOM2(); or
Syntax
disp_BlitPixelsFromCOM3();
Arguments None
Returns Nothing
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.
Description
New in v1.1 PmmC
2.9.1 media_Init()
Syntax media_Init();
Arguments none
Returns result
result Returns: 1 if memory card is present and successfully initialised
Returns: 0 if no card is present or not able to initialise
Description Initialise a uSD/SD/SDHC memory card for further operations. The SD card is connected to the SPI
(serial peripheral interface) of the processor.
Example while(!media_Init())
gfx_Cls();
pause(300);
puts(“Please insert SD card”);
pause(300);
wend
This example waits for SD card to be inserted and initialised, flashing a message if no SD card detected.
Returns nothing
Description Set media memory internal Address pointer for access at a non sector aligned byte address.
This example sets the media address to byte 513 (which is sector #1, 2nd byte in sector) for subsequent
operations.
Returns result
Description Set media memory internal Address pointer for sector access.
This example sets the media address to the 11th sector (which is also byte address 5120) for
subsequent operations
2.9.4 media_RdSector(Destination_Address)
Syntax media_RdSector(Destination_Address);
Arguments Destination_Address
Reads and Returns 512 bytes (256 words) into a destination block (eg rdblock[256]) pointed to by the
Description
internal Sector pointer. After the read the Sector pointer is automatically incremented by 1.
media_SetSector(0,10)
if (media_RdSector(rdblock));
Print(“Data collected”);
endif
This example sets a 512 bytes block and collects data from the address pointed to by media_SetSector
command.
2.9.5 media_WrSector(Source_Address)
Syntax media_WrSector(Source_Address);
Arguments Source_Address
Writes 512 bytes (256 words) from a source memory block (eg wrblock[256]) into the uSD card. After
Description the write the Sect pointer is automatically incremented by 1.
Returns TRUE if uSD response was TRUE
func main()
prepare_block();
media_SetSector(0,10)
if (media_WrSector(wrblock));
Print(“Data transferred”);
endif
:
:
This example sets a 512 bytes block and transfers data to the address pointed to by media_SetSector
command.
2.9.6 media_ReadByte()
Syntax media_ReadByte();
Arguments none
Description Returns the byte value from the current media address. The internal byte address will then be
internally incremented by one.
This example initialises the media, sets the media byte address to 510, and reads the last 2 bytes from
sector 0. If the card happens to be FAT formatted, the result will be “AA55”. The media internal address
is internally incremented for each of the byte operations.
2.9.7 media_ReadWord()
Syntax media_ReadWord();
Arguments none
Description Returns the word value (2 bytes) from the current media address. The internal byte address will then
be internally incremented by two. If the address is not aligned, the word will still be read correctly.
This example initialises the media, sets the media byte address to 510 and reads the last word from
sector 0. If the card happens to be formatted, the result will be “AA55”
2.9.8 media_WriteByte(byte_val)
Syntax media_WriteByte(byte_val);
Arguments byte_val
byte_val The lower 8 bits specifies the byte to be written at the current media address location.
The arguments can be a variable, array element, expression or constant
Returns success
success Returns non zero if write was successful.
Description Writes a byte to the current media address that was initially set with media_SetAdd() or
media_SetSector(...); After the write the Address pointer is automatically incremented by 1.
Note: Writing bytes or words to a media sector must start from the beginning of the sector. All writes
will be incremental until the media_Flush() function is executed, or the sector address rolls over to
the next sector. When media_Flush() is called, any remaining bytes in the sector will be padded with
0xFF, destroying the previous contents. An attempt to use the media_SetAdd(..) function will result
in the lower 9 bits being interpreted as zero. If the writing rolls over to the next sector, the
media_Flush() function is issued automatically internally.
This example initialises the media, writes some bytes to the required sector, then prints the
result from the required location.
2.9.9 media_WriteWord(word_val)
Syntax media_WriteWord(word_val);
Arguments word_val
word_val The 16 bit word to be written at the current media address location.
The arguments can be a variable, array element, expression or constant
Returns success
success Returns non zero if write was successful.
Description Writes a word to the current media address that was initially set with media_SetAdd() or
media_SetSector(...); After the write the Address pointer is automatically incremented by 2.
Note: Writing bytes or words to a media sector must start from the beginning of the sector. All writes
will be incremental until the media_Flush() function is executed, or the sector address rolls over to
the next sector. When media_Flush() is called, any remaining bytes in the sector will be padded with
0xFF, destroying the previous contents. An attempt to use the media_SetAdd(..) function will result in
the lower 9 bits being interpreted as zero. If the writing rolls over to the next sector, the media_Flush()
function is issued automatically internally.
Example var n;
2.9.10 media_Flush()
Syntax media_Flush();
Arguments none
returns 0 if Failed
Returns
returns non-zero if OK
Description After writing any data to a sector, media_Flush() should be called to ensure that the current sector
that is being written is correctly stored back to the media else write operations may be unpredictable.
2.9.11 media_Image(x, y)
Arguments x, y
x, y Specifies the top left position where the image will be displayed.
The arguments can be a variable, array element, expression or constant
Returns nothing
Description Displays an image from the media storage at the specified co-ordinates. The image address is
previously specified with the media_SetAdd(..) or media_SetSector(...) function. If the image is
shown partially off screen, it may not be displayed correctly.
This example draws an image at several positions, showing the effects of clipping.
2.9.12 media_Video(x, y)
Arguments x, y
x, y Specifies the top left position where the video clip will be displayed.
The arguments can be a variable, array element, expression or constant
Returns nothing
Description Displays a video clip from the media storage device at the specified co-ordinates. The video address
location in the media is previously specified with the media_SetAdd(..) or media_SetSector(...)
function. If the video is shown partially off screen, it may not be displayed correctly. Note that showing
a video blocks all other processes until the video has finished showing. See the
media_VideoFrame(...) functions for alternatives.
This example plays a video clip at several positions, showing the effects of clipping.
Arguments x, y
x, y Specifies the top left position where the video clip will be displayed.
Returns nothing
Description Displays a video from the media storage device at the specified co-ordinates. The video address is
previously specified with the media_SetAdd(..) or media_SetSector(...) function. If the video is shown
partially off it may not be displayed correctly. The frames can be shown in any order. This function
gives you great flexibility for showing various icons from an image strip, as well as showing videos
while doing other tasks
media_VideoFrame(..) will now show error box for out of range video frames. Also, if frame is set to -
1, just a rectangle will be drawn in background colour to blank an image. It applies to PmmC R29 or
above.
This first example shows how to display frames as required while possibly doing other tasks. Note that
the frame timing (although not noticeable in this small example) is not correct as the delay
commences after the image frame is shown, therefore adding the display overheads to the frame
delay. This second example employs a timer for the framing delay, and shows the same movie
simultaneously running forward and backwards with time left for other tasks as well. A number of
videos (or animated icons) can be shown simultaneously using this method.
if ((frame & 3) == 0)
gfx_CircleFilled(80,20,2,colr); // a blinking circle fun
colr := colr ^ 0xF800; // alternate colour,
endif // BLACK/RED using XOR
// do more here if required
while(peekW(TIMER0)); // wait for timer to expire
until(frame == peekW(IMG_FRAME_COUNT));
frame := 0;
forever
2.10.1 flash_Bank()
Syntax flash_Bank();
Arguments none
Returns value
value 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
bank := flash_Bank();
pallete2colour An array of 2 elements being the colors for the two possible colour values.
Returns count
count Actual count (normally same as count, will be lower if bank bounds exceeded)
Description 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
pallete4colour An array of 4 elements being the colors for the four possible colour values.
Returns count
count Actual count (normally same as count, will be lower if bank bounds exceeded)
Description 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
Pallete16colour An array of 16 elements being the colors for the sixteen possible colour values.
Returns count
count Actual count (normally same as count, will be lower if bank bounds exceeded)
Description 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
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);
Returns count
count Actual count (normally same as count, will be lower if bank bounds exceeded)
Description 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
Returns count
count Actual count (normally same as count, will be lower if bank bounds exceeded)
Description 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
Returns count
count The count of bytes transferred.
Description Copies bytes from any flash locations to a user buffer. If the bank is read protected, 0 bytes will be
read.
Returns status
status Returns true if the function succeeded.
Description 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
thru FLASHBANK_5 are cleared.
Note: Use with caution, this is a good way to 'clean up' the entire flash when starting new projects.
Note: reset processor if program is erasing itself, or the ALL bank option is selected.
Returns Value
Value Returns the value from main in the called bank.
Description This function calls the main function in another bank. The main program in FLASH retains all memory
allocations (eg 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.
Example flash_Exec(FLASHBANK_1, 0) ;
Returns byte
byte The byte value from the location
Description Reads a single byte from any flash location. If the bank is read protected, only the first 2 bytes can be
read.
Returns word
word The word value from the location
Description Reads a single word from any flash location. If the bank is read protected, only the first word can be
read.
Returns status
status Returns true if the function succeeded
Description Copies a file from uSD to the required flashbank. The destination bank cannot be the execution bank,
or a bank that is write protected.
Returns status
status True if function succeeds, usually ignored. 0 if bank is read protected.
Description 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.
2.10.14 flash_Run(bank)
Syntax flash_Run(bank)
Arguments bank
Flash bank to load the program from.
0 or FLASHBANK_0
1 or FLASHBANK_1
bank 2 or FLASHBANK_2
3 or FLASHBANK_3
4 or FLASHBANK_4
5 or FLASHBANK_5
Returns value
value 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.
Description Restarts the processor, running code from the required flash bank. Bank may be a variable, or one of
the pre-defined constants.
Returns status
status Returns true if the function succeeded.
Description 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.
var status;
Returns status
status Returns 0 if successful
Description 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. eg
0x0100 means parameter 8 is a single string, 0x0002 means paramter 9 is an array of strings with
parameter 8 containing the count.
Returns status
status Returns true if the function succeeded
Description Copies a file from uSD to the required flashbank. The destination bank cannot be the execution bank,
or a bank that is write protected.
Note: SPI0 is connected internally to the uSD card. spi_Init(), spi_Read(), spi_Write() and spi_Disable() all refer to the
SPI0 to communicate with the uSD card through direct SPI commands. Only adept users should attempt this as it might
damage the uSD card.
Returns nothing
Description Sets up the Diablo16 SPI port to communicate with the uSD card through direct SPI commands. It
should not be used if uSD card is active. See the example in section spi_Read().
Note: address_mode needs to be SPI_ADDRESS_MODE4 for flash devices with more than 16MB of
capacity (to enable 4 byte addressing), else 0 for standard 3 byte addressing.
Note: This is only for the uSD Card, it is not for SPI1, SPI2 or SPI3.
WARNING: This should not be tampered with for normal operation, as the Diablo16 handles the uSD card itself.
Only use if you are an adept user and know what you are doing.
2.11.2 spi_Read()
Syntax spi_Read();
Arguments none
Returns byte
byte Returns a single data byte from the uSD card via SPI.
Description This function allows a raw unadorned byte read from the uSD card via SPI.
Note: This is only for the uSD Card, it is not for SPI1, SPI2 or SPI3
//...
spi_Write(0x40);
result := spi_Read();
print("result: ", result);
Note: This is only for the uSD Card, it is not for SPI1, SPI2 or SPI3.
WARNING: This should not be tampered with for normal operation, as the Diablo16 handles the uSD card itself.
Only use if you are an adept user and know what you are doing.
2.11.3 spi_Write(byte)
Syntax spi_Write(byte);
Arguments byte
byte Specifies the data byte to be sent to the uSD card via SPI.
The arguments can be a variable, array element, expression or constant
Returns nothing
Description This function allows a raw unadorned byte write to the uSD card via SPI.
Note: This is only for the uSD Card, it is not for SPI1, SPI2 or SPI3
Note: This is only for the uSD Card, it is not for SPI1, SPI2 or SPI3.
WARNING: This should not be tampered with for normal operation, as the Diablo16 handles the uSD card itself.
Only use if you are an adept user and know what you are doing.
2.11.4 spi_Disable()
Syntax spi_Disable();
Arguments none
Returns nothing
Description This function raises the Chip Select (SDCS) line of the uSD card, disabling it from further activity. The
CS line will be automatically lowered next time the SPI functions spi_Read() or spi_Write(...) are used,
and also by action of any of the media_ functions.
Note: This is only for the uSD Card, it is not for SPI1, SPI2 or SPI3
16 bit Modes
SPI16_MODE_0 8 SCK idles low, SDO stable for first falling
edge, SDI sampled on first falling edge
Mode can also be “OR’ed” with SPI_ADDRESS_MODE4 when SPI Flash memory is used
which requires 4 byte addressing.
This is only required for Flash chips having a capacity of greater than 16MB, thus
requiring more than he standard 3 byte addressing. Refer to the Datasheet of the Flash
Memory in question.
The syntax would be for example SPI8_MODE_0 | SPI_ADDRESS_MODE4, in place of
the ‘mode’ argument.
Returns status
status Returns true if the function succeeded.
Description Initialize the SPI port to communicate with the SPI device. There are three peripheral interfacable SPI
ports that can be used to communicate with three different SPI devices with different speeds and
modes at the same time. SPI1, SPI2 and SPI3 need to be initialized separately using SPI1_Init(..),
SPI2_Init(..) or SPI3_Init(..) functions.
Note: This is only for SPI1, SPI2 or SPI3, it is separate from the spi_Init() function used for the uSD
Card
SPI1_Read(); or
Syntax SPI2_Read(); or
SPI3_Read();
Arguments none
Returns byte
byte Returns a single data byte from the SPI device.
Description This function allows a raw unadorned byte read from the SPI device connected to SPI1, SPI2 or SPI3
port. A dummy write using all bits set is automatically written to the SPI port to being the read.
Note: The Chip Select line needs to be manually lowered and raised by the users’ code since this pin
is determined by the user and is not a fixed pin.
Note: This is only for SPI1, SPI2 or SPI3, it is separate from the spi_Read() function used for the uSD
Card
Example #CONST
EnablePin PA0
ClockPin PA1
SDIPin PA2
SDOPin PA3
#END
func main()
var result, power, err;
pin_HI(EnablePin) ;
pin_Set(PIN_OUT,EnablePin);
if (! SPI1_SDI_pin(SDIPin))
print("SDI Pin Invalid\n") ;
err := 1 ;
endif
if (! SPI1_SCK_pin(ClockPin))
print("SCK Pin Invalid\n") ;
err := 1 ;
endif
if (! SPI1_SDO_pin(SDOPin))
print("SDO Pin Invalid\n") ;
err := 1 ;
endif
if (! SPI1_Init(SPI_SPEED0, SPI16_MODE_1))
print("INIT parameter Invalid\n") ;
err := 1 ;
endif
if(err)
repeat forever
endif
pin_LO(EnablePin); //Chip Select
SPI1_Write(0x0200); // Power supply data read Request
pin_HI(EnablePin);
pin_LO(EnablePin);
result:=SPI1_Read();
power:=result<<8;
result:=SPI1_Read();
power:=power+result;
pin_HI(EnablePin);
endfunc
SPI1_Write(byte); or
Syntax SPI2_Write(byte); or
SPI3_Write(byte);
Arguments byte
byte Specifies the data byte to be sent to the SPI device.
The arguments can be a variable, array element, expression or constant
Returns Data
Data Returns the data read from the SPI port whilst the write is in progress
Description This function allows a raw unadorned byte write to the SPI device connected to SPI1, SPI2 or SPI3
port.
Note: The Chip Select line needs to be manually lowered and raised by the users’ code since this pin
is determined by the user and is not a fixed pin.
Note: This is only for SPI1, SPI2 or SPI3, it is separate from the spi_Write() function used for the uSD
Card
SPI1_SCK_pin(pin); or
Syntax SPI2_SCK_pin(pin); or
SPI3_SCK_pin(pin);
Arguments pin
Specifies the pin to be set for SCK for SPI1, SPI2 or SPI3 ports.
PA0 61 1 No
PA1 62 3 Yes
PA2 63 5 No
PA3 64 7 Yes
PA4 46 29 Yes
PA5 49 27 Yes
pin PA6 50 25 Yes
PA7 51 23 Yes
PA8 52 21 Yes
PA9 53 19 Yes
PA10 43 8 No
PA11 44 6 No
PA12 31 28 Yes (See Note 1)
PA13 32 30 Yes (See Note 1)
PA14 37 24 No
PA15 36 26 No
Returns status
status Returns TRUE if function succeeded (usually ignored)
Description Selects the hardware pin for spi Clock line. SPI1, SPI2 or SPI3’s SCK pin could be assigned to the
available pins. Note that only a single pin should be mapped to spi SCK. If the pin argument is 0 the
previously selected spi SCK pin is disconnected. The pin is automatically set to an output.
Note 1: 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.
SPI1_SDI_pin(pin); or
Syntax SPI2_SDI_pin(pin); or
SPI3_SDI_pin(pin);
Arguments pin
Specifies the pin to be set for SDI for SPI1, SPI2 or SPI3 ports.
PA0 61 1 Yes
PA1 62 3 Yes
PA2 63 5 Yes
PA3 64 7 Yes
PA4 46 29 Yes
PA5 49 27 Yes
pin PA6 50 25 Yes
PA7 51 23 Yes
PA8 52 21 Yes
PA9 53 19 Yes
PA10 43 8 Yes
PA11 44 6 Yes
PA12 31 28 Yes (See Note 1)
PA13 32 30 Yes (See Note 1)
PA14 37 24 No
PA15 36 26 No
Returns status
status Returns TRUE if finction succeeded (usually ignored)
Description Selects the hardware pin for SPI Receive line. SPI1, SPI2 or SPI3’s SDI pin could be assigned to the
available pins. Note that only a single pin should be mapped to spi SDI. If the pin argument is 0 the
function has no effect. The pin is automatically set to an output.
Note: If the spi SDI pin is set to same pin as spi SDO pin (eg for a loopback check) it is necessary to
configure the SDI pin first,
SPI2_SDI_pin(PA3); // configure SPI2 SDI to PA3 (this disconnects anything else)
SPI2_SDO_pin(PA3)); // configure SPI2 SDO to PA3
Note 1: 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.
SPI1_SDO_pin(pin); or
Syntax SPI2_SDO_pin(pin); or
SPI3_SDO_pin(pin);
Arguments pin
Specifies the pin to be set for SDO for SPI1, SPI2 or SPI3 ports.
PA0 61 1 No
PA1 62 3 Yes
PA2 63 5 No
PA3 64 7 Yes
PA4 46 29 Yes
PA5 49 27 Yes
pin PA6 50 25 Yes
PA7 51 23 Yes
PA8 52 21 Yes
PA9 53 19 Yes
PA10 43 8 No
PA11 44 6 No
PA12 31 28 Yes (See Note 1)
PA13 32 30 Yes (See Note 1)
PA14 37 24 No
PA15 36 26 No
Returns status
status Returns TRUE if finction succeeded (usually ignored)
Description Selects the hardware pin for SPI Transmit line. SPI1, SPI2 or SPI3’s SDO pin could be assigned to the
available pins. Note that only a single pin should be mapped to spi SDO. If the pin argument is 0 the
previously selected spi SDO pin is disconnected. The pin is automatically set to an output.
Note 1: 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.
spi_ReadBlock("buf", "bufsize") or
spi1_ReadBlock("buf", "bufsize") or
Syntax
spi2_ReadBlock("buf", "bufsize") or
spi3_ReadBlock("buf", "bufsize")
Returns Nothing
Description Bufsize bytes are read from the SPI port to the string pointer "buf". This function gives much better
performance than reading individual bytes at a time. Once the data has been read into a buffer it also
makes it easy to perform CRC calculations on the data. The SPI port must be initialised in 8 bit mode.
func main()
var st[20] ;
endfunc
spi_WriteBlock("buf", "bufsize") or
spi1_WriteBlock("buf", "bufsize") or
Syntax
spi2_WriteBlock("buf", "bufsize") or
spi3_WriteBlock("buf", "bufsize")
Returns Nothing
Description Bufsize bytes are written to the SPI port from the string pointer "buf". This function gives much better
performance than writeing individual bytes at a time. Once the data has been read into a buffer it also
makes it easy to perform CRC calculations on the data. The SPI port must be initialised in 8 bit mode.
func main()
var st[20] ;
to(st) ;
print("Hello there!") ;
spi3_WriteBlock(str_Ptr(st), 12) ;
endfunc
COM1_RX_pin(pin); or
Syntax COM2_RX_pin(pin); or
COM3_RX_pin(pin);
Arguments pin
pin Specifies the GPIO pin to use for the com ports receive line
The arguments can be a variable, array element, expression or constant
Returns Status
Status Returns True if the function succeeded, usually ignored
Description Use this function to specify which GPIO is going to be assigned to the relative com ports receive line.
Note that only a single pin can be mapped to any given com ports RX.
The pin is automatically set to an input. If the COMx RX pin is set to same pin as COMx TX pin (eg for
a loopback check) it is necessary to configure the input pin first,
For Example:
Note 1: 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.
COM1_TX_pin(pin); or
Syntax COM2_TX_pin(pin); or
COM3_TX_pin(pin);
Arguments pin
pin Specifies the GPIO pin to use for the com ports transmit line
The arguments can be a variable, array element, expression or constant
Returns Status
Status Returns True if the function succeeded, usually ignored
Description Use this function to specify which GPIO is going to be assigned to the relative com ports transmit line.
Note that only a single pin can be mapped to any given com ports TX.
Note 1: 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.
2.12.3 setbaud(baudnum)
Syntax setbaud(baudnum);
Arguments baudnum
baudnum Specifies the baud rate of COM0 using the baud number or pre-defined constant
Baud number Pre-defined Baud Rate Error Actual Baud Rate
Constant (%)
0 BAUD_110 0.00% 110
1 BAUD_300 0.00% 300
2 BAUD_600 0.00% 600
3 BAUD_1200 0.00% 1200
4 BAUD_2400 0.04% 2401
5 BAUD_4800 0.04% 4802
6 BAUD_9600 0.16% 9615
7 BAUD_14400 0.27% 14439
8 BAUD_19200 0.38% 19273
BAUD_31250
9 or 0.00% 31250
MIDI
10 BAUD_38400 0.83% 38717
11 BAUD_56000 0.16% 56090
12 BAUD_57600 1.27% 58333
13 BAUD_115200 2.64% 118243
14 BAUD_128000 0.53% 128676
15 BAUD_256000 0.53% 257353
16 BAUD_300000 4.17% 312500
17 BAUD_375000 6.06% 397727
18 BAUD_500000 9.38% 546875
19 BAUD_600000 4.17% 625000
The arguments can be a variable, array element, expression or constant
Returns nothing
Description Use this function to set the required baud rate. The default Baud Rate for COM0 is 115,200 bits per
second or 115,200 baud.
If a value other than 0-19 is used, a run time error (error 25)
Note: Baud rates each have degree of accuracy for several reasons. The actual baud rate you would
receive and relevant error% compared to the setting value, can be calculated.
Actual Baud is calculated using the following formula:
Actual Baud = 4375000/(trunc(4375000/RequiredBaud))
Example for 115200 is, 4375000/115200 = 37.977, Trucated is 37. 4375000/37 = 118243 (rounded).
Error% therefore is % difference between 115200 and 118243, therefore 2.64%
It is desirable to only use a baud rate between 2 devices which has a difference of typically < 2%.
Note both devices will have a degree of error, not just this 4D Processor, both need to be
considered.
Returns Status
Status Returns True if BAUD rate was acceptable.
Description Use this function to set the required baud rate for the required Com port. Sets to any viable baud rate
from 160 to 655350.
Note: The default Baud Rate for COM0 is 115,200 bits per second or 115,200 baud. The default Baud
Rate for COM1, COM2 and COM3 is 9600 bits per second or 9600 baud.
Note: As of the v1.1 PmmC several ‘low’ values have special meanings
1 : 2187500 baud
2 : 1458333 baud
3 : 1093750 baud
4 : 875000 baud
5 : 729167 baud
Note: Baud rates each have degree of accuracy for several reasons. The actual baud rate you would
receive and relevant error% compared to the setting value, can be calculated.
It is desirable to only use a baud rate between 2 devices which has a difference of typically < 2%.
Note both devices will have a degree of error, not just this 4D Processor, both need to be
considered.
serin(); or
serin1(); or
Syntax
serin2(); or
serin3();
Arguments none
Returns char
char Returns: -1 if no character is available
Returns: -2 if a framing error or over-run has occurred (auto cleared)
Returns: -3 (BREAK) if a break signal is detected
Returns: positive value 0 to 255 for a valid character received
serin may be buffered (refer to com_Init(..) functions). If it is desired to be able to receive the BREAK
signal using buffered functions then the com_InitBrk() function must be used instead.
Note: COM0 pins cannot be mapped, and are fixed as pins 42(Rx0) and 33(Tx0) on the Diablo16 chip.
Rx and Tx of COM1, COM2 or COM3 should be defined before using serin1(), serin2() or serin3().
serout(char); or
serout1(char); or
Syntax
serout2(char); or
serout3(char);
Arguments char
char Specifies the data byte to be sent to the serial port.
The arguments can be a variable, array element, expression or constant
Returns nothing
Note: COM0 pins cannot be mapped, and are fixed as pins 42(Rx0) and 33(Tx0) on the Diablo16 chip.
Rx and Tx of COM1, COM2 or COM3 should be defined before using serout1(), serout2() or serout3().
Note: The BREAK signal can be transmitted using the predefined constant BREAK as the char to
serout().
Returns nothing
Description This is the initialisation function for the serial communications buffered service. Once initialised, the
service runs in the background capturing and buffering serial data without the user application having
to constantly poll the serial port. This frees up the application to service other tasks.
MODES OF OPERATION
If any low level errors occur during the buffering service (such as framing or over-run) the
internal COM_ERROR flag will be set (which can be read with the com_Error() function). Note
that the COM_FULL flag will remain latched to indicate that the buffer did become full, and
is not reset (even if all the characters are read) until the com_Init(..) or com_Reset() function
is issued.
• Using a qualifier
If a qualifier character is specified, after the buffer is initialised with com_Init(..) , the service
will ignore all characters until the qualifier is received and only then initiate the buffer write
sequence with incoming data. After that point, the behaviour is the same as above for the
'non qualified' mode.
com_Reset(); or
com1_Reset(); or
Syntax
com2_Reset();or
com3_Reset();
Arguments none
Returns nothing
Resets the serial communications buffered service and returns it to the default polled mode.
com_Count(); or
com1_Count(); or
Syntax
com2_Count(); or
com3_Count();
Arguments none
Returns count
count Current count of characters in the communications buffer.
Description Can be read at any time (when in buffered communications is active) to determine the number of
characters that are waiting in the buffer.
com_Full(); or
com1_Full() ; or
Syntax
com2_Full(); or
com3_Full();
Arguments none
Returns status
status Returns 1 if buffer or queue has become full, or is overflowed, else returns 0.
Description If the queue is not read frequently by the application, and characters are still being sent by the host,
the head will eventually catch up with the tail setting the COM_FULL flag which is read with this
function. If this flag is set, any further characters from the host are discarded, however, all the
characters that were buffered up to this point are readable.
com_Error(); or
com1_Error();or
Syntax
com2_Error();or
com3_Error();
Arguments none
Returns status
status Returns 1 if any low level communications error occurred, else returns 0.
Description If any low level errors occur during the buffering service (such as framing or over-run) the internal
COM_ERROR flag will be set which can be read with this function.
com_Sync(); or
com1_Sync(); or
Syntax
com2_Sync(); or
com3_Sync();
Arguments none
Returns status
status Returns 1 if the qualifier character has been received, else returns 0.
Description If a qualifier character is specified when using buffered communications, after the buffer is initialized
with com_Init(..), com1_Init(..), com2_Init(..), or com3_Init(..) the service will ignore all characters
until the qualifier is received and only then initiate the buffer write sequence with incoming data.
com_Sync(), com1_Sync(), com2_Sync(), com3_Sync() is called to determine if the qualifier character
has been received yet.
Returns None
Description Initialise a serial buffer for the COM0, COM1, COM2 or COM3 output. The program must declare a
var array as a circular buffer. When a TX buffer is declared for comms, the transmission of characters
becomes non-blocking. If the buffer has insufficient space to accept the next character from a
serout(..), serout1(..), serout2(..) or serout3(..) function, the excess characters will be ignored, and
the com_Full(), com1_Full(), com2_Full() or com3_Full() error will be asserted. If the TX buffer is no
longer required, just set the buffer pointer to zero, the size in this case doesnt matter and is ignored.
The function can be resized or reallocated to another buffer at any time. The buffer is flushed before
any changes are made.
"pin" designates an IO pin to control a bi-directional control device for half duplex mode. "pin" will go
HI at the start of a transmission, and will return low after the final byte is transmitted.
com_TXbufferHold(state); or
com1_TXbufferHold(state); or
Syntax
com2_TXbufferHold(state); or
com3_TXbufferHold(state);
Arguments state
state Specifies the state of the buffer used for the buffering service.
The arguments can be a variable, array element, expression or constant
Returns count
Returns -1 if function is called illegally when TX comms is not buffered.
Returns buffer count when called with argument of 1, for example
com_TXbufferHold(ON), com1_TXbufferHold(ON), com2_TXbufferHold(ON) or
count
com3_TXbufferHold(ON)
Returns 0 when argument is zero, eg com_TXbufferHold(OFF),
com1_TXbufferHold(OFF), com2_TXbufferHold(OFF), com3_TXbufferHold(OFF)
Note: If you fill the buffer whilst it is held comms error 4 will be set and the data written will be lost.
com_TXcount(); or
com1_TXcount(); or
Syntax
com2_TXcount(); or
com3_TXcount();
Arguments None
Returns count
count Returns count of characters
Description Return count of characters remaining in COM0, COM1 or COM2 or COM3 transmit buffer that was
previously allocated with com_TXbuffer(..), com1_TXbuffer(..), com2_TXbuffer(..),
com3_TXbuffer(..).
com_TXemptyEvent(functionAddress); or
com1_TXemptyEvent(functionAddress); or
com2_TXemptyEvent(functionAddress); or
Syntax
com3_TXemptyEvent(functionAddress);
Arguments functionAddress
functionAddress Address of the event Function to be queued when COM0, COM1, COM2 or COM3
TX buffer empty
Returns Address
Address Returns any previous event function address or zero if there was no previous function.
Description If a comms TX buffer that was previously allocated with com_TXbuffer(...), com1_TXbuffer(...),
com2_TXbuffer(...) or com3_TXbuffer(...) this function can be used to set up a function to be called
when the COM0, COM1, COM2 or COM3 TX buffer is empty.
This is useful for either reloading the TX buffer, setting or clearing a pin to change the direction of eg
a RS485 line driver, or any other form of traffic control. The event function must not have any
parameters. To disable the event, simply call com_TXemptyEvent(0), com1_TXemptyEvent(0) ,
com2_TXemptyEvent(0) or com3_TXemptyEvent(0).
/*************************************************
* Description: buffered TX service
* Use Workshop terminal at 9600 baud to see result
* Example of Buffered TX service vs Non buffered
* Also explains the use of COMMS events
*
* NB Program must be written to flash so
* the Workshop Terminal can be used.
*
**************************************************/
func main()
var n, r, D, fh;
setbaud(BAUD_9600);
txt_Set(TEXT_OPACITY, OPAQUE);
repeat
gfx_Cls();
print("took ",peekW(SYSTEM_TIMER_LO),"Msec\n\n");
// time spent blocking is only approx 1msec
// note that here the time is only approx 1msec overhead due to buffering.
print("Send 440 chars buffered\n");
pokeW(SYSTEM_TIMER_LO, 0); // reset timer
print("took ",peekW(SYSTEM_TIMER_LO),"Msec\n\n");
// time spent blocking is only approx 1msec
print("\n\nTX Empty");
forever // do it forever
//com_TXbuffer(0, 0, 0); // if done with the pin, must release it
endfunc
Returns Status
Status Returns True if the parameters were acceptable.
Description Use this function to set the required serial port parameters to other than 8N1
com_RXblock("buf", "bufsize") or
com1_RXblock("buf", "bufsize") or
Syntax
com2_RXblock("buf", "bufsize") or
com3_RXblock("buf", "bufsize")
Returns Nothing
Description Bufsize bytes are received from the serial port to the string pointer "buf". If a receive buffer is active
and bufsize characters are available this function will return almost immediately otherwise it will block
until until the required bytes are received. This function is useful for protocols that require the reading
of a fixed amount of data in one hit. Once the data has been read into a buffer it also makes it easy to
perform CRC calculations on the data.
func main()
var st[20] ;
com_RXblock(str_Ptr(st), 8) ;
str_PutByte(str_Ptr(st)+8, 0) ; // terminate
endfunc
com_TXblock("buf", "bufsize") or
com1_TXblock("buf", "bufsize") or
Syntax
com2_TXblock("buf", "bufsize") or
com3_TXblock("buf", "bufsize")
Returns Nothing
Description Bufsize bytes are transmitted to the serial port from the string pointer "buf". If a transmit buffer is
active and space is available this function will return almost immediately otherwise it will block until
until the required bytes are sent. This function is useful for protocols that require the reading of a
fixed amount of data in one hit. Once the data has been read into a buffer it also makes it easy to
perform CRC calculations on the data.
func main()
var st[20] ;
to(st) ;
print("Hello there!") ;
com_TXblock(str_Ptr(st), 12) ;
endfunc
Returns nothing
Description This is the initialisation function for the serial communications buffered service with the ability to
receive the BREAK signal as though it is a character. The parameters are identical to com_Init() except
that each buffer entry can now only hold one byte. The BREAK ‘character’ is is a predefined constant
call BREAK.
Returns None
Description This is the initialisation function for the serial communications tramsmit buffered service with the
ability to sent the BREAK signal as though it is a character. The parameters are identical to
com_TXbuffer() except that each buffer entry can now only hold one byte. The BREAK ‘character’ is is
a predefined constant call BREAK.
Arguments Speed
Speed Specifies the I2C bus speed (See list in Description box)
SCLpin Specifies the GPIO pin to use for the SCL signal
SDApin Specifies the GPIO pin to use for the SDA signal
The arguments can be a variable, array element, expression or constant
Returns Status
1 if Successful
Status
0 if Unsuccessful
Description Calling this function configures the I2C module and initialises it to be ready for service. The I 2C clock
speed is specified by the Speed parameter. Multiple I2C Speed settings are available to suit various
requirements.
Constant Speed
I2C_SLOW 100KHz
I2C_MED 400KHz
I2C_FAST 1MHz
I2C_10KHZ 10KHz
I2C_20KHZ 20KHz
I2C_50KHZ 50KHz
I2C_250KHZ 250KHz
Note: Normally the I2C pins are PA0 to PA13, use of these pins has a couple of limitations, a) There is
no slew rate control at I2C_MED and b) I2C_FAST is not truly 1MHz. If either of these restrictions need
to be addressed, a special case of SCLpin = PA14 and SDApin = PA15 exists ONLY for speeds I2C_MED
(which uses slew rate control) and I2C_FAST (which is truly 1MHz).
Example I2C1_Open(I2C_MED, PA2, PA3); // Open the I2C port in 400KHz mode.
I2C1_Close(); or
Syntax I2C2_Close(); or
I2C3_Close();
Arguments None
Returns None
Description Calling this function closes the I2C port and disables the I2C hardware
I2C1_Start(); or
Syntax I2C2_Start(); or
I2C3_Start();
Arguments None
____
SDA \_______________________
I2C1_Stop(); or
Syntax I2C2_Stop(); or
I2C3_Stop();
Arguments None
Description Calling this function sends an I2C stop condition. The hardware first releases the SCL to high state,
and then releases the SDA line high.
_________________
SCL ____/
______________
SDA ______/
I2C1_Restart(); or
Syntax I2C2_Restart(); or
I2C3_Restart();
Arguments None
I2C1_Read(); or
Syntax I2C2_Read(); or
I2C3_Read();
Arguments None
Returns Byte
Byte Byte from the I2C Bus in the lower 8 bits.
Description Calling this function reads a single byte from the I2C bus.
Note: Data can only change when the clock is low.
__ __ __ __ __ __ __ __
SCL ____/ \___/ \___/ \___/ \___/ \___/ \___/ \___/ \_
__ __ 1__ __ 2__ __ 3__ __ 4__ __ 5__ __6___ __7__ __8__
SDA X_____ X______X______X______X_____X______X_____ X_____X
I2C1_Write(byte); or
Syntax I2C2_Write(byte); or
I2C3_Write(byte);
Arguments byte
byte The byte to be written to the I2C Bus.
The arguments can be a variable, array element, expression or constant
Returns Status
Returns 2 if NACK received
Status Returns 1 if ACK received
Returns 0 if Failed
I2C1_Ack(); or
Syntax I2C2_Ack(); or
I2C3_Ack();
Arguments None
Returns None
I2C1_Nack(); or
Syntax I2C2_Nack(); or
I2C3_Nack();
Arguments None
Returns None
I2C1_AckStatus(); or
Syntax I2C2_AckStatus(); or
I2C3_AckStatus();
Arguments None
Returns Status
Status Device Ack status
Description Call this function to get the ACK status from the slave device
The state of SDA is returned.
NB:- returns the state of SDA after the last clock pulse
__ Previous Clock Pulse
SCL X \______
____
SDA ____ X ____ Ack Status
I2C1_AckPoll(control); or
Syntax I2C2_AckPoll(control); or
I2C3_AckPoll(control);
Arguments control
control The control word to be written to the device.
The arguments can be a variable, array element, expression or constant
Returns Status
Status Device Ack Status
Description Call this function to wait for a device to return an ACK during ACK polling
The SDA is monitored for an Ack.
NB:- returns the state of SDA after the last clock pulse
__ Previous Clock Pulse
SCL X \______
____
SDA ____ X ____ Ack Status
Example r := I2C2_AckPoll(0xA0); //send the control byte the wait for a device
//to return poll the device until an ACK
//is received.
I2C1_Idle(); or
Syntax I2C2_Idle(); or
I2C3_Idle();
Arguments None
Returns Status
1 if Successful
Status
0 if Failed (Timed Out)
Description Call this function to wait until the I2C bus is inactive.
NB:- wait for the bus to become idle. Times out if not inactive within 1 second.
___ ________
SCL X ___ X /
___ ________
SDA X ___ X /
I2C1_Gets(buffer, size); or
Syntax I2C2_Gets(buffer, size); or
I2C3_Gets(buffer, size);
Returns count
count Returns the count of bytes actually read.
Description Reads up to size characters into buffer from an ascii string stored in a device. Reads up to the ASCII
NULL terminator and includes the terminator.
Example c := I2C3_Gets(buf, size); //read a string from the I2C Bus to buffer
//up to size characters.
I2C1_Getn(buffer, count); or
Syntax I2C2_Getn(buffer, count); or
I2C3_Getn(buffer, count);
Returns Status
Status Returns True if block read ok else returns False.
Description Reads count bytes in to buffer and returns True if function succeeds
Example I2C1_Getn(buffer, count); //read I2C count bytes from the I2C Bus to
//the buffer
I2C1_Puts(buffer); or
Syntax I2C2_Puts(buffer); or
I2C3_Puts(buffer);
Arguments buffer
buffer Storage for the string being written to the device.
The arguments can be a variable, array element, expression or constant
Returns Count
Count Returns the count of bytes actually written.
Description Writes an ASII string from buffer to a device. The ASCII NULL terminator is also written.
I2C1_Putn(buffer, count); or
Syntax I2C2_Putn(buffer, count); or
I2C3_Putn(buffer, count);
Returns written
written Returns number of bytes written.
Description Writes count bytes from the buffer to the device, and returns written if function succeeds.
2.14.1 sys_T()
Syntax sys_T();
Arguments None
Returns value
value Returns the value of system timer. (LO Word)
Description Returns the current value of the rolling 32bit system timer (1mse) LO word.
Example t := sys_T(); // .
2.14.2 sys_T_HI()
Syntax sys_T_HI();
Arguments None
Returns value
value Returns the value of system timer. (HI Word)
Description Returns the current value of the rolling 32bit system timer (1mse) HI word.
Example t := sys_T_HI(); //
Returns None
Description Set a countdown on the selected timer or 'top-up' if required. There are 8 timers TIMER0 to TIMER7
which stop at the count of 0. Maximum timeout period is 65, 535 milliseconds or 65.535 seconds.
A timer can be read with the sys_GetTimer("timernum") function.
2.14.4 sys_GetTimer(timernum)
Syntax sys_GetTimer(timernum);
Arguments timernum
timernum One of eight timers TIMER0 to TIMER7.
Returns Value
Value Returns 0 if timer has expired, or the current countdown value.
Description Returns 0 if timer has expired, or the current countdown value. There are 8 timers TIMER0 to
TIMER7 which stop at the count of 0. Maximum timeout period is 65, 535 milliseconds or 65.535
seconds.
A timer can be set with the sys_SetTimer("timernum", "value") function.
Example t := sys_GetTimer(TIMER2); //
Returns Address
Returns any previous event function address, or zero if there was no previous
Address
function.
Description Set a function to be called for selected timer. When the timer reaches zero, the function is called. The
called function must not have any parameters, and should not have a return value. This is necessary
because the timer event is invoked asynchronously to the mainline program (i.e, it is not called in the
normal way, so parameters and return values don’t apply).
Note:
When a child process is run using the file_run or file_exec function, or if a file was loaded with
file_Loadfunction and is executed, the loaded process gets its own code and memory space,
therefore, any timer that reaches zero that has a timer event attached in the parent code space, will
fail and cause a crash as an attempt is made to force the program counter to some wild place in the
child process - There are 2 ways to overcome this problem.
1] If a child process will not be requiring the use of any timers or timer events, the parent program
can simply use the eventsPostpone() function before calling or entering the child process. Once the
parent program regains control, the eventsResume() function will allow any events in the queue to
then be processed. The side effect of this method is that several events may bank up, and will execute
immediately once the eventsResume() takes place. This however disallows a child process to use any
timer events in the sub program so method 2 is preferable in this case.
2] The parent program can 'disconnect' the event(s) by setting it/them to zero prior to child process
execution, or setting the associated timer to zero so the event wont fire. In either case, it is necessary
to do the following:-
while(sys_EventQueue());
to ensure the event queue is empty prior to calling the child process. Note also that if just the timer
is set to zero, the child process cannot use this timer. If the timer was now set to a value and the old
event still existed, when the timer reaches zero the 'bad' parent address event will fire causing a
crash.
The reverse situation also applies of course, the same level of respect is required if a child program
needs to use any timer events. Method [1] (above) will not work as the events have been
postponed, stopping the child process from using any timer events. If the child process did an
eventsResume() in this case, everything would crash miserably. So the same applies, a child that
uses any timer events must respect any timers that may be used by the parent, and a child must
zero the sys_SetTimerEvent before returning to the parent.
2.14.6 sys_EventQueue()
Syntax sys_EventQueue();
Arguments None
Returns Count
Count Returns number of events .
Description returns the max number of events that were pending in the event queue since the last call to this
function. This can be used to assess event overhead burden, especially after or during a
sys_EventsPostpone action..
2.14.7 sys_EventsPostpone()
Syntax sys_EventsPostpone();
Arguments None
Returns None
Description Postpone any events until the sys_EventResume function is executed. The event queue will continue
to queue events, but no action will take place until a sys_EventResume function is encountered.
The queue will continue to receive up to 32 events before discarding any further events. This function
is required to allow a sequence of instructions or functions to occur that would otherwise be
corrupted by an event occurring during the sequence of instructions or functions. A good example of
this is when you set a position to print, if there was no way of locking the current sequence, an event
may occur which does a similar thing, and a contention would occur - printing to the wrong position.
This function should be used wisely, if any action that is required would take considerable time, it is
better to disable any conflicting event functions with a bypass flag, then restart the conflicting event
by re-issuing a timer value.
2.14.8 sys_EventsResume()
Syntax sys_EventsResume();
Arguments None
Returns None
Description Resume any postponed events. The queue will try to execute any events that were incurred during
the postponed period. Note that queued events are only checked for and executed at the the end of
each 4DGL instruction.
2.14.9 sys_DeepSleep(units)
Syntax sys_DeepSleep(units);
Arguments units
units Sleep timer units are approx 1 second. When in sleep mode, timing is controlled by an
RC oscillator, therefore, timing is not totally accurate and should not be relied on for
timing purposes
The arguments can be a variable, array element, expression or constant
Returns Status
Status Remaining time units when touch screen is touched, else returns zero.
Deep Sleep is a sleep state that is ‘deeper’ than the regular Sleep (for most display modules) and
therefore consumes less power. Some displays do not support being powered to a lower state, so
sleep and deepsleep power consumption can sometimes be roughly the same.
Puts the display and processor into lowest power mode for a period of time. If "units" is zero, the
display goes into sleep mode forever and needs power cycling to re-initialize. If "units" is 1 to
Description
65535, the display will sleep for that period of time, or will be woken when touch screen is touched.
The function returns the count of "units" that are remaining when the screen was touced. When
returning from deep sleep mode, some displays might lose their screen and/or need to be
reinitialised with disp_Init()
2.14.10 sys_Sleep(units)
Syntax sys_Sleep(units);
Arguments units
units Sleep timer units are approx 1 second. When in sleep mode, timing is controlled by an
RC oscillator, therefore, timing is not totally accurate and should not be relied on for
timing purposes
The arguments can be a variable, array element, expression or constant
Returns Status
Status Remaining time units when touch screen is touched, else returns zero.
Description Regular sleep, which puts the display and processor into low power mode for a period of time. If
"units" is zero, the display goes into sleep mode forever and needs power cycling to re-initialize. If
"units" is 1 to 65535, the display will sleep for that period of time, or will be woken when touch
screen is touched. The function returns the count of "units" that are remaining when the screen
was touced. When returning from sleep mode, the display and processor are restored from low
power mode.
Note: Sys_Sleep() was found to have an issue in PmmC’s prior to R33, the units value was not
always near 1 second. This has been corrected in PmmC R33.
2.14.11 iterator(offset)
Syntax iterator_(offset);
Arguments offset
offset Offset size for the next ++ or - - command
The arguments can be a variable, array element, expression or constant
Returns None
Description Sets the iterator size for the next postinc, postdec, preinc or predec by a specified value. The offset
will return to 1 after the next operation.
2.14.12 sys_GetDate()
Syntax sys_GetDate();
Arguments None
Returns None
2.14.13 sys_GetTime()
Syntax sys_GetTime();
Arguments None
Returns None
Returns Status
Status TRUE if valid date
If an I2C real time clock is present, this function can be used to synchronize the internal date to the
I2C RTC date.
Returns Status
Status TRUE if valid time
If an I2C real time clock is present, this function can be used to synchronize the internal time to the
I2C RTC time.
year Specifies the address for the storage location of the returned year value
month Specifies the address for the storage location of the returned month value
day Specifies the address for the storage location of the returned day value
Returns None
Description Returns the current year, month and day into variables.
Example Sys_GetDateVar(&year, &month, &day); // Read the current Date inot variables
hour Specifies the address for the storage location of the returned hour value
minute Specifies the address for the storage location of the returned minute value
second Specifies the address for the storage location of the returned second value
msecs Specifies the address for the storage location of the returned milli-second value
Returns None
Description Returns the current hour, minute, second and milli-second into variables.
Example Sys_GetTimeVar(&hour, &minute, &second, &msecs); // Get the current Time into
variables
2.15.1 file_Error()
Syntax file_Error();
Arguments None.
2.15.2 file_Count(filename)
Syntax file_Count(filename);
Arguments filename
filename Name of the file(s) for the search (passed as a string). 8.3 Format
Returns Count
Count Number of files that match the criteria.
2.15.3 file_Dir(filename)
Syntax file_Dir(filename);
Arguments filename
filename Name of the file(s) for the search (passed as a string). 8.3 Format
Returns Count
Count Number of files found that match the criteria.
Description 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.
2.15.4 file_FindFirst(fname)
Syntax file_FindFirst(fname);
Arguments fname
fname Name of the file(s) for the search (passed as a string). 8.3 Format
Returns Status
1: If at least one file exists that satisfies the criteria.
Status
0: If no file satisfies the criteria.
Description 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.
Example If (file_FindFirst(“*.4XE”))
Print(“File Found”);
endif
2.15.5 file_FindNext()
Syntax file_FindNext();
Arguments None
Returns Status
1: If more files exist that satisfy the criteria set in the file_FindFirst(fname)
Status
0: If no more files satisfy the criteria set in the file_FindFirst(fname)
Description 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.
2.15.6 file_Exists(fname)
Syntax file_Exists(fname);
Arguments fname
fname Name of the file for the search (passed as a string). 8.3 Format
Returns Status
1: File found
Status
0: File not found
Description 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.
Example If (file_Exists(“fil1.4XE”))
Print(“File Found”);
endif
Returns handle
Returns handle if file exists. Sets internal file error number accordingly (0 if no
handle
errors).
Description 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..
fname must be 8.3 format. Long Filenames are not supported. TESTPR~1.4XE for 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.
Note: 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.
2.15.8 file_Close(handle)
Syntax file_Close(handle);
Arguments handle
handle 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 Status
1: File Closed.
Status
0: File not closed.
Returns count
count Returns the number of characters read.
Description 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.
Returns Status
Status Returns TRUE if ok, usually ignored
Description Places the file pointer at the required position in a file that has been opened in 'r' (read) or 'a' (append)
mode. In append mode, file_Seek does not expand a filesize, instead, the file pointer (handle) is set
to the end position of the file, eg:- assuming the file size is 10000 bytes, file_Seek(handle, 0, 0x1234);
will set the file position to 0x00001234 (byte position 4660) for the file handle, so subsequent data
may be read from that position onwards with file_GetC(...), file_GetW(...), file_GetS(...), or an image
can be displayed with file_Image(...). Conversely, file_PutC(...), file_PutW(...) and file_PutS(...) can
write to the file at the position. A FE_EOF (end of file error) will occur if you try to write or read past
the end of the file.
Returns Status
Status Returns TRUE if ok, usually ignored
Description Places the file pointer at the position in a file that has been opened in 'r' (read) or 'a' (append) mode.
In append mode, file_Index does not expand a filesize, instead, the file pointer (handle) is set to the
end position of the file, eg:- assuming the record size is 100 bytes, file_Index(handle, 0, 100, 22); will
set the file position to 2200 for the file handle, so subsequent data may be read from that position
onwards with file_GetC(...), file_GetW(...), file_GetS(...), or an image can be displayed with
file_Image(...). Conversely, file_PutC(...), file_PutW(...) and file_PutS(...) can write to the file at the
position. A FE_EOF (end of file error) will occur if you try to write or read past the end of the file.
Returns Status
Status Returns TRUE if ok, usually ignored
Description Reads the 32 bit file pointer and stores it into 2 variables, HiWord and LoWord
Returns count
count Returns the number of bytes written.
Description 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.
Returns Status
Status Returns TRUE if ok, usually ignored.
Description Reads the 32 bit file size and stores it into 2 variables, HiWord and LoWord
Arguments x, y, handle
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)
Description 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(...).
Returns Status
Status Returns 0 if function successful.
Description Save an image of the screen shot to file at the current file position.
The image can later be displayed with file_Image(...); The file may be opened in append mode to
accumulate multiple images. Later, the images can be displayed with file_Seek(...).
The image is saved from x, y (with respect to top left corner), and the capture area is determined by
"width" and "height".
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
Returns Status
Status Returns true if function succeeded
Description 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.
Arguments handle
handle The handle that references the file.
Returns byte
byte Returns the next char from the file
Description 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.
Returns Status
Status Returns true if function succeeded
Description 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.
2.15.20 file_GetW(handle)
Syntax file_GetW(handle);
Arguments handle
handle The handle that references the file.
Returns Word
Word Returns the next word in the file
Description 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.
Returns count
count Returns the number of characters written (excluding the null terminator).
Description 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.
Returns Count
Count Returns the number of characters read from file (excluding the null terminator)
Description 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)
2.15.23 file_Erase(fname)
Syntax file_Erase(fname);
Arguments fname
fname Name of the file to be erased
Returns Status
1: if successful
Status
0: if unsuccessful
2.15.24 file_Rewind(handle)
Syntax file_Rewind(handle);
Arguments handle
handle The handle that references the file
Returns Status
Status Returns TRUE if ok, usually ignored
Description Resets the file pointer to the beginning of a file that has been opened in 'r' (read), 'w', or 'a' (append)
mode.
2.15.25 file_LoadFunction(fname.4XE)
Syntax file_LoadFunction(fname.4XE);
Arguments fname.4XE
fname.4XE Name of the 4DGL application program that is about to be loaded into RAM.
Returns Pointer
Returns a pointer to the memory allocation where the function has been loaded from
Pointer
file which can be then used as a function call.
Description 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.
res := mem_Free(popupWindow);
if(!res) goto FreeFunctionFailed; //should never happen if memory not
//corrupted
slidervals[6] := 40;
slidervals[7] := 25;
slidervals[8] := 45;
slidervals[9] := 5;
Returns Value
Value Returns the value from main in the called program.
Description 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.
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.
#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 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 touchY1[MAXBUTTONS];
var touchX2[MAXBUTTONS];
var touchY2[MAXBUTTONS];
#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 = FONT_1 to FONT_4
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
)
xgap := 2;
ygap := 2;
x1 := xorg;
y1 := yorg;
// 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];
endif
touchX1[n] := x1;
touchY1[n] := y1;
touchX2[n] := x2;
touchY2[n] := y2;
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 , FONT_4);
txt_MoveCursor(3, 0);
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)
n := 0;
r := 0;
return r;
endfunc
//==================================================================
func main()
var k, n, state, x, y;
var p, s, w, f;
redo:
w := 140;
f := FONT_4;
btnTextColor := BLACK;
btnBtnColor := LIGHTGREY;
gfx_Cls();
gfx_Set(BEVEL_WIDTH, 2);
txt_Set(FONT_ID, FONT_3);
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");
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
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
Returns Value
Value Returns the value from main in the called program.
Description This function is similar to file_Run, however, the main program in FLASH retains all memory
allocations (eg file buffers, memory allocated with mem_Alloc etc)
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.
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.
func main()
var i ;
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
repeat
forever
endfunc
Function on uSD:
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
mode 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.
Mode 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.
Returns Status
Returns a handle (pointer to the memory allocation) to the image control list that
Status has been created.
Returns NULL if function fails.
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:
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(MyImageControlHandle);
#constant OK 1
#constant FAIL 0
//-------------------------------------------------------------------
// 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, FONT_2);
txt_Set(TEXT_OPACITY, OPAQUE);
if (!file_Mount())
print("File error ", file_Error());
while(!CheckTouchExit());
// just hang if we didnt get the image list
r := FAIL;
goto quit;
endif
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
pause(3000);
gfx_Cls();
repeat
n := 0;
n++;
wend
until(exit);
quit:
return r;
endfunc
//===================================================================
2.15.29 file_Mount()
Syntax file_Mount();
Arguments None
Returns Status
Status Returns true if successful.
Description 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().
2.15.30 file_Unmount()
Syntax file_Unmount();
Arguments None
Returns None
Description Release any buffers for FAT16 and unmount the Disk File System. This function is to be called to close
the FAT16 file system.
2.15.31 file_PlayWAV(fname)
Syntax file_PlayWAV(fname);
Arguments fname
fname Name of the wav file to be opened and played
Returns value
value If there are no errors, returns number of blocks to play (1 to 32767)
If errors occurred, the following is returned
-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
Description 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.
This function automatically grabs a chunk of memory for a file buffer, and a wave buffer. The minimum
memory requirement is about 580 bytes for the disk io service and a minimum wave buffer size of
1024. The size of the wave buffer allocation can be increased by the snd_BufSize function.
Note: The memory is only required during the duration of play, and is automatically released while
not in use.
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
Returns Status
1: if successful
Status
0: if unsuccessful
Returns Status
1: if successful
Status
0: if unsuccessful (Handle not valid, or Date/Time not valid)
Description 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.
Note that the FAT file system can only store even numbered seconds.
CHECKUPDATE_QUERY 1
Checks the specified file and compares its DateTime to the program running in Flash.
options
CHECKUPDATE_UPDATENEWER 2
Updates the program in Flash and resets the display if the program on uSD is newer.
CHECKUPDATE_UPDATEALWAYS 3
Always updates the program in Flash and resets the display.
Returns value
If update occurs and the program is running from Flash, as display is reset after update.
Otherwise if a query or an error occurs, the following is returned:
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.
value
CHECKUPDATE_UPDATEDONE 3
An update was performed and the program is running from RAM.
CHECKUPDATE_NOFILE 4
The specified file does not exist, or uSD not initialised.
CHECKUPDATE_INVALIDFILE 5
The specified file is not a valid .4xe or .4fn
Description Checks and/or updates the program running in Flash using the specified file on uSD.
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
2.16.1 Snd_Volume(var)
Syntax Snd_Volume(var);
Arguments var
var sound playback volume
The arguments can be a variable, array element, expression or constant
Returns None
Description Set the sound playback volume. Var must be in the range from 8 (min volume) to 127 (max volume).
If var is less than 8, volume is set to 8, and if var > 127 it is set to 127.
2.16.2 Snd_Pitch(pitch)
Syntax Snd_Pitch(pitch);
Arguments pitch
pitch Sample's playback rate. Minimum is 4KHz. Range is, 4000 – 65535.
The arguments can be a variable, array element, expression or constant
Returns value
value Returns sample's original sample rate.
Description Sets the samples playback rate to a different frequency. Setting pitch to zero restores the original
sample rate.
Example snd_Pitch(7000); //Play the wav file with a sample frequency of 7KHz.
2.16.3 Snd_BufSize(var)
Syntax Snd_BufSize(var);
Arguments var
var Specifies the buffer size.
0 = 1024 bytes (default)
1 = 2048 bytes
2 = 4096 bytes
3 = 8192 bytes
The arguments can be a variable, array element, expression or constant
Returns None.
Description Specify the memory chunk size for the wavefile buffer, default size 1024 bytes. Depending on the
sample size, memory constraints, and the sample quality, it may be beneficial to change the buffer
size from the default size of 1024 bytes.
This function is for control of a wav buffer, see the file_PlayWAV(..) ; function
2.16.4 snd_Stop()
Syntax snd_Stop();
Arguments None
Returns None
Description Stop any sound that is currently playing, releasing buffers and closing any open wav file.
This function is for control of a wav buffer, see the file_PlayWAV(..) ; function
2.16.5 snd_Pause()
Syntax snd_Pause();
Arguments None
Returns None
Description Pause any sound that is currently playing, does nothing until sound is resumed with snd_Continue().
The sample can be terminated with snd_Stop.
Buffers and closes any open wav file.
This function is for control of a wav buffer, see the file_PlayWAV(..) ; function
2.16.6 snd_Continue()
Syntax snd_Continue();
Arguments None
Returns None
2.16.7 snd_Playing()
Syntax snd_Playing();
Arguments None
Returns value
value Number of 512 byte blocks to go.
Description Returns 0 if sound has finished playing, else return number of 512 byte blocks to go.
This function is for control of a wav buffer, see the file_PlayWAV(..) ; function
Returns status
status Returns TRUE if freq >= 10 and a wav file is not currently playing.
Description Produces a pure square wave waveform on the audio output pin. This command is designed to drive
Piezo transducers which require this sort of input. Whilst it also works on displays with a builtin
amplifier the sound produced is extremely annoying.
2.17.1 str_Ptr(&var)
Syntax str_Ptr(&var);
Arguments var
var Pointer to string buffer
Returns Pointer
Pointer Returned value is the byte pointer to string buffer.
Returns Status
Status Returns TRUE if function succeeds, advancing ptr
Returns Status
Status Returns TRUE if function succeeds, advancing ptr.
func main()
to(buffer); print("0x1234 0b10011001 12345 abacus");
p := str_Ptr(buffer); // raise a string pointer so we can use the
// string functions
Returns Status
Status Returns TRUE if function succeeds, advancing ptr
func main()
Returns Status
Status Returns TRUE if function succeeds, advancing ptr.
func main()
endfunc
2.17.6 str_GetByte(ptr)
Syntax str_GetByte(ptr);
Arguments ptr
ptr Address of byte array or string.
Returns byte
byte Returns the byte value at pointer location.
func main()
to(buffer); print("Testing 1 2 3");
p := str_Ptr(buffer); // get a byte pointer from a word region
n := 0;
endfunc
2.17.7 str_GetWord(ptr)
Syntax str_GetWord(ptr);
Arguments ptr
ptr Byte pointer
Returns Word
Word Returns the word at pointer location.
func main()
endfunc
Returns None
func main()
endfunc
Returns None
Description Put a word value into a byte buffer at ptr, similar to "POKEW" in basic.
It is not necessary for byte pointer ptr to be word aligned
endfunc
Returns Value
Returns 0 if no match, else advance ptr to the next position after the match and
Value
returns a pointer to the match position.
Note: The address of the pointer must be passed so the function can advance it if required.
func main()
repeat
forever
endfunc
Returns Value
Returns 0 if no match, else advance ptr to the next position after the match and
Value
returns a pointer to the match position.
Note: The address of the pointer must be passed so the function can advance it if required.
func main()
// string to parse
to(buffer); print( "The sun rises in the East" );
p := str_Ptr(buffer); // string pointer to be used
// with string functions
q := p;
// Will match if the string starts with "The", or "the"
if ( n := str_MatchI( &p, "the" ) )
str_Printf ( &p, "%s\n" ); // print remainder of string
else
print ( "not found\n" );
endif
print ( "startpos=" , q , "\nfindpos=" , n , "\nendpos=" , p );
repeat
forever
endfunc
Returns Value
Returns 0 if not found.
Value
Returns the address of the first character of the match if successful.
func main()
txt_Set ( FONT_ID, FONT2 );
strings[0] := "useful" ;
strings[1] := "string" ;
strings[2] := "way" ;
strings[3] := "class" ;
to(buffer); print ( "and by the way, the string class is rather
useful " );
// raise a string pointer so we can use the string functions
p := str_Ptr(buffer);
// offset into the buffer a little so we don't see word "way"
p := p + 13;
print( "p=" , p , "\n\n" ); // show the start point of our search
n := 0;
while ( n < 4 )
print( "\"" , [STR] strings[n] , "\" is at pos " , str_Find( &p
, strings[n++] ) , "\n" );
wend
//note that p is unchanged
print ( "\nNOTE: p is unchanged, p=" , p );
repeat
forever
endfunc
Returns Value
Returns 0 if not found.
Value
Returns the address of the first character of the match if successful.
func main()
txt_Set ( FONT_ID, FONT2 );
strings[0] := "USEFUL" ;
strings[1] := "string" ;
strings[2] := "way" ;
strings[3] := "class" ;
to(buffer); print ( "and by the way, the String Class is rather
useful " );
// raise a string pointer so we can use the string functions
p := str_Ptr(buffer);
// offset into the buffer a little so we don't see word "way"
p := p + 13;
// show the start point of our search
print( "p=" , p , "\n\n" );
n := 0;
while ( n < 4 )
print( "\"" , [STR] strings[n] , "\" is at pos " , str_FindI (
&p , strings[n++] ) , "\n" );
wend
//note that p is unchanged
print ( "\nNOTE: p is unchanged, p=" , p );
repeat
forever
endfunc
2.17.14 str_Length(ptr)
Syntax str_Length(ptr);
Arguments ptr
ptr Pointer to string buffer.
Returns Value
Value Returns String length.
// Array Example
func main()
var c[40]; // 80 character buffer for a source string
var pc; // This will be a String pointer to c[]
Format Specifiers:
%c character
%s string of characters
%d signed decimal
%ld long decimal
%u unsigned decimal
%lu long unsigned decimal
%x hex byte
%X hex word
%lX hex long
%b binary word
%lb long binary word
(number) width description (use between '%' and format specifier to set the field
width).
Note: If (number) is preceded by 0, the result is Left-pads with zeroes (0) instead of
spaces.
Returns Pointer
Returns the position of last extraction point. This is useful for processing by other
Pointer
string functions.
Description This function prints a formatted string from elements derived from a structured byte region.
There is only one input argument, the byte region pointer ptr which is automatically advanced as the
format specifier string is processed. The format string is similar to the C language, however, there are
a few differences, including the addition of the indirection token * (asterix).
func main()
var k;
p := q;
k := str_Printf ( &p , "%04s" ); // prints 4 leading spaces before
// string
n := 0;
m[n++] := "Mrs Smith" ;
m[n++] := 200 ;
m[n++] := 300 ;
m[n++] := 0xAA55 ;
m[n++] := 500 ;
endfunc
Returns Pointer
Pointer Returns pointer to the destination.
Description Appends a copy of the source string to the destination string. The terminating null character in
destination is overwritten by the first character of source, and a new null-character is appended at
the end of the new string formed by the concatenation of both in destination.
func main()
var p ;
to(buf) ;
print("Hello ") ;
p := str_Ptr(buf) ;
str_Cat(p,"There"); // Will append "There" to the end of buf
print([STR] buf) ;
repeat
forever
endfunc
Returns Pointer
Pointer Returns pointer to the destination.
func main()
var p ;
to(buf) ;
print("Sun ") ;
p := str_Ptr(buf) ;
str_CatN(p,"Monday",3); // Concatenate "Mon" to the end of buf
print([STR] buf) ;
repeat
forever
endfunc
Returns Pointer
Pointer Returns a pointer to the end of the destination (which is "dest" + "count").
Description Copy bytes from "src" to "dest", stopping only when "count" is exhausted. No terminator is appended,
it is purely a byte copy, and any zeroes encountered will also be copied.
Example var src, dest, mybuf1[10], mybuf2[10]; // string pointers and two 20 byte buffers
to(mybuf1); putstr("TESTING 123");
src := strPtr(mybuf1);
dest := str_Ptr(mybuf2);
src += 6; // move src pointer to "G 123"
str_ByteMove(src, dest, 6); // move to second buffer (including the zero terminator)
Returns Pointer
Pointer Returns a pointer to the 0x00 string terminator at the end of "dest" (which is "dest"
+ str_Length(src); ).
Description Copy a string from "src" to "dest", stopping only when the end of source string "src" is encountered
(0x00 terminator). The terminator is always appended, even if "src" is an empty string.
Returns Pointer
Pointer Returns a pointer to the 0x00 string terminator at the end of "dest" (which is "dest"
+ str_Length(src); ).
Description Copy a string from "src" to "dest", stopping only when "count" is exhausted, or end of source string
"str" is encountered (0x00 string terminator). The terminator is always appended, even if "count" is
zero, or "src" is a null string.
Returns None
Description Specifies a new touch detect region on the screen. This setting will filter out any touch activity outside
the region and only touch activity within that region will be reported by the status poll
touch_Get(TOUCH_STATUS) function.
2.18.2 touch_Set(mode)
Syntax touch_Set(mode);
Arguments mode
mode mode = TOUCH_ENABLE (Mode 0) Enable Touch Screen
touch_Set(TOUCH_ENABLE);
Enables and initialises Touch Screen hardware
touch_Set(TOUCH_DISABLE);
Disables the Touch Screen.
Note: Touch Screen task runs in the background and disabling it when not in use
will free up extra resources for 4DGL CPU cycles.
touch_Set(TOUCH_REGIONDEFAULT);
This will reset the current active region to default which is the full screen area
Returns None
Example touch_Set(TOUCH_ENABLE); // .
2.18.3 touch_Get(mode)
Syntax touch_Get(mode);
Arguments mode
mode mode = TOUCH_STATUS (Mode 0): Get Status
mode = TOUCH_GETX (Mode 1) : Get X coordinates
mode = TOUCH_GETY (Mode 2) : Get Y coordinates
Returns Value
Value mode = TOUCH_STATUS (Mode 0)
Returns the various states of the touch screen
0 = NOTOUCH
1 = TOUCH_PRESSED
2 = TOUCH_RELEASED
3 = TOUCH_MOVING
if (vertical)
if ( x > 170 && (y > 240 && y < 270 ))// Horiz button
vertical := 0;
exit := 1;
endif
else
if ( x > 170 && (y > 200 && y < 230 ))// Vert button
vertical := 1;
exit := 2;
endif
endif
endif
2.18.4 touch_TestArea(&rect)
Syntax touch_TestArea(&rect);
Arguments rect
rect An array of 4 vars, x1, y1, x2, y2 (using absolute co-ordinates)
Returns Status
Status Returns TRUE if last touch co-ordinates are within the absolute co-ordinate test area.
Description The touch_TestArea function creates a test area based on the parameters in rect, and returns true if
the last touch resided within the test area.
repeat
state := touch_Get(TOUCH_STATUS);// look for any touch activity
x := touch_Get(TOUCH_GETX);
y := touch_Get(TOUCH_GETY);
gfx_MoveTo(150, 0);
print("x: ",x," ");
gfx_MoveTo(150, 15);
print("y: ",y," ");
curStatus := touch_TestArea(r);
if(curStatus != prevStatus)
gfx_MoveTo(0,0);
if(curStatus)
print("touched! ");
else
print("no touch!");
endif
prevStatus := curStatus;
endif
forever
2.18.5 touch_TestBox(&rect)
Syntax touch_TestBox(&rect);
Arguments rect
rect An array of 4 vars, x1, y1, width, height
Returns Status
Status Returns TRUE if last touch co-ordinates are within the boxed test area.
Description The touch_TestArea function creates a test box based on the parameters in rect, and returns true if
the last touch resided within the boxed test area.
rect is an array of 4 vars, x1, y1, width, height (using boxed co-ordinates)
repeat
state := touch_Get(TOUCH_STATUS);// look for any touch activity
x := touch_Get(TOUCH_GETX);
y := touch_Get(TOUCH_GETY);
gfx_MoveTo(150, 0);
print("x: ",x," ");
gfx_MoveTo(150, 15);
print("y: ",y," ");
curStatus := touch_TestBox(r);
if(curStatus != prevStatus)
gfx_MoveTo(0,0);
if(curStatus)
print("touched! ");
else
print("no touch!");
endif
prevStatus := curStatus;
endif
forever
The following functions are Image File System for use with a SPI Flash Memory device, only available for
the Flash-based PmmC.
Returns Status
Status Returns TRUE if index OK and function successful
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Sets the position where the image will next be displayed. Returns TRUE if index was ok and function
was successful. (the return value is usually ignored).
You may turn off an image so when img_Show() is called, the image will not be shown.
This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Returns Status
Status Returns TRUE if index OK and function successful
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Enables a selected image in the image list. Returns TRUE if index was ok and function was successful.
This is the default state so when img_Show() is called all the images in the list will be shown.
To enable all of the images in the list at the same time set index to -1.
To enable a selected image, use the image index number.
Returns Status
Status Returns TRUE if index OK and function successful
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Disables an image in the image list. Returns TRUE if index was ok and function was successful. Use
this function to turn off an image so that when img_Show() is called the selected image in the list will
not be shown.
To disable all of the images in the list at the same time set index to -1.
Returns Status
Status Returns TRUE if index OK and function successful
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Darken an image in the image list. Returns TRUE if index was ok and function was successful. Use this
function to darken an image so that when img_Show() is called the control will take effect. To darken
all of the images in the list at the same time set index to -1.
Note: This feature will take effect one time only and when img_Show() is called again the darkened
image will revert back to normal.
Returns Status
Status Returns TRUE if index OK and function successful
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Lighten an image in the image list. Returns TRUE if index was ok and function was successful. Use this
function to lighten an image so that when img_Show() is called the control will take effect. To lighten
all of the images in the list at the same time set index to -1.
Note: This feature will take effect one time only and when img_Show() is called again the lightened
image will revert back to normal.
Returns Status
Status TRUE if successful, usually ignored
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Set specified word in an image entry. Returns TRUE if successful, return value usually ignored.
Note: Not all Constants are listed as some are Read Only.
img_Show(..) will now show error box for out of range video frames. Also, if frame is set to -1, just a
rectangle will be drawn in background colour to blank an image. It applies to PmmC R29 or above.
Returns Value
value Returns the image entry in the list.
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Returns Status
Status Returns TRUE if successful, usually ignored
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Returns Status
Status Returns TRUE if successful, usually ignored
Description This function SETS one or more bits in the IMAGE_FLAGS field of an image control entry. "value"
refers to various bits in the image control entry (see image attribute flags).
A '1' bit in the "value" field SETS the respective bit in the IMAGE_FLAGS field of the image control
entry.
Example :
:
img_Enable(Ihndl, SPRITE_CAT); // we'll also use small cat video
img_SetAttributes(Ihndl, SPRITE_CAT, I_NOGROUP);
img_SetPosition(Ihndl, SPRITE_CAT, 160, 180); // set its position
:
Note: if index is set to -1, the attribute is altered in ALL of the entries in the image list
.
Returns Status
Status Returns TRUE if successful, usually ignored
Description Clear various image attribute flags in a image control entry. (see image attribute flags below)
Returns Status
Returns index if Touched
Status
Returns -1 if not Touched
Description This function requires that an image control has been created with the file_LoadImageControl(...);
function.
Returns index if image touched or returns -1 image not touched. If index is passed as -1 the function
tests all images and returns -1 if image not touched or returns index.
Returns Status
Status Returns TRUE if index was ok and function successful
Description This Functions sets a position in an image control for sequential reading of pixels from the uSD card
(fat16 or raw modes supported)
This function provides a means of preparing to load an image, or part of an image, to an array. (see
img_SequentialRead)
h := img_GetWord(handle, 0, IMAGE_HEIGHT);
w := img_GetWord(handle, 0, IMAGE_WIDTH);
Returns Status
Status Returns TRUE if index was ok and function successful
Description Once a position has ben set with the img_SelectReadPosition function, this function can then used
for sequential reading of pixels from image storage.
"ptr" must point to a valid array that is at least the size of "count", or part of an image, to an array.
(see img_SelectReadPosition)
Returns Count
Count Returns number of characters read
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Reads the number of bytes specified by "size" from the file referenced by "handle" into a destination
memory buffer. If "dest" is zero, data is directed to GRAM window.
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns Status
Status Returns true if successful, usually ignored
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Set file position to specified address for the file handle so subsequent data may be read from that
position onwards with img_FileGetC(...), img_FileGetW(...) or img_FileGetS(...).
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
HiSize Contains the upper 16bits of the size of the file records
LoSize Contains the lower 16bits of the size of the file records
Returns Status
Status Returns true if successful, usually ignored
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Set file seek position to specified address for the file handle so subsequent data may be read from
that position onwards with img_FileGetC(...), img_FileGetW(...) or img_FileGetS(...).
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Example res := img_FileIndex(hSource, 0, 1000, 123, 1); // set file seek position
to 123000
HiWord Specifies location for the upper 16bits of the file pointer
LoWord Specifies location for the lower 16bits of the file pointer
Returns Status
Status Returns true if successful
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Reads the current 32 bit file pointer and stores it into the two variables specified in "HiWord" and
"LoWord".
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
HiWord Specifies location for the upper 16bits of the file size
LoWord Specifies location for the lower 16bits of the file size
Returns Status
Status Returns true if successful
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Reads the 32-bit file size and stores it into the two variables specified in "HiWord" and "LoWord".
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns byte
byte Returns next char from file.
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
This function reads a byte from the file, at the position indicated by the associated file-position pointer
and advances the pointer appropriately (incremented by 1).
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns byte
byte Returns the next word read in file.
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
This function reads a word (2 bytes) from the file, at the position indicated by the associated file-
position pointer and advances the pointer appropriately (incremented by 2).
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns result
result Returns pointer to string or null if failed
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
This function reads a line of text to a buffer (specified by "*string") from a file at the current file
position indicated by the associated file-position pointer and advances the pointer appropriately.
This function reads only reads up to "size - 1" characters into "*string" (one character is reserved for
the null-terminator). Characters are read until either a newline or an EOF is received or until the
number of characters read reaches "size - 1" or a read error is received.
img_FileGetS(...) 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), or
C] It reaches the end of file
D] A read error occurs.
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns byte
byte Returns true if file rewound successfully, usually ignored
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Resets the file pointer to the the beginning of the open file.
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns pointer
Returns a pointer to the memory allocation where the function has been loaded from
pointer
file which can be then used as a function call.
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Load a function or program from disk and return a function pointer to the allocation.
The function can then be invoked just like any other function would be called via a function pointer.
Parameters may be passed to it in a conventional way. The callers stack is shared by the loaded
function, however any global variables in the loaded function are private to that function.
The function may be discarded at any time when no longer required, freeing its memory resources
through mem_Free(..).
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
res := mem_Free(popupWindow);
if(!res) goto FreeFunctionFailed; // should never happen if memory not
corrupted. The callers stack is shared by the loaded function, however any
global variables in the loaded function are private to that function.
Returns value
value Returns the value from main in the called program.
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Load a program from disk where the current program releases any allocated memory but retains the
stack and global memory.
If arglistptr is 0, no arguments are passed, else, arglist points to an array, the first element being the
number of elements in the array.
The func 'main' in the called program accepts the arguments, if any. The arguments can only be passed
by value, no pointers or references can be used as all memory is cleared before the file is loaded.
Refer to img_FileExec(...) and img_FileLoadFunction(…) for functions that can pass by reference.
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns value
value Returns the value from main in the called program.
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Load a program from disk and returns like a function, the calling program is kept active and control
returns to it.
The func 'main' in the called program accepts the arguments, if any. If arglistptr is 0, no arguments
are passed, else arglist points to an array, the first element being the number of elements in the array.
This function is similar to img_FileLoadFunction(...), however, the function argument list is passed by
pointer, and the memory consumed by the function is released as soon as the function completes.
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns byte
If there are no errors, returns number of blocks to play (1 to 32767)
If errors occurred, the following is returned:
-7 : Insufficient memory available for WAV buffer and file
-6 : cant play this rate
byte -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
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
Play a wave file at index "index" in the image filesystem "handle". This function automatically grabs
a chunk of memory for a file buffer, and a wave buffer.
The minimum memory requirement is about 580 bytes for the disk I/O service and a minimum wave
buffer size of 1024. The size of the wave buffer allocation can be increased by the snd_BufSize
function. The default size 1024 bytes. The memory is only required during the duration of play, and is
automatically released while not in use.
Note: This function is only for files embedded in a GCF, for Flash only, ie this is not valid for GCI and
uSD card access.
Returns none
Description This function requires that an image file control has been created with the file_LoadImageControl(...);
function under Mode 3.
2.20.1 mem_Alloc(size)
Syntax mem_Alloc(size);
Returns value
Returned value is the pointer (Word) to the allocation if successful.
value
If function fails returns a null (0).
Description Allocate a block of memory to pointer myvar. The allocated memory contains garbage but is a fast
allocation.
The block must later be released with mem_Free(myvar);
2.20.2 mem_AllocV(size)
Syntax mem_AllocV(size);
Returns Value
Returned value is the pointer (Word) to the allocation if successful.
Value
If function fails returns a null (0).
Description Allocate a block of memory to pointer myvar. The block of memory is filled with initial signature
values. The block starts with A5,5A then fills with incrementing number eg:-
A5,5A,00,01,02,03...FF,00,11.... This can be helpful when debugging. The block must later be released
with mem_Free(myvar).
2.20.3 mem_Allocz(size)
Syntax mem_Allocz(size);
Arguments size
size Specifies the number of bytes that's allocated from the heap.
Returns Value
Returned value is the pointer to the allocation if successful. If function fails returns a
Value
null (0).
Description Allocate a block of memory to pointer myvar. The block of memory is filled with zeros.
The block must later be released with mem_Free(myvar);
Returns newptr
newptr Pointer to the new object location
Description The function may move the memory block to a new location, in which case the pointer to the new
location is returned.
The content of the memory block is preserved up to the lesser of the new and old sizes, even if the
block is moved.
If the new size is larger, the value of the newly allocated portion is indeterminate.
In case that ptr is NULL, the function behaves exactly as mem_Alloc(), assigning a new block of size
bytes and returning a pointer to the beginning of it.
In case that the size is 0, the memory previously allocated in ptr is deallocated as if a call to
mem_Free(myvar) was made, and a NULL pointer is returned.
2.20.5 mem_Free(allocation)
Syntax mem_Free(allocation);
Arguments allocation
allocation specifies the location of memory block to free up.
Returns Status
Returns non-zero if function is successful
Status
Returns 0 if the function fails.
Description The function de-allocates a block of memory previously created with mem_Alloc(...), mem_AllocV(...)
or mem_AllocZ(...).
2.20.6 mem_Heap()
Syntax mem_Heap();
Arguments None
Returns Value
Value Returns the largest available byte memory chunk in the heap.
Description Returns byte size of the largest chunk of memory available in the heap.
Returns Pointer
Pointer Returns the pointer.
func main()
Returns Pointer
Pointer Returns source.
Note:
Note that count is a byte count, this facilitates comparing word aligned byte arrays when using word
aligned packed strings.
Source can be a string constant e.g. myptr := mem_Copy("TEST STRING", ptr2, 12);
Returns Value
Returns 0 if we have a match, -1 if ptr1 < ptr2, and +1 if ptr2 > ptr1.
Value
(The comparison is done alphabetically)
Returns None
Description This function (and the similar mem_ArrayOp2 function) can be used to perform highly optimised
operation against an array of data. Mem_ArrayOp1 is for Single Arrays.
func main()
var i, j, res[2], v1[2], v2[2] ;
repeat
forever
endfunc
Returns None
Description This function (and the similar mem_ArrayOp1 function) can be used to perform highly optimised
operation against an array of data. Mem_ArrayOp2 is for Dual Arrays.
func main()
repeat
forever
endfunc
2.21.1 pause(time)
Syntax pause(time);
Arguments time
Returns nothing
Description Stop execution of the user program for a predetermined amount of time.
Returns result
result See description.
Description 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.
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, eg :
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");
repeat forever
endfunc
Returns result
result See description.
Description 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.
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, eg:
key := 5000;
r := lookup16(key, 5,10,20,50,100,200,500,1000,2000,5000,10000);
//r := lookup16(key, LEGALVALS);
if(r)
print("\nSearch value 5000 \nfound at index ", r);
else
putstr("\nValue not found");
endif
repeat forever
endfunc
Returns pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Performs floating point addition (A+B) and returns the value in the result register.
Returns pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Performs floating point Subtraction (A-B) and returns the value in the result register.
Returns pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Performs floating point Multiplication (A * B) and returns the value in the result register.
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 origin to point 0, 108,
//printing will start from this point
print("steps: ", [DEC4Z]Vsteps);// print the number of steps
Returns pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Performs floating point Division (A/B) and returns the value in the result register.
Returns pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Raises A to power B (AB) and returns the result value in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Rounds value up to the integer value. Removes fractional part, rounding up correctly.
print("result: ");
flt_PRINT(result,"%.5f");
print("\n");
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Rounds value down to the integer value. Removes fractional part, rounding down correctly.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the SINE of float value in radians and returns the value in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the COSINE of float value in radians and returns the value in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the TANGENT of float value in radians and returns the value in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the ARCSINE of float value and returns the angle in radians in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the ARCCOS of float value and returns the angle in radians in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the ARCTAN of float value and returns the angle in radians in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the Exponent of float value and returns the value in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the Natural Log of float value and returns the value in the result register.
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 pointer
Returns a pointer to the float result register or zero if error occurs. Carry and overflow
pointer
are not affected.
Description Calculates the square root of float value and returns the value in the result register.
Returns status
status True if A < B, false otherwise
if(flt_LT(floatA, floatB))
print("floatA is less than floatB\n");
endif
Returns status
status True if A == B, false otherwise
if(flt_EQ(floatA, floatB))
print("floatA is equal to floatB\n");
else
print("floatA is not equal to floatB\n");
endif
Returns status
status True if A != B, false otherwise
if(flt_NE(floatA, floatB))
print("floatA is not equal to floatB\n");
else
print("floatA is equal to floatB\n");
endif
Returns status
status True if A > B, false otherwise
if(flt_GT(floatB, floatA))
print("floatB is greater than floatA\n");
endif
Returns status
status True if A >=B, false otherwise
if(flt_GE(floatB, floatA))
print("floatB is greater than or equal to floatA\n");
endif
Returns status
status True if A <= B, false otherwise
if(flt_LE(floatB, floatA))
print("floatB is less than or equal to floatA\n");
endif
2.22.24 flt_SGN(&floatval)
Syntax flt_SGN(&floatval)
Returns value
value Returns 16bit integer -1 if float sign is negative, or zero if positive
Description 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
if(flt_SGN(floatA) == -1)
print("floatA is a negative value\n");
endif
2.22.25 flt_FTOI(&floatval)
Syntax flt_FTOI(&floatval)
Returns value
value The integer value of the float
Description Converts a floating point number to a 16bit integer. The floating point number is rounded up or down
accordingly.
result := flt_FTOI(floatA);
print("result: ", result,"\n");
Returns pointer
pointer Returns the pointer to the float result, normally ignored
Description Converts a 16bit signed integer value to a signed floating point number.
Returns pointer
pointer Returns the pointer to the float result.
Description Converts a 16bit unsigned integer value to a positive floating point number.
Returns pointer
pointer Returns the pointer to the float result.
Description Converts a 32bit signed integer value to a signed floating point number.
Returns pointer
pointer Returns the pointer to the float result.
Description Converts a 32bit unsigned integer value to a positive floating point number.
Returns pointer
pointer Returns the pointer to the float result.
Description Converts the number string to a valid float value. Carry and overflow are not affected.
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 status
status Returns ‘0’ if successfull.
Description
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.
%<flag><width>.<precision><specifier>
modifier
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
//specify format
print(" %f: ");
flt_PRINT(floatA,"%f");//prints "5000.000000"
//default precision is six 0's after the decimal point
print("\n");
print("\n");
//specify precision
print(" %.2f: ");
flt_PRINT(floatA,"%.2f");//prints "5000.00"
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");
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 Status
status Returns ‘0’ if successfull.
Description 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)”.
//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");
//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");
2.23.1 sys_PmmC()
Syntax sys_Pmmc();
Arguments None
Returns None
2.23.2 sys_Driver()
Syntax sys_Driver();
Arguments None
Returns None
Description Prints the system driver name and date string eg "uLCD-32WDTU-A\n130411”
These functions can be used to access an SPI FLASH storage device connected to the selected SPI port, and correctly
initialised with the spi_Init(...) function, each FLASH device also needs a dedicated enable pin pulled high and set as
output from within the driving program. Devices like the M25Pxx and A25Lxx which has 512Kbit to 128Mbit of Serial
Flash Memory are supported. Other similar devices should work. Additionally, support for more than 16MB of serial
flash is available by using SPI_ADDRESS_MODE4 in the relevant SPI Init function.
Note that when accessing certain file types via spiflash it may be necessary to append an identifiable EOF character
(eg ^Z) to enable your program to properly detect EOF.
pin_HI(EnablePin) ;
pin_Set(PIN_OUT,EnablePin) ;
SPI1_SDI_pin(SDIPin) ;
SPI1_SCK_pin(ClockPin) ;
SPI1_SDO_pin(SDOPin) ;
SPI1_Init(SPI_SPEED15, SPI8_MODE_5, EnablePin) ;
Note that the Init must be done in 8 bit mode, but the internal functions will automatically flip between 8 and 16 bit
mode to gain optimal performance.
Returns Nothing
Description Erases the required block in a FLASH media device. The function returns no value, and the operation
can take up to 3 milliseconds.
Returns Nothing
Description Erases the entire flash media device. The function returns no value, and the operation can take up to
80 seconds depending on the size of the flash device. Note that not all devices support this command.
Returns Value
Value Returns the value from main in the called program.
Description This function is similar to spiflash_Run, however, the main program in FLASH retains all memory
allocations (eg 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.
This function is similar to spiflash_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.
spiflash_SetAdd should have previously been called to identify the address of the program to be
called.
Returns byte
byte Returns the next char from the file
Description Reads a character (or byte) from the SPI FLASH memory device on the specified SPI port and enable
pin. The source is the address set by spiflash_SetAdd(), or incremented by subsequent reads or
writes.
Returns Count
Count Returns the number of characters read from file (excluding the null terminator)
Description This function Reads a line of text to a buffer (specified by "*string") from the FLASH memory device
on the specified SPI port and enable pin into the specified destination. The source is the address set
by spiflash_SetAdd(), or incremented by subsequent reads or writes.
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)
Returns Word
Word Returns the next word in the file
Description This function reads a word (2 bytes) from the FLASH memory device on the specified SPI port and
enable pin, at the spiflash_SetAdd(), or incremented by subsequent reads or writes and advances the
pointer appropriately (incremented by 2).
Returns Nothing
Description Reads the memory type and capacity from the serial FLASH device. Hi byte contains type, and low
byte contains capacity. Refer to the device data sheet for further information.
Description Display an image from the SPI FLASH at screen location specified by x, y(top left corner). The image is
displayed from a file at the current FLASH position set by spiflash_SetAdd().
Returns Pointer
Returns a pointer to the memory allocation where the function has been loaded from
Pointer
file which can be then used as a function call.
Description Load a function or program from the FLASH memory device on the specified SPI port and enable pin
at the address set by spiflash_SetAdd(), or incremented by subsequent reads or writes 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.
res := mem_Free(popupWindow);
if(!res) goto FreeFunctionFailed; //should never happen if memory not
//corrupted
Returns Status
Returns a handle (pointer to the memory allocation) to the image control list that
Status has been created.
Returns NULL if function fails.
Description Reads a control file to create an image list from the FLASH memory device on the specified SPI port
and enable pin. The source is the address set by spiflash_SetAdd(), or incremented by subsequent
reads or writes. The ".dat" file is first and is immediately followed by a ^Z and then the ".gci' file.
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:
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(MyImageControlHandle);
#constant OK 1
#constant FAIL 0
//-------------------------------------------------------------------
// 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, FONT_2);
txt_Set(TEXT_OPACITY, OPAQUE);
if (!file_Mount())
print("File error ", file_Error());
while(!CheckTouchExit());
// just hang if we didnt get the image list
r := FAIL;
goto quit;
endif
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
pause(3000);
gfx_Cls();
repeat
n := 0;
n++;
wend
until(exit);
quit:
return r;
endfunc
//===================================================================
Returns value
value If there are no errors, returns number of blocks to play (1 to 32767)
If errors occurred, the following is returned
-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
Description Play a wave file from the FLASH memory device on the specified SPI port and enable pin. The source
is the address set by spiflash_SetAdd(), or incremented by subsequent reads or writes. Opens 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.
This function automatically grabs a chunk of memory for a wave buffer. The minimum memory
requirement is the wave buffer size of 1024. The size of the wave buffer allocation can be increased
by the snd_BufSize function.
Note: The memory is only required during the duration of play, and is automatically released while
not in use.
Example print("\nding.wav\n");
for(n:=0; n<45; n++)
pitch := NOTES[n];
print([UDEC] pitch,"\r");
snd_Pitch(pitch);
spiflash_PlayWAV(SPI1, PA0);
while(snd_Playing());
//pause(500);
next
Returns Nothing
Description This function writes the byte specified by "char" to the FLASH memory device on the specified SPI
port and enable pin, at the position spiflash_SetAdd(), or incremented by subsequent reads or writes
and advances the pointer appropriately (incremented by 1).
Returns count
count Returns the number of characters written (excluding the null terminator).
Description This function writes an ASCIIZ (null terminated) string from a buffer specified by "*source" to the
FLASH memory device on the specified SPI port and enable pin, at the position set by
spiflash_SetAdd(), or incremented by subsequent reads or writes and advances the pointer
appropriately.
Returns Nothing
Description This function writes word sized (2 bytes) data specified by "word" to the FLASH memory device on
the specified SPI port and enable pin, at the position indicated by set by spiflash_SetAdd(), or
incremented by subsequent reads or writesand advances the pointer appropriately (incremented by
2).
Returns count
count Returns the number of characters read.
Description Reads the number of bytes specified by "size" from the FLASH memory device on the specified SPI
port and enable pin into a destination memory buffer. The source is the address set by
spiflash_SetAdd(), or incremented by subsequent reads or writes.
Returns Value
Value Returns the value from main in the called program.
Description 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.
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 spiflash_Exec and spiflash_LoadFunction for functions that
can pass by reference.
spiflash_SetAdd should have previously been called to identify the address of the program to be
called.
Returns nothing
Description Set media memory internal Address pointer for to SPI FLASH memory.
This example sets the SPI FLASH address to byte 513 for subsequent operations.
Returns Signature
Signature Returns the Electronic Signature of the SPI FLASH device.
Description Returns the Electronic Signature of the SPI FLASH device. Only the low order byte is valid, the upper
byte is ignored.
Returns Status
Status Returns TRUE if the Source address is valid
Description Writes the number of bytes specified by "size" from the source buffer into the FLASH memory device
on the specified SPI port and enable pin.
Returns Nothing
Description Erase the 32KB flash block including the currently set address
Returns Nothing
Description Erase the 4KB flash sector including the currently set address
Spi# The SPI interface to which the Flash memory chip is located SPI0 for the uSD port, or
SPI1, SPI2 or SPI3.
Enablepin The enable, or CS pin for the Flash memory chip PA0-PA15, or USD_ENABLE for the
uSD's enable pin.
Description Reads a byte from the FLASH memory device on the specified SPI port and enable pin and returns it.
The enable pin is lowered at the start of the operation and raised at the end unless the flag is set to
SPIFLASH_HOLDCS is set, in which case the pin is left low.
Description Writes the specified byte to the FLASH memory device on the specified SPI port and enable pin. The
enable pin is lowered at the start of the operation and raised at the end unless the reg/value has
SPIFLASH_HOLDCS orred onto it, in which case the pin is left low.
Returns Nothing
Description Sets the address size to be used to access the FLASH memory device on the specified SPI port and
enable pin. The size should be set using the correct command for the SPI FLASH memory device you
are using.Then this function should be called to enable that addresing mode to be used.
Returns a handle (pointer to the memory allocation) to the image control list that has been created.
Returns
Returns NULL if function fails.
Description spiflash_SetAdd() should have previously been called to set the GCIF start location.
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.
Returns CRC
CRC Returns the generated 16 bit CRC.
Description 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
Returns CRC
CRC Returns the generated CCITT CRC.
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.
Returns CRC
CRC Returns the generated 8 bit checksum CRC.
Description 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
Returns CRC
CRC Returns the generated MODBUS CRC.
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
ADDRESS
LABEL USAGE
DEC HEX
MEDIA_SECTOR_HI 93 0x5D micro-SD sector address HI
MEDIA_SECTOR_COUNT 94 0x5E micro-SD number of bytes remaining in sector
TEXT_XPOS 95 0x5F text current x pixel position
TEXT_YPOS 96 0x60 text current y pixel position
TEXT_MARGIN 97 0x61 text left pixel pos for carriage return
TXT_FONT_ID 98 0x62 font type, 0 = system font, else pointer to user font
TXT_FONT_MAX 99 0x63 max number of chars in font
TXT_FONT_OFFSET 100 0x64 starting offset (normally 0x20)
TXT_FONT_WIDTH 101 0x65 current font width
TXT_FONT_HEIGHT 102 0x66 Current font height
GFX_TOUCH_REGION_X1 103 0x67 touch capture region
GFX_TOUCH_REGION_Y 104 0x68 touch capture region
GFX_TOUCH_REGION_X2 105 0x69 touch capture region
GFX_TOUCH_REGION_Y2 106 0x6A touch capture region
GFX_CLIP_LEFT_VAL 107 0x6B left clipping point (set with gfx_ClipWindow(...)
GFX_CLIP_TOP_VAL 108 0x6C top clipping point (set with gfx_ClipWindow(...)
GFX_CLIP_RIGHT_VAL 109 0x6D right clipping point (set with gfx_ClipWindow(...)
GFX_CLIP_BOTTOM_VAL 110 0x6E bottom clipping point (set with gfx_ClipWindow(...)
GFX_CLIP_LEFT 111 0x6F current clip value (reads full size if clipping turned off)
GFX_CLIP_TOP 112 0x70 current clip value (reads full size if clipping turned off)
GFX_CLIP_RIGHT 113 0x71 current clip value (reads full size if clipping turned off)
GFX_CLIP_BOTTOM 114 0x72 current clip value (reads full size if clipping turned off)
GRAM_PIXEL_COUNT_LO 115 0x73 LO word of count of pixels in the set GRAM area
GRAM_PIXEL_COUNT_HI 116 0x74 HI word of count of pixels in the set GRAM area
TOUCH_RAW_X 117 0x75 12 bit raw A2D X value from touch screen
TOUCH_RAW_Y 118 0x76 12 bit raw A2D Y value from touch screen
GFX_LAST_CHAR_WIDTH 119 0x77 calculated char width from last call to charWidth function
GFX_LAST_CHAR_HEIGHT 120 0x78 calculated height from last call to charHeight function
GFX_LAST_STR_WIDTH 121 0x79 calculated width from last call to strWidth function
GFX_LAST_STR_HEIGHT 122 0x7A calculated height from last call to strHeight function
PIN_COUNTER_PA4 123 0x7B pin counter for PA4
PIN_COUNTER_PA5 124 0x7C pin counter for PA5
PIN_COUNTER_PA6 125 0x7D pin counter for PA6
PIN_COUNTER_PA7 126 0x7E pin counter for PA7
PIN_COUNTER_PA8 127 0x7F pin counter for PA8
PIN_COUNTER_PA9 128 0x80 pin counter for PA9
PIN_EVENT_PA4 129 0x81 pin counter rollover event for PA4
PIN_EVENT_PA5 130 0x82 pin counter rollover event for PA5
PIN_EVENT_PA6 131 0x83 pin counter rollover event for PA6
PIN_EVENT_PA7 132 0x84 pin counter rollover event for PA7
PIN_EVENT_PA8 133 0x85 pin counter rollover event for PA8
PIN_EVENT_PA9 134 0x86 pin counter rollover event for PA9
QEN1_COUNTER_LO 135 0x87 quadrature encoder #1 counter LO
QEN1_COUNTER_HI 136 0x88 quadrature encoder #1 counter HI
QEN1_DELTA 137 0x89 quadrature encoder #1 delta count
QEN2_COUNTER_LO 138 0x8A quadrature encoder #2 counter LO
QEN2_COUNTER_HI 139 0x8B quadrature encoder #2 counter HI
QEN2_DELTA 140 0x8C quadrature encoder #2 delta count
FALSE_REASON 141 0x8D explanation 'false' results, currently only for flash_ functions
NOTE: These registers are accessible with peekW and pokeW functions.
4D Programming Cable
5.3. Memory Cards - FAT16 Format occurring. Furthermore, manufacturers may choose
to implement read disturb protection on a specific
The Diablo16 Processor uses off the shelf standard part of the flash memory only, such that the beginning
SDHC/SD/micro-SD memory cards with up to 4GB part of the memory might not be protected. The
capacity usable with FAT16 formatting. For any FAT RMPET utility in Workshop4 is designed to create the
file related operations, before the memory card can first partition at an offset from the start of the
be used it must first be microSD card to account for this situation. It is
formatted with FAT16 therefore recommended to always partition and
option. The formatting format an industrial microSD card using the RMPET
of the card can be done utility before using it with 4D Systems processors.
on any PC system with a
card reader. Select the
appropriate drive and choose the FAT16 (or just FAT in
some systems) option when formatting. The card is
now ready to be used in the Diablo16 based
application.
Workshop4 PRO adds a professional set of features to Workshop4 PRO adds a professional set of features to
the ViSi environment, called Smart Widgets. These the Visi-Genie environment called Genie-Magic. The
smart widgets allow Users to create custom gauges, added features allow the user to add in 4DGL scripts,
sliders, buttons and more, rather than relying on the which can be activated from the display itself, from an
built-in ones. This provides an extra level of interfacing Host, or from an external sensor or device.
customisation available for intelligent products. These PRO set of features of Genie-Magic allow the
User to create an immensely powerful GUI system
with a fraction of the effort required by other systems.
6.3. ViSi Genie Environment
Along with Genie-Magic, ViSi-Genie also benefits from
ViSi Genie is a breakthrough in the way 4D Labs’ Smart widgets, as described in the previous ViSi
graphic processors are programmed. It is an Environment section.
environment like no other, a code-less programming
environment that provides the user with a rapid visual
experience, enabling a simple GUI application to be
‘written’ from scratch in literally seconds.
7. Revision History
Revision History
Revision Revision Content Revision Date
Added Mode PWM_BINARY and usage notes. Added notes to spiflash initialization. Added
1.5 disp_BlitPixelsFromCOMx. Added special baud rates to com_SetBaud(). Added 25/02/2014
spix_ReadBlock and spix_Writeblock. All these additions apply to PmmC 1.1 and later.
1.6 Documented v1.1 PmmC’s changes to files opened in append mode. Added new I2C options. 21/03/2014
8. Legal Notice
Proprietary Information
The information contained in this document is the property of 4D Labs Semiconductors and may be the subject of
patents pending or granted, and must not be copied or disclosed without prior written permission.
4D Labs Semiconductors endeavours to ensure that the information in this document is correct and fairly stated but
does not accept liability for any error or omission. The development of 4D Labs Semiconductors products and services
is continuous and published information may not be up to date. It is important to check the current position with 4D
Labs Semiconductors. 4D Labs Semiconductors reserves the right to modify, update or makes changes to
Specifications or written material without prior notice at any time.
All trademarks belong to their respective owners and are recognised and acknowledged.
4D Labs Semiconductors makes no warranty, either expressed or implied with respect to any product, and specifically
disclaims all other warranties, including, without limitation, warranties for merchantability, non-infringement and
fitness for any particular purpose.
Information contained in this publication regarding device applications and the like is provided only for your
convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with
your specifications.
Images and graphics used throughout this document are for illustrative purposes only. All images and graphics used
are possible to be displayed on the 4D Labs Semiconductors range of products, however the quality may vary.
In no event shall 4D Labs Semiconductors be liable to the buyer or to any third party for any indirect, incidental,
special, consequential, punitive or exemplary damages (including without limitation lost profits, lost savings, or loss
of business opportunity) arising out of or relating to any product or service provided or to be provided by 4D Labs
Semiconductors, or the use or inability to use the same, even if 4D Labs Semiconductors has been advised of the
possibility of such damages.
4D Labs Semiconductors products are not fault tolerant nor designed, manufactured or intended for use or resale as
on line control equipment in hazardous environments requiring fail – safe performance, such as in the operation of
nuclear facilities, aircraft navigation or communication systems, air traffic control, direct life support machines or
weapons systems in which the failure of the product could lead directly to death, personal injury or severe physical
or environmental damage (‘High Risk Activities’). 4D Labs Semiconductors and its suppliers specifically disclaim any
expressed or implied warranty of fitness for High Risk Activities.
Use of 4D Labs Semiconductors’ products and devices in 'High Risk Activities' and in any other application is entirely
at the buyer’s risk, and the buyer agrees to defend, indemnify and hold harmless 4D Labs Semiconductors from any
and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise,
under any 4D Labs Semiconductors intellectual property rights.
9. Contact Information
For Technical Support: www.4dlabs.com.au/support
For Sales Support: sales@4dlabs.com.au
Website: www.4dlabs.com.au