Skip to main content

Standard Library


These standard library functions are built in natively into the firmware and are available on all systems. You will likely not use these directly, but use the simpler wrapper methods provided by the individual modules.

tip

These are particularly useful for using DUELink Microcomputers or for making custom modules.


caution

Unless otherwise is stated, all Standard Libraries that calls for array require a byte array and not a float array. Use b1 for example instead of a1.

Special Pins

Some functions only work on pins with specific features.

  • Analog capable pins: P1, P2, P3, P4, P5, P6, P7, P8, P9, P17
  • Interrupt capable pins: P1, P2, P3, P4, P5, P6, P7, P12
  • PWM capable pins: P1, P2, P3, P4, P5, P6, P7, P8, P11
tip

PWM pins share timers. Changing the frequency on one will effect the other. Changing duty-cycle is okay however!

  • P1, P2
  • P3
  • P4, P11
  • P5, P6, P7, P8

Print

Print to output.

FunctionDescription
Print("text" or variable)Print the value of its argument.
PrintLn("text" or variable)Print the value of its argument with line breaks.

Print() accepts multiple argument, separated by commas, Print("Value is: ", _v)

tip

Print is invoked automatically when a function returns a value that is not consumed. Running DRead(1, 1) in immediate mode will show 0 or 1.

Samples
Print("DUELink")
PrintLn(" is awesome!")
_x=100
PrintLn(_X)
Print("_X = ", _X)

Timing

FunctionDescription
Wait(duration)Wait for duration milliseconds.
TickMs()Read system ticks in milliseconds.
TickUs()Read system ticks in microseconds.
Samples
 _T = TickMs()
PrintLn("Current tick = ",_T)
Wait(5000)
_N = TickMs()
PrintLn("New tick = ",_N)
PrintLn("Delta = ",_N - _T)

Pin Control

Status LED

Control the on-board STAT LED, found on every single DUELink module.

FunctionDescription
StatLed(high, low, count)Blink the status (STAT) LED with high duration on in milliseconds and low duration in milliseconds. Repeat count, use 0 to repeat forever.

The status LED is automatically controlled by the engine by default, as explained on the Specs page. Calling StatLed() will take control over the LED. It is possible to release LED back to the engine by calling StatLed(0,0,0).

Samples
# Blink the STAT LED on for 1000 milliseconds, off for 1000 milliseconds, 10 times. 
StatLed(1000, 1000, 10)
# Wait for 5 seconds
Wait(5000)
# Release the Status LED back to the system
StatLed(0, 0, 0)

Digital

Access digital pins.

FunctionDescription
DRead(pin, pull)Returns the digital state of pin. Enable pull (0 none, 1 up, 2 down).
DWrite(pin, state)Sets pin to state: 1 = high or 0 = low.
Samples
# Read the current level of pin 1, with pull-down resistor enabled
_P = DRead(1,2)
# Set pin 2 to high (active) state
DWrite(2,1)

Analog

Access pins in an analog format.

FunctionDescription
ARead(pin)Read the analog level on pin (0 to 4095).
VRead(pin)Read calibrated voltage level on pin.
AWrite(pin, power)Sets the power level on pin using PWM. Power level is 0 to 1, 0.33 is 33% for example.

VRead() and ARead() only works with analog capable pins, see Special Pins.

AWrite() only works on PWM pins, see Special Pins.

tip

AWrite() changes the internal timer frequency to 1Khz, see Special Pins.

Samples
# Read the voltage level at pin 3
_V = VRead(3)
# Read the analog input on pin 2
_A = Aread(2)
# Set power level (duty-cycle) of pin 4 to 33%
AWrite(4, 0.33)

Beep

Generate tones. This is a blocking function that works on all pins.

FunctionDescription
Beep(pin, frequency, duration)Generate a beep on pin with frequency for duration in milliseconds.
Samples
# Generate a frequency of 1KHz on pin 1 for 200ms
Beep(1, 1000, 200)

Melody

Generate tones. This is a non-blocking function that works on PWM pins.

MelodyP() requires a float array, use a1 for example. Float arrays must be initialized with {} brackets.

FunctionDescription
MelodyP(pin, {notes})A non-blocking call to play a melody in the background on pin using the frequencies and delays found in {notes} float array.
MelodyS(pin)Stop a melody on pin.
Samples
Dim a1[]={500, 50, # 500Hz for 50ms
1000, 100} # 1000Hz for 100ms
MelodyP(3, a1)
Wait(2000)
MelodyS(3)

Button

Use interrupts to keep track of pins. Only available on interrupt capable pins, see Special Pins above!

FunctionDescription
BtnEn(p,l)Enable button scanning feature on p pin with l as pressed state (0 is low when pressed, 1 is high when pressed).
BtnUp(p)Returns 1 if p pin transitioned to unpressed state.
BtnDown(p)Returns 1 if p pin transitioned to a pressed state.
BtnRead(p)Returns 1 if button on p is currently pressed.
Samples
# Enable button on pin 1 with a low for pressed-state.
BtnEn(1, 1)
# Read the current button state, pressed or unpressed.
_B = BtnRead(1)

Frequency

Sets a frequency (PWM) parameters to a pin. Only works on pins that support PWM.

tip

This changes the timer frequency, see Special Pins.

FunctionDescription
Freq(pin, frequency, duration, dutycycle)Sets PWM pin to frequency for duration in milliseconds at dutycycle where 1 is 100%, 0.2 is 20%...etc.
Samples
# Sweep though frequencies on pin 3
for _x in range(800,8000,50)
Freq(3, _x, 100, 0.5)
Wait(100)
next

Touch

Read capacitive touch by charging a pin and then reading the discharge time in microseconds.

FunctionDescription
Touch(pin, charge_t, charge_s, timeout)Charges pin with charge state charge_s for charge time charge_t in milliseconds then read how long it takes for pin to discharge, returning value in microseconds. timeout is used in case the pin didn't change its state.
Samples
# Read cap-touch on pin 1 with 100ms charing at high state, with 1sec timeout
while 1
printLn(Touch(1, 100, 1, 1000))
Wait(1000)
wend

PulseIn

Reads a pulse on a pin and return time in microseconds.

FunctionDescription
PulseIn(pin, state, timeout)Read a pulse width on a pin where the pulse is level selected using state (high or low). If no valid state detected, returns 0. This is a blocking function waiting for the pulse, or returns after timeout milliseconds.
Samples
# Detect low width on pin 3
println(PulseIn(3,0,1000))

Digital Control

Distance

Read distance from ultrasonic distance sensors.

FunctionDescription
Dist(trig, echo)Returns distance in centimeters from ultrasonic distance sensor connected to trig and echo pins.
Samples
# Measure ultrasonic distance with trig on pin 2 and echo on pin 1
_D = _Dist(2, 1)

Servo Motors

Control servo motors.

tip

This changes the timer frequency to 50Hz, see Special Pins.

FunctionDescription
ServoSt(pin, degree)Position a servo on pin to degree: 0 to 180

ServoSt() only works with PWM pins, see Special Pins.

Samples
# Servo on pin 1 to 90 degrees
servost(1, 90)

I2C

Access the I2C bus.

FunctionDescription
I2cCfg(baudrate)baudrate: Sets the I2C clock speed in khz, typically 100K or 400K, and 1M in some cases.
I2cWr(address, [arrayWrite], [arrayRead])address: I2C slave address (7 bits) - arrayWrite: array to send, arrayRead: array to read.

Pins used for I2C are 15-SCL and 16-SDA.

Samples
# Write 2 bytes to 0x3C and do not read anything back
i2ccfg(100) # set clock 100KHz
b1[0] = 1
b1[1] = 2
i2cwr(0x3C,b1,[])

SPI

Access the SPI bus.

FunctionDescription
SpiCfg(mode, frequency)Configure SPI with mode: 0 to 3 and frequency in KHz, ranging 200KHz to 20MHz. If LSB is needed, set mode bit 7 to 1 mode=mode|0x80 .
SpiWr(byte)Write a byte then return the received byte.
SpiWrs([data_w], [data_r])Write an byte array of data_w , also return an byte array of data_r.
tip

The system defaults to SpiCfg(0,8000), means SPI mode 0, 8MHz, and first bit is MSB.

Pins used for SPI are 12-SCK, 13-MISO, 14-MOSI. Use any GPIO for manual use of CS.

Samples
spicfg(0,8000)
# Write/Read (exchange) a byte
_R = SpiWr(0x55)
# Write B1 array and read back B2
Dim B1[2] = [1,2]
Dim B2[2]
SpiWrs(B1,B2)

Serial (UART)

Read and write serial data.

FunctionDescription
SerCfg(baud, rxsize)Start serial port with baud and allocate a receive buffer of rxsize.
SerRd()Read a single byte from the receive buffer. Returns zero if it finds no data.
SerRds([data], timeout)Block the system till all data elements are filled. Terminate and return if no data received in timeout milliseconds. Returns how many bytes it read successfully.
SerWr(byte)Write a single byte to the serial port.
SerWrs([data])Write an array of data.
SerB2R()Returns how many bytes are available in the receive buffer.
SerDisc()Discard the receive buffer.

The pins used for UART are 1-RX and 2-TX. The DBG pin is an output indicating the sample point, used by us internally.

Serial is handled by software with special internal features. There is also basic hardware UART option available when UART Uplink is not needed, for example on boards with only USB Uplink, such as DueDuino. To activate the hardware UART, use a negative baud in SerCfg(), for example SerCfg(-115200,100). Pins used for hardware UART are 21-TX and 22-RX. We do not support using both hardware and software UARTs simultaneously.

Samples
SerCfg(9600, 1024)

# If there is data, read a byte and write it back
if SerB2R() > 0
_B = SerRd()
SerWr(_B)
end

DMX

Read and write from DMX512 devices. Must call SerCfg(250000, 513) before using these functions. The pins used for DMX are same as UART.

FunctionDescription
DmxW([channels])Write channel byte array.
DmxU()Enable receive to update internal buffer with incoming channels.
DmxRdy()Returns 1 when there is a frame that was requested by DmxU().
DmxR(channel)Returns the value of a specific channel.
tip

This feature only support DMX frames with Start Code zero.

Samples
# Enable DMX update on UART pins
DmxU()

# wait until ready
while DmxRdy() = 0
wait(200)
wend

# Read channel 3
_D = DmxR(3)


Infrared

Receive and decode signals from Infrared remotes. Generate tones. Tx pin must be a PWM capable pin. Rx pin must be an interrupt capable pin.

FunctionDescription
IrEn(t,r)Enable IR transmitter on t pin and scanner on r pin. Both pins are optional, use -1 for the pin not being used.
IrRead()Returns previously received key press value. Returns -1 if no key press was received.
IrWrite(data)Write data. This is a blocking call.
Samples
# Enable Ir transmit feature on pin 3, no receiver 
IrEn(3, -1)
# Send 0x55
IrWrite(0x55)

Temperature

Read temperature from a specific sensor

FunctionDescription
Temp(pin, type)Read temperature sensor with type connected to pin. Returns temperature in Celsius.
IDType
0Internal CPU temperature (pin is ignored)
1DHT11
2DHT12
3DHT21
4DHT22
Samples
# Read DH22 sensor on pin 5
Temp(5,4)

Humidity

Read humidity from a specific sensor.

FunctionDescription
Humid(pin, type)Read a humidity sensor type connected to pin.
IDType
0reserved
1DHT11
2DHT12
3DHT21
4DHT22
Samples
# Read DH22 sensor on pin 5
duelink.Humid(5, 4)

System Info

Read info about the system.

FunctionDescription
Info(type)Returns the a specific type of info!
Type IDReturned value
0Product type
1Firmware version
2Interface (0: None, 1: I2C, 2: USB, 3: UART)
3Downlink Mode (see DLMode())
Samples
# Read the firmware version
_v = Info(1)

Graphics

DUELink firmware include a flexible graphics facilities, detailed on the Graphics Engine page.


File System

DUELink firmware include a complete file system facilities, detailed on the File System page.


Scheduler

See Scheduler for details.

FunctionDescription
SStart("func", timeout, count)Schedule func to run at every timeout (in milliseconds) for count times, or -1 to run forever.
SStat("func")func: Returns how many times the schedule will still need to run for, 0 is complete and -1 ids forever.
SAbort("func")func: Abort func scheduler.
Samples
_S = 1

fn Blink()
_S = ! _S
DWrite(1,_S)
fend

# Start the scheduler to run Blink 20 times once every 100ms.
SStart("Blink",100,20)

# Do not terminate
while 1
# Do something!
wend


Interrupts

See Interrupts for details.

FunctionDescription
IStart("func", pin, trigger, pull)Enable interrupt on pin to trigger func. trigger is: 0 - falling, 1 - rising, 2 - rising and falling. Enable pull: 0 - pull down, 1 - pull up, 2 - no pull.
Istatled("func")Returns status of interrupt on func: 0- no interrupt, 1- active interrupt.
IAbort("func")Abort interrupt for func.
Samples
fn Changed()
PrintLn("Pin was changed!")
fend

# Run "Changed" function when pin 1 goes low
IStart("Changed", 1, 0, 1)


# Do not terminate
while 1
# Do something!
wend


FunctionDescription
DLMode(mode)Sets Downlink mode (0:Null, 1: Interface, 2: Host, 3: UART).
DLI2cWr(address, [arrayWrite], [arrayRead])address: I2C slave address (7 bits) - arrayWrite: array to send, arrayRead: array to read. This only works with DLMode(4).
Cmd("command")Sends a script command Downlink, only available in DLMode(2) mode, Host mode. You can only to read a float from a function or a variable: _W = Cmd("GetW()") or _W = Cmd("_W"). Setting a remote value is done using cmd(fmt("_x=",_x)).
CmdTmot(t)Sets t timeout for Cmd() in milliseconds, default 1000ms.

More info are found on the Downlink interface and Daisylink pages.

tip

Use Info() to read the current DLMode() state.

Samples
# Switch Downlink to I2C mode
DLMode(4)
Dim B1[]=[0x11,0x22]
# Write 2 bytes to 0x44 and read nothing
DLI2CWr(0x44,B1,[])

Device Addressing

These functions are needed for helping with Daisylink devices chained through Downlink connections.

FunctionDescription
Sel(add, add, add ...)Select a devices at add in the chain.
GetAdd()Returns the selected device(s) address.
SetAdd(add)add Sets the device's address. This command has chain reaction where each device sets the next one. ** Internal function, do not use**

The Sel(add) command accepts multiple addresses. Sel(3,7) will activate the third and and seventh modules in Daisylink. Any command issue from that point forward are executed by both modules. Zero is broadcast address, where Sel(0) will activate all modules. Use GetAdd() to detect what modules are currently active.

Device addressing controls modules on a Daisylink, not a device itself. For that, Sel() can only be issued by the host. Of course, the host can be a third-party board or a DUELink module in host mode.

Samples
# Select device 2
Sel(2)
# Blink the LED on selected device
StatLed(200,200,10)

Math

FunctionDescription
Rnd(max)Returns a random number with max value.
Cos(rad)Returns cosine of rad.
Sin(rad)Returns sine of rad.
Tan(rad)Returns tangent rad.
Sqrt(number)Returns square root of number.
Abs(number)Returns absolute value of a number.
Ceil(number)Returns ceiling of a number.
Floor(number)Floor a number.
Round(number)Round a number.
Trunc(number)Returns a truncated value number.
IsNaN(number)Returns 1 number is a valid value.
Samples
# Read a random number between 0 and 10
_R = Rnd(10)

Converters

FunctionDescription
SprintF([buffer], format)Works like sprintf() in the C-language.
Fmt(...)Returns formatted string for internal functions, takes arguments just like Print().
Hex(num)Returns the number in hex.
Chr(num)Returns the ascii char of a number.
Scale(value, fromLow, fromHigh, toLow, toHigh)Returns a scaled number from value.
Memcpy([dst], offset_dst, [src], offset_src, count)Used to copy a block of memory from one location to another. [dst] and [src] must be same array type.
Samples
_H = 0x55
# Print the value in its hex representation
PrintLn(Hex(_H))

Asynchronous IO

Enable Asynchronous IO. Detailed on the Engine main page.

FunctionDescription
AsIo(enable)enable: 1 = Enable, 0 = Disable
Samples
AsIo(1) # Enable Asynchronous IO

# The engine will respond even when looping
while 1
# ...do something!
wend

System Reset

Reset or clear the system.

FunctionDescription
Reset(mode)Reset the system with mode.
modeDescription
0System Reset (just like pressing reset button).
1Wipe out the entire chip (factory reset!). This command must be executed twice for it to take effect.

It is important to keep device addressing under consideration. To do so, Reset(0) will automatically reset all devices, regardless of what device was selected using Sel(). However, Reset(1) will only erase the selected device. We recommend Reset(1):Reset(1) on a singular connected device, or on the first connected device in a daisylink. If you really need, Sel(0):Reset(1):Reset(1) will wipe out every single device in a daisylink!

Samples
# Reset All devices
Sel(0)
Reset(0)

Low Power

FunctionDescription
LowPwr(m, p)Put the module in m sleep mode, with p pin function.
Sleep ModeWake up pinDescription
0Pins 1 or 3System shutdown, including the internal RTC. A low-to-high on p pins 1 & 3 will reset the module.
1Any interrupt-capable pinSystem shut down, but keep the internal RTC running. A low-to-high on p pin or an RTC alarm will reset the module.

Setting wake up pin to 0 will disable the GPIO wake up feature.

tip

A module will exit any low power mode after system reset or power cycle.

Samples
# Go to sleep and reset when pin 3 changes from low to high.
LowPwr(0, 2)

One-Time Programmable

Write and read from a special memory type that can be written only once and can never be erased or changed! The size of this special memory region is 512 bytes (64 8-Byte blocks).

FunctionDescription
OtpR(addr)Read a single byte from addr.
OtpW(addr, [data])*STOP Irreversible Action! Write data bytes to addr, where addr must be and data size must be multiple of 8. Returns 1 on success, 0 if failed because an 8 byte block was previously written to.
tip

Use byte arrays. If float array is used then only the first byte of each element is written.

Samples
# Read a value from OTP address 12
OtpR(12)

Coprocessor

A few modules, such as USB Host include a coprocessor. See Coprocessor for more details.


RTC

Access clock and date in the internal Real Time Clock (RTC).

FunctionDescription
RtcW([timedate])Sets (write) the desired time and date from timedate array in the RTC.
RtcR([timedate])Read the current time and date into array. If 0 is used instead of array then the rtc value is printed as HH:MM:SS - DD MMM YYYY.

The array used for all RTC functions is 6 bytes, organized as: [Second,minute,hour,day,mon,year]. Values must be proper for their field. For example, there is no 70 seconds in time. Also, year is starting from the year 2000. For year 2025, just use 25. Hours are military 24 hours.

tip

Power loss will cause the internal RTC to lose its value. This is where RTC Module comes in handy.

Samples
# Sets the current time to 18:10:00 27 Feb 2025
Dim b1[6]= [0,10,18,27,2,25]
RtcW(b1)

Dim b2[6]
# Read the time into array
RtcR(b2)
# Show (print) the current time
RtcR(0)

Streams

Streams allows a Supported Hardware to "stream" data out of or in to a device. See Stream page.


Misc

FunctionDescription
Version()Returns firmware version and device ID in this format: GHI Electronics DUELink v01.03:BB01.
Echo(enable)Sets local echo functionality(1: Enable, 0: Disable). This is disabled by default.
Len([array])Returns the length of array.
ReadVCC()Returns current system voltage.
Exit()Terminate and exit the script.
Samples
# Read the system's voltage
_V = ReadVCC()

Library Specific

These are library specific functions that are added to help with controlling modules and scripts. These functions do not exist on the script side.

FunctionDescription
float duelink.Engine.ExecuteCommand("cmd")Writes a command to a module and returns a float.
string duelink.Engine.ExecuteCommandRaw("cmd")Writes a command to a module and returns a raw string.

Also, there are other functions to help with accessing the module's internal arrays, see stream.

Samples

Library only functionality.