Espruino Software Reference

Version 1v78

Contents

Globals

Array

ArrayBuffer

ArrayBufferView

Boolean

CC3000

Date

E

Error

Ethernet

File

Float32Array

Float64Array

Function

Graphics

HASH

Hardware

I2C

Int16Array

Int32Array

Int8Array

InternalError

JSON

Math

Modules

NetworkJS

Nucleo

Number

Object

OneWire

Pin

Pipe

SPI

Serial

Server

Socket

String

SyntaxError

TypeError

Uint16Array

Uint32Array

Uint8Array

Uint8ClampedArray

WIZnet

WLAN

Waveform

console

fs

hashlib

http

httpCRq

httpCRs

httpSRq

httpSRs

httpSrv

net

process

tv

url

Detail

Global Functions

(top)

Methods and Fields

variable HIGH

(top)

Call type:

variable HIGH

Parameters

No parameters

Returns

Logic 1 for Arduino compatibility - this is the same as just typing 1

variable Infinity

(top)

Call type:

variable Infinity

Parameters

No parameters

Returns

Positive Infinity (1/0)

variable LOW

(top)

Call type:

variable LOW

Parameters

No parameters

Returns

Logic 0 for Arduino compatibility - this is the same as just typing 0

variable NaN

(top)

Call type:

variable NaN

Parameters

No parameters

Returns

Not a Number

function analogRead

(top)

Call type:

function analogRead(pin)

Description

Get the analog value of the given pin

This is different to Arduino which only returns an integer between 0 and 1023

However only pins connected to an ADC will work (see the datasheet)

Parameters

pin The pin to use
You can find out which pins to use by looking at your board's reference page and searching for pins with the ADC markers.

Returns

The analog Value of the Pin between 0 and 1

function analogWrite

(top)

Call type:

function analogWrite(pin, value, options)

Description

Set the analog Value of a pin. It will be output using PWM

Parameters

pin The pin to use
You can find out which pins to use by looking at your board's reference page and searching for pins with the PWM or DAC markers.

value A value between 0 and 1

options An object containing options.
Currently only freq (pulse frequency in Hz) is available: analogWrite(A0,0.5,{ freq : 10 });
Note that specifying a frequency will force PWM output, even if the pin has a DAC

Returns

No return value (undefined)

variable arguments

(top)

Call type:

variable arguments

Description

A variable containing the arguments given to the function

Parameters

No parameters

Returns

An array containing all the arguments given to the function

function atob

(top)

Call type:

function atob(binaryData)

Description

Convert the supplied base64 string into a base64 string

Note: This is only available in some devices: not devices with low flash memory

Parameters

binaryData A string of base64 data to decode

Returns

A string containing the decoded data

function btoa

(top)

Call type:

function btoa(binaryData)

Description

Convert the supplied string (or array) into a base64 string

Note: This is only available in some devices: not devices with low flash memory

Parameters

binaryData A string of data to encode

Returns

A base64 encoded string

function changeInterval

(top)

Call type:

function changeInterval(id, time)

Description

Change the Interval on a callback created with setInterval, for example:

var id = setInterval(function () { print('foo'); }, 1000); // every second

changeInterval(id, 1500); // now runs every 1.5 seconds

This takes effect the next time the callback is called (so it is not immediate).

Parameters

id The id returned by a previous call to setInterval

time The new time period in ms

Returns

No return value (undefined)

function clearInterval

(top)

Call type:

function clearInterval(id)

Description

Clear the Interval that was created with setInterval, for example:

var id = setInterval(function () { print('foo'); }, 1000);

clearInterval(id);

If no argument is supplied, all timers and intervals are stopped

Parameters

id The id returned by a previous call to setInterval

Returns

No return value (undefined)

function clearTimeout

(top)

Call type:

function clearTimeout(id)

Description

Clear the Timeout that was created with setTimeout, for example:

var id = setTimeout(function () { print('foo'); }, 1000);

clearTimeout(id);

If no argument is supplied, all timers and intervals are stopped

Parameters

id The id returned by a previous call to setTimeout

Returns

No return value (undefined)

function clearWatch

(top)

Call type:

function clearWatch(id)

Description

Clear the Watch that was created with setWatch. If no parameter is supplied, all watches will be removed.

Parameters

id The id returned by a previous call to setWatch

Returns

No return value (undefined)

function digitalPulse

(top)

Call type:

function digitalPulse(pin, value, time)

Description

Pulse the pin with the value for the given time in milliseconds. It uses a hardware timer to produce accurate pulses, and returns immediately (before the pulse has finished). Use digitalPulse(A0,1,0) to wait until a previous pulse has finished.

eg. digitalPulse(A0,1,5); pulses A0 high for 5ms. digitalPulse(A0,1,[5,2,4]); pulses A0 high for 5ms, low for 2ms, and high for 4ms

digitalPulse is for SHORT pulses that need to be very accurate. If you're doing anything over a few milliseconds, use setTimeout instead.

Parameters

pin The pin to use

value Whether to pulse high (true) or low (false)

time A time in milliseconds, or an array of times (in which case a square wave will be output starting with a pulse of 'value')

Returns

No return value (undefined)

function digitalRead

(top)

Call type:

function digitalRead(pin)

Description

Get the digital value of the given pin

If the pin argument is an array of pins (eg. [A2,A1,A0]) the value returned will be an number where the last array element is the least significant bit, for example if A0=A1=1 and A2=0, digitalRead([A2,A1,A0]) == 0b011

Parameters

pin The pin to use

Returns

The digital Value of the Pin

function digitalWrite

(top)

Call type:

function digitalWrite(pin, value)

Description

Set the digital value of the given pin

If pin argument is an array of pins (eg. [A2,A1,A0]) the value argument will be treated as an array of bits where the last array element is the least significant bit.

In this case, pin values are set last significant bit first (from the right-hand side of the array of pins). This means you can use the same pin multiple times, for example digitalWrite([A1,A1,A0,A0],0b0101) would pulse A0 followed by A1.

Parameters

pin The pin to use

value Whether to pulse high (true) or low (false)

Returns

No return value (undefined)

function dump

(top)

Call type:

function dump()

Description

Output current interpreter state in a text form such that it can be copied to a new device

Note: 'Internal' functions are currently not handled correctly. You will need to recreate these in the onInit function.

Parameters

No parameters

Returns

No return value (undefined)

function echo

(top)

Call type:

function echo(echoOn)

Description

Should TinyJS echo what you type back to you? true = yes (Default), false = no. When echo is off, the result of executing a command is not returned. Instead, you must use 'print' to send output.

Parameters

echoOn

Returns

No return value (undefined)

function edit

(top)

Call type:

function edit(funcName)

Description

Fill the console with the contents of the given function, so you can edit it.

NOTE: This is a convenience function - it will not edit 'inner functions'. For that, you must edit the 'outer function' and re-execute it.

Parameters

funcName The name of the function to edit (either a string or just the unquoted name)

Returns

No return value (undefined)

function eval

(top)

Call type:

function eval(code)

Description

Evaluate a string containing JavaScript code

Parameters

code

Returns

The result of evaluating the string

function getPinMode

(top)

Call type:

function getPinMode(pin)

Description

Return the current mode of the given pin. See pinMode

Parameters

pin The pin to check

Returns

The pin mode, as a string

function getSerial

(top)

Call type:

function getSerial()

Description

Get the serial number of this board

Parameters

No parameters

Returns

The board's serial number

function getTime

(top)

Call type:

function getTime()

Description

Return the current system time in Seconds (as a floating point number)

Parameters

No parameters

Returns

See description above

variable global

(top)

Call type:

variable global

Description

A reference to the global scope, where everything is defined.

Parameters

No parameters

Returns

The global scope

function isNaN

(top)

Call type:

function isNaN(x)

Description

Whether the x is NaN (Not a Number) or not

Parameters

x

Returns

True is the value is NaN, false if not.

function load

(top)

Call type:

function load()

Description

Load program memory out of flash

This command only executes when the Interpreter returns to the Idle state - for instance

a=1;load();a=2; will still leave 'a' as undefined (or what it was set to in the saved program).

Espruino will resume from where it was when you last typed save(). If you want code to be executed right after loading (for instance to initialise devices connected to Espruino), create a function called onInit (which will be automatically executed by Espruino).

Parameters

No parameters

Returns

No return value (undefined)

function parseFloat

(top)

Call type:

function parseFloat(string)

Description

Convert a string representing a number into an float

Parameters

string

Returns

The value of the string

function parseInt

(top)

Call type:

function parseInt(string, radix)

Description

Convert a string representing a number into an integer

Parameters

string

radix The Radix of the string (optional)

Returns

The integer value of the string (or NaN)

function peek16

(top)

Call type:

function peek16(addr, count)

Description

Read 16 bits of memory at the given location - DANGEROUS!

Parameters

addr The address in memory to read

count (optional) the number of items to read. If >1 a Uint16Array will be returned.

Returns

The value of memory at the given location

function peek32

(top)

Call type:

function peek32(addr, count)

Description

Read 32 bits of memory at the given location - DANGEROUS!

Parameters

addr The address in memory to read

count (optional) the number of items to read. If >1 a Uint32Array will be returned.

Returns

The value of memory at the given location

function peek8

(top)

Call type:

function peek8(addr, count)

Description

Read 8 bits of memory at the given location - DANGEROUS!

Parameters

addr The address in memory to read

count (optional) the number of items to read. If >1 a Uint8Array will be returned.

Returns

The value of memory at the given location

function pinMode

(top)

Call type:

function pinMode(pin, mode)

Description

Set the mode of the given pin - note that digitalRead/digitalWrite/etc set this automatically unless pinMode has been called first. If you want digitalRead/etc to set the pin mode automatically after you have called pinMode, simply call it again with no mode argument:

pinMode(pin)

Parameters

pin The pin to set pin mode for

mode The mode - a string that is either 'analog', 'input', 'input_pullup', 'input_pulldown', 'output', 'opendrain', 'af_output' or 'af_opendrain'. Do not include this argument if you want to revert to automatic pin mode setting.

Returns

No return value (undefined)

function poke16

(top)

Call type:

function poke16(addr, value)

Description

Write 16 bits of memory at the given location - VERY DANGEROUS!

Parameters

addr The address in memory to write

value The value to write, or an array of values

Returns

No return value (undefined)

function poke32

(top)

Call type:

function poke32(addr, value)

Description

Write 32 bits of memory at the given location - VERY DANGEROUS!

Parameters

addr The address in memory to write

value The value to write, or an array of values

Returns

No return value (undefined)

function poke8

(top)

Call type:

function poke8(addr, value)

Description

Write 8 bits of memory at the given location - VERY DANGEROUS!

Parameters

addr The address in memory to write

value The value to write, or an array of values

Returns

No return value (undefined)

function print

(top)

Call type:

function print(text, ...)

Description

Print the supplied string(s) to the console

Note: If you're connected to a computer (not a wall adaptor) via USB but you are not running a terminal app then when you print data Espruino may pause execution and wait until the computer requests the data it is trying to print.

Parameters

text, ...

Returns

No return value (undefined)

function require

(top)

Call type:

function require(moduleName)

Description

Load the given module, and return the exported functions

Parameters

moduleName A String containing the name of the given module

Returns

The result of evaluating the string

function reset

(top)

Call type:

function reset()

Description

Reset the interpreter - clear program memory, and do not load a saved program from flash. This does NOT reset the underlying hardware (which allows you to reset the device without it disconnecting from USB).

This command only executes when the Interpreter returns to the Idle state - for instance

a=1;reset();a=2; will still leave 'a' as undefined.

The safest way to do a full reset is to hit the reset button.

Parameters

No parameters

Returns

No return value (undefined)

function save

(top)

Call type:

function save()

Description

Save program memory into flash. It will then be loaded automatically every time Espruino powers on or is hard-reset.

This command only executes when the Interpreter returns to the Idle state - for instance

a=1;save();a=2; will save 'a' as 2.

When Espruino powers on, it will resume from where it was when you typed save(). If you want code to be executed right after loading (for instance to initialise devices connected to Espruino), create a function called onInit (which will be automatically executed by Espruino).

In order to stop the program saved with this command being loaded automatically, hold down Button 1 while also pressing reset. On some boards, Button 1 enters bootloader mode, so you will need to press Reset with Button 1 raised, and then hold Button 1 down a fraction of a second later.

Parameters

No parameters

Returns

No return value (undefined)

function setBusyIndicator

(top)

Call type:

function setBusyIndicator(pin)

Description

When Espruino is busy, set the pin specified here high. Set this to undefined to disable the feature.

Parameters

pin

Returns

No return value (undefined)

function setDeepSleep

(top)

Call type:

function setDeepSleep(sleep)

Description

Set whether we can enter deep sleep mode, which reduces power consumption to around 100uA. This only works on the Espruino Board.

Please see http://www.espruino.com/Power+Consumption for more details on this.

Parameters

sleep

Returns

No return value (undefined)

function setInterval

(top)

Call type:

function setInterval(function, timeout)

Description

Call the function specified REPEATEDLY after the timeout in milliseconds.

The function that is being called may also take an argument, which is an object containing a field called 'time' (the time in seconds at which the timer happened)

for example:

setInterval(function (e) { print(e.time); }, 1000);

This can also be removed using clearInterval

Note: If setDeepSleep(true) has been called and the interval is greater than 5 seconds, Espruino may execute the interval up to 1 second late. This is because Espruino can only wake from deep sleep every second - and waking early would cause Espruino to waste power while it waited for the correct time.

Parameters

function A Function or String to be executed

timeout The time between calls to the function

Returns

An ID that can be passed to clearInterval

function setSleepIndicator

(top)

Call type:

function setSleepIndicator(pin)

Description

When Espruino is asleep, set the pin specified here low (when it's awake, set it high). Set this to undefined to disable the feature.

Please see http://www.espruino.com/Power+Consumption for more details on this.

Parameters

pin

Returns

No return value (undefined)

function setTime

(top)

Call type:

function setTime(time)

Description

Set the current system time in seconds (to the nearest second)

Parameters

time

Returns

No return value (undefined)

function setTimeout

(top)

Call type:

function setTimeout(function, timeout)

Description

Call the function specified ONCE after the timeout in milliseconds.

The function that is being called may also take an argument, which is an object containing a field called 'time' (the time in seconds at which the timer happened)

for example:

setTimeout(function (e) { print(e.time); }, 1000);

This can also be removed using clearTimeout

Note: If setDeepSleep(true) has been called and the interval is greater than 5 seconds, Espruino may execute the interval up to 1 second late. This is because Espruino can only wake from deep sleep every second - and waking early would cause Espruino to waste power while it waited for the correct time.

Parameters

function A Function or String to be executed

timeout The time until the function will be executed

Returns

An ID that can be passed to clearTimeout

function setWatch

(top)

Call type:

function setWatch(function, pin, options)

Description

Call the function specified when the pin changes

The function may also take an argument, which is an object of type {time:float, lastTime:float, state:bool}.

time is the time in seconds at which the pin changed state, lastTime is the time in seconds at which the pin last changed state, and state is the current state of the pin.

For instance, if you want to measure the length of a positive pulse you could use:

setWatch(function(e) { console.log(e.time-e.lastTime); }, BTN, { repeat:true, edge:'falling' });

If the callback is a native function void (bool state)

then you can also add irq:true to options, which will cause the function to be

called from within the IRQ. When doing this, interruptions will happen on both

edges and there will be no debouncing.

Watches set with setWatch can be removed using clearWatch

Parameters

function A Function or String to be executed

pin The pin to watch

options If this is a boolean or integer, it determines whether to call this once (false = default) or every time a change occurs (true)
If this is an object, it can contain the following information: { repeat: true/false(default), edge:'rising'/'falling'/'both'(default), debounce:10}. debounce is the time in ms to wait for bounces to subside, or 0.

Returns

An ID that can be passed to clearWatch

function trace

(top)

Call type:

function trace(root)

Description

Output debugging information

Note: This is only available in some devices: not devices with low flash memory

Parameters

root The symbol to output (optional). If nothing is specified, everything will be output

Returns

No return value (undefined)

Array Class

(top)

This is the built-in JavaScript class for arrays.

Arrays can be defined with

[],

new Array(), or

new Array(length)

Methods and Fields

constructor Array

View MDN documentation

(top)

Call type:

new Array(args, ...)

Description

Create an Array. Either give it one integer argument (>=0) which is the length of the array, or any number of arguments

Parameters

args, ... The length of the array OR any number of items to add to the array

Returns

An Array

function Array.concat

View MDN documentation

(top)

Call type:

function Array.concat(args, ...)

Description

Create a new array, containing the elements from this one and any arguments, if any argument is an array then those elements will be added.

Note: This is only available in some devices: not devices with low flash memory

Parameters

args, ... Any items to add to the array

Returns

An Array

function Array.every

View MDN documentation

(top)

Call type:

function Array.every(function, thisArg)

Description

Return 'true' if the callback returns 'true' for every element in the array

Parameters

function Function to be executed

thisArg if specified, the function is called with 'this' set to thisArg (optional)

Returns

A boolean containing the result

function Array.fill

View MDN documentation

(top)

Call type:

function Array.fill(value, start, end)

Description

Fill this array with the given value, for every index >= start and < end

Note: This is only available in some devices: not devices with low flash memory

Parameters

value The value to fill the array with

start Optional. The index to start from (or 0). If start is negative, it is treated as length+start where length is the length of the array

end Optional. The index to end at (or the array length). If end is negative, it is treated as length+end.

Returns

This array

function Array.filter

View MDN documentation

(top)

Call type:

function Array.filter(function, thisArg)

Description

Return an array which contains only those elements for which the callback function returns 'true'

Parameters

function Function to be executed

thisArg if specified, the function is called with 'this' set to thisArg (optional)

Returns

An array containing the results

function Array.forEach

View MDN documentation

(top)

Call type:

function Array.forEach(function, thisArg)

Description

Executes a provided function once per array element.

Parameters

function Function to be executed

thisArg if specified, the function is called with 'this' set to thisArg (optional)

Returns

No return value (undefined)

function Array.indexOf

View MDN documentation

(top)

Call type:

function Array.indexOf(value)

Description

Return the index of the value in the array, or -1

Parameters

value The value to check for

Returns

the index of the value in the array, or -1

Array.isArray

View MDN documentation

(top)

Call type:

Array.isArray(var)

Description

Returns true if the provided object is an array

Parameters

var The variable to be tested

Returns

True if var is an array, false if not.

function Array.join

View MDN documentation

(top)

Call type:

function Array.join(separator)

Description

Join all elements of this array together into one string, using 'separator' between them. eg.

[1,2,3].join(' ')=='1 2 3'

Parameters

separator The separator

Returns

A String representing the Joined array

property Array.length

View MDN documentation

(top)

Call type:

property Array.length

Description

Find the length of the array

Parameters

No parameters

Returns

The value of the array

function Array.map

View MDN documentation

(top)

Call type:

function Array.map(function, thisArg)

Description

Return an array which is made from the following:

A.map(function) = [function(A[0]), function(A[1]), ...]

Parameters

function Function used to map one item to another

thisArg if specified, the function is called with 'this' set to thisArg (optional)

Returns

An array containing the results

function Array.pop

View MDN documentation

(top)

Call type:

function Array.pop()

Description

Pop a new value off of the end of this array

Parameters

No parameters

Returns

The value that is popped off

function Array.push

View MDN documentation

(top)

Call type:

function Array.push(arguments, ...)

Description

Push a new value onto the end of this array'

Parameters

arguments, ... One or more arguments to add

Returns

The new size of the array

function Array.reduce

View MDN documentation

(top)

Call type:

function Array.reduce(callback, initialValue)

Description

Execute previousValue=initialValue and then previousValue = callback(previousValue, currentValue, index, array) for each element in the array, and finally return previousValue.

Note: This is only available in some devices: not devices with low flash memory

Parameters

callback Function used to reduce the array

initialValue if specified, the initial value to pass to the function

Returns

The value returned by the last function called

function Array.reverse

View MDN documentation

(top)

Call type:

function Array.reverse()

Description

Reverse all elements in this array (in place)

Note: This is only available in some devices: not devices with low flash memory

Parameters

No parameters

Returns

The array, but reversed.

function Array.shift

View MDN documentation

(top)

Call type:

function Array.shift()

Description

Remove the first element of the array, and return it

Note: This is only available in some devices: not devices with low flash memory

Parameters

Returns

The element that was removed

function Array.slice

View MDN documentation

(top)

Call type:

function Array.slice(start, end)

Description

Return a copy of a portion of this array (in a new array)

Parameters

start Start index

end End index (optional)

Returns

A new array

function Array.some

View MDN documentation

(top)

Call type:

function Array.some(function, thisArg)

Description

Return 'true' if the callback returns 'true' for any of the elements in the array

Parameters

function Function to be executed

thisArg if specified, the function is called with 'this' set to thisArg (optional)

Returns

A boolean containing the result

function Array.sort

View MDN documentation

(top)

Call type:

function Array.sort(var)

Description

Do an in-place quicksort of the array

Note: This is only available in some devices: not devices with low flash memory

Parameters

var A function to use to compare array elements (or undefined)

Returns

This array object

function Array.splice

View MDN documentation

(top)

Call type:

function Array.splice(index, howMany, elements, ...)

Description

Both remove and add items to an array

Parameters

index Index at which to start changing the array. If negative, will begin that many elements from the end

howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.

elements, ... One or more items to add to the array

Returns

An array containing the removed elements. If only one element is removed, an array of one element is returned.

function Array.toString

View MDN documentation

(top)

Call type:

function Array.toString(radix)

Description

Convert the Array to a string

Parameters

radix unused

Returns

A String representing the array

function Array.unshift

View MDN documentation

(top)

Call type:

function Array.unshift(elements, ...)

Description

Remove the first element of the array, and return it

Note: This is only available in some devices: not devices with low flash memory

Parameters

elements, ... One or more items to add to the beginning of the array

Returns

The new array length

ArrayBuffer Class

(top)

This is the built-in JavaScript class for array buffers.

Methods and Fields

constructor ArrayBuffer

(top)

Call type:

new ArrayBuffer(byteLength)

Description

Create an Array Buffer object

Parameters

byteLength The length in Bytes

Returns

An ArrayBuffer object

ArrayBufferView Class

(top)

This is the built-in JavaScript class that is the prototype for Uint8Array / Float32Array / etc

Methods and Fields

property ArrayBufferView.buffer

(top)

Call type:

property ArrayBufferView.buffer

Description

The buffer this view references

Parameters

No parameters

Returns

An ArrayBuffer object

property ArrayBufferView.byteLength

(top)

Call type:

property ArrayBufferView.byteLength

Description

The length, in bytes, of the view

Parameters

No parameters

Returns

The Length

property ArrayBufferView.byteOffset

(top)

Call type:

property ArrayBufferView.byteOffset

Description

The offset, in bytes, to the first byte of the view within the ArrayBuffer

Parameters

No parameters

Returns

The byte Offset

function ArrayBufferView.fill

(top)

Call type:

function ArrayBufferView.fill(value, start, end)

Description

Fill this array with the given value, for every index >= start and < end

Note: This is only available in some devices: not devices with low flash memory

Parameters

value The value to fill the array with

start Optional. The index to start from (or 0). If start is negative, it is treated as length+start where length is the length of the array

end Optional. The index to end at (or the array length). If end is negative, it is treated as length+end.

Returns

This array

function ArrayBufferView.forEach

(top)

Call type:

function ArrayBufferView.forEach(function, thisArg)

Description

Executes a provided function once per array element.

Parameters

function Function to be executed

thisArg if specified, the function is called with 'this' set to thisArg (optional)

Returns

No return value (undefined)

function ArrayBufferView.indexOf

(top)

Call type:

function ArrayBufferView.indexOf(value)

Description

Return the index of the value in the array, or -1

Parameters

value The value to check for

Returns

the index of the value in the array, or -1

function ArrayBufferView.join

(top)

Call type:

function ArrayBufferView.join(separator)

Description

Join all elements of this array together into one string, using 'separator' between them. eg.

[1,2,3].join(' ')=='1 2 3'

Parameters

separator The separator

Returns

A String representing the Joined array

function ArrayBufferView.map

(top)

Call type:

function ArrayBufferView.map(function, thisArg)

Description

Return an array which is made from the following:

A.map(function) = [function(A[0]), function(A[1]), ...]

Note: This returns an ArrayBuffer of the same type it was called on. To get an Array, use Array.prototype.map

Parameters

function Function used to map one item to another

thisArg if specified, the function is called with 'this' set to thisArg (optional)

Returns

An array containing the results

function ArrayBufferView.reduce

(top)

Call type:

function ArrayBufferView.reduce(callback, initialValue)

Description

Execute previousValue=initialValue and then previousValue = callback(previousValue, currentValue, index, array) for each element in the array, and finally return previousValue.

Note: This is only available in some devices: not devices with low flash memory

Parameters

callback Function used to reduce the array

initialValue if specified, the initial value to pass to the function

Returns

The value returned by the last function called

function ArrayBufferView.reverse

(top)

Call type:

function ArrayBufferView.reverse()

Description

Reverse the contents of this arraybuffer in-place

Note: This is only available in some devices: not devices with low flash memory

Parameters

No parameters

Returns

This array

function ArrayBufferView.set

(top)

Call type:

function ArrayBufferView.set(arr, offset)

Description

Copy the contents of array into this one, mapping this[x+offset]=array[x];

Parameters

arr Floating point index to access

offset The offset in this array at which to write the values (optional)

Returns

No return value (undefined)

function ArrayBufferView.slice

(top)

Call type:

function ArrayBufferView.slice(start, end)

Description

Return a copy of a portion of this array (in a new array).

Note: This currently returns a normal Array, not an ArrayBuffer

Note: This is only available in some devices: not devices with low flash memory

Parameters

start Start index

end End index (optional)

Returns

A new array

function ArrayBufferView.sort

(top)

Call type:

function ArrayBufferView.sort(var)

Description

Do an in-place quicksort of the array

Note: This is only available in some devices: not devices with low flash memory

Parameters

var A function to use to compare array elements (or undefined)

Returns

This array object

Boolean Class

(top)

Methods and Fields

constructor Boolean

View MDN documentation

(top)

Call type:

new Boolean(value)

Description

Creates a number

Parameters

value A single value to be converted to a number

Returns

A Boolean object

CC3000 Class

(top)

Methods and Fields

CC3000.connect

(top)

Call type:

CC3000.connect(spi, cs, en, irq)

Description

Initialise the CC3000 and return a WLAN object

Parameters

spi Device to use for SPI (or undefined to use the default). SPI should be 1,000,000 baud, and set to 'mode 1'

cs The pin to use for Chip Select

en The pin to use for Enable

irq The pin to use for Interrupts

Returns

A WLAN Object

Date Class

(top)

The built-in class for handling Dates

Methods and Fields

constructor Date

View MDN documentation

(top)

Call type:

new Date(args, ...)

Description

Creates a date object

Parameters

args, ... Either nothing (current time), one numeric argument (milliseconds since 1970), a date string (see Date.parse), or [year, month, day, hour, minute, second, millisecond]

Returns

A Date object

function Date.getDate

View MDN documentation

(top)

Call type:

function Date.getDate()

Description

Day of the month 1..31

Parameters

No parameters

Returns

See description above

function Date.getDay

View MDN documentation

(top)

Call type:

function Date.getDay()

Description

Day of the week (0=sunday, 1=monday, etc)

Parameters

No parameters

Returns

See description above

function Date.getFullYear

View MDN documentation

(top)

Call type:

function Date.getFullYear()

Description

The year, eg. 2014

Parameters

No parameters

Returns

See description above

function Date.getHours

View MDN documentation

(top)

Call type:

function Date.getHours()

Description

0..23

Parameters

No parameters

Returns

See description above

function Date.getMilliseconds

View MDN documentation

(top)

Call type:

function Date.getMilliseconds()

Description

0..999

Parameters

No parameters

Returns

See description above

function Date.getMinutes

View MDN documentation

(top)

Call type:

function Date.getMinutes()

Description

0..59

Parameters

No parameters

Returns

See description above

function Date.getMonth

View MDN documentation

(top)

Call type:

function Date.getMonth()

Description

Month of the year 0..11

Parameters

No parameters

Returns

See description above

function Date.getSeconds

View MDN documentation

(top)

Call type:

function Date.getSeconds()

Description

0..59

Parameters

No parameters

Returns

See description above

function Date.getTime

View MDN documentation

(top)

Call type:

function Date.getTime()

Description

Return the number of milliseconds since 1970

Parameters

No parameters

Returns

See description above

function Date.getTimezoneOffset

View MDN documentation

(top)

Call type:

function Date.getTimezoneOffset()

Description

The getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.

Parameters

No parameters

Returns

The difference, in minutes, between UTC and local time

Date.now

View MDN documentation

(top)

Call type:

Date.now()

Description

Get the number of milliseconds elapsed since 1970 (or on embedded platforms, since startup)

Parameters

No parameters

Returns

See description above

Date.parse

View MDN documentation

(top)

Call type:

Date.parse(str)

Description

Parse a date string and return milliseconds since 1970. Data can be either '2011-10-20T14:48:00', '2011-10-20' or 'Mon, 25 Dec 1995 13:30:00 +0430'

Parameters

str A String

Returns

The number of milliseconds since 1970

function Date.toString

View MDN documentation

(top)

Call type:

function Date.toString()

Description

Converts to a String, eg: Fri Jun 20 2014 14:52:20 GMT+0000

Note: This always assumes a timezone of GMT+0000

Parameters

No parameters

Returns

A String

function Date.toUTCString

View MDN documentation

(top)

Call type:

function Date.toUTCString()

Description

Converts to a String, eg: Fri, 20 Jun 2014 14:52:20 GMT

Note: This always assumes a timezone of GMT

Parameters

No parameters

Returns

A String

function Date.valueOf

View MDN documentation

(top)

Call type:

function Date.valueOf()

Description

Return the number of milliseconds since 1970

Parameters

No parameters

Returns

See description above

E Class

(top)

This is the built-in JavaScript class for Espruino utility functions.

Methods and Fields

E.FFT

(top)

Call type:

E.FFT(arrReal, arrImage, inverse)

Description

Performs a Fast Fourier Transform (fft) on the supplied data and writes it back into the original arrays. Note that if only one array is supplied, the data written back is the modulus of the complex result sqrt(rr+ii).

Note: This is only available in some devices: not devices with low flash memory

Parameters

arrReal An array of real values

arrImage An array of imaginary values (or if undefined, all values will be taken to be 0)

inverse Set this to true if you want an inverse FFT - otherwise leave as 0

Returns

No return value (undefined)

E.clip

(top)

Call type:

E.clip(x, min, max)

Description

Clip a number to be between min and max (inclusive)

Note: This is only available in some devices: not devices with low flash memory

Parameters

x A floating point value to clip

min The smallest the value should be

max The largest the value should be

Returns

The value of x, clipped so as not to be below min or above max.

E.connectSDCard

(top)

Call type:

E.connectSDCard(spi, csPin)

Description

Setup the filesystem so that subsequent calls to E.openFile and require('fs').* will use an SD card on the supplied SPI device and pin.

It can even work using software SPI - for instance:

var spi = new SPI();
spi.setup({mosi:C7,miso:C8,sck:C9});
E.connectSDCard(spi,C6);
console.log(require("fs").readdirSync());

Note: This is only available in some devices: not Linux-based builds

Parameters

spi The SPI object to use for communication

csPin The pin to use for Chip Select

Returns

No return value (undefined)

E.convolve

(top)

Call type:

E.convolve(arr1, arr2, offset)

Description

Convolve arr1 with arr2. This is equivalent to v=0;for (i in arr1) v+=arr1[i] * arr2[(i+offset) % arr2.length]

Note: This is only available in some devices: not devices with low flash memory

Parameters

arr1 An array to convolve

arr2 An array to convolve

offset The mean value of the array

Returns

The variance of the given buffer

E.dumpTimers

(top)

Call type:

E.dumpTimers()

Description

Output the current list of Utility Timer Tasks - for debugging only

Note: This is only available in some devices: not release builds

Parameters

No parameters

Returns

No return value (undefined)

E.enableWatchdog

(top)

Call type:

E.enableWatchdog(timeout)

Description

Enable the watchdog timer. This will reset Espruino if it isn't able to return to the idle loop within the timeout. NOTE: This will not work with setDeepSleep unless you explicitly wake Espruino up with an interval of less than the timeout.

Note: This is only available in some devices: not devices with low flash memory

Parameters

timeout The timeout in seconds before a watchdog reset

Returns

No return value (undefined)

E.getAnalogVRef

(top)

Call type:

E.getAnalogVRef()

Description

Check the internal voltage reference. To work out an actual voltage of an input pin, you can use analogRead(pin)*E.getAnalogVRef()

While this is implemented on Espruino boards, it may not be implemented on other devices. If so it'll return NaN.

Note: This is only available in some devices: not devices with low flash memory

Parameters

No parameters

Returns

The voltage (in Volts) that a reading of 1 from analogRead actually represents

E.getErrorFlags

(top)

Call type:

E.getErrorFlags()

Description

Get and reset the error flags. Returns an array that can contain:

'FIFO_FULL': The receive FIFO filled up and data was lost. This could be state transitions for setWatch, or received characters.

'BUFFER_FULL': A buffer for a stream filled up and characters were lost. This can happen to any stream - Serial,HTTP,etc.

'CALLBACK': A callback (setWatch, setInterval, on('data',...)) caused an error and so was removed.

'LOW_MEMORY': Memory is running low - Espruino had to run a garbage collection pass or remove some of the command history

'MEMORY': Espruino ran out of memory and was unable to allocate some data that it needed.

Note: This is only available in some devices: not devices with low flash memory

Parameters

No parameters

Returns

An array of error flags

E.getSizeOf

(top)

Call type:

E.getSizeOf(v)

Description

Return the number of Variable Blocks used by the supplied variable. This is useful if you're running out of memory and you want to be able to see what is taking up most of the available space.

See http://www.espruino.com/Internals for more information

Note: This is only available in some devices: not devices with low flash memory

Parameters

v A variable to get the size of

Returns

The number of variable 'blocks' as an integer

E.getTemperature

(top)

Call type:

E.getTemperature()

Description

Use the STM32's internal thermistor to work out the temperature.

While this is implemented on Espruino boards, it may not be implemented on other devices. If so it'll return NaN.

Note: This is not entirely accurate and varies by a few degrees from chip to chip. It measures the die temperature, so when connected to USB it could be reading 10 over degrees C above ambient temperature. When running from battery with setDeepSleep(true) it is much more accurate though.

Note: This is only available in some devices: not devices with low flash memory

Parameters

No parameters

Returns

The temperature in degrees C

E.interpolate

(top)

Call type:

E.interpolate(array, index)

Description

Interpolate between two adjacent values in the Typed Array

Note: This is only available in some devices: not devices with low flash memory

Parameters

array A Typed Array to interpolate between

index Floating point index to access

Returns

The result of interpolating between (int)index and (int)(index+1)

E.interpolate2d

(top)

Call type:

E.interpolate2d(array, width, x, y)

Description

Interpolate between four adjacent values in the Typed Array, in 2D.

Note: This is only available in some devices: not devices with low flash memory

Parameters

array A Typed Array to interpolate between

width Integer 'width' of 2d array

x Floating point X index to access

y Floating point Y index to access

Returns

The result of interpolating in 2d between the 4 surrounding cells

E.mapInPlace

(top)

Call type:

E.mapInPlace(from, to, map, bits)

Description

Take each element of the from array, look it up in map (or call the

function with it as a first argument), and write it into the corresponding

element in the to array.

Note: This is only available in some devices: not devices with low flash memory

Parameters

from An ArrayBuffer to read elements from

to An ArrayBuffer to write elements too

map An array or function to use to map one element to another

bits If specified, the number of bits per element

Returns

No return value (undefined)

E.nativeCall

(top)

Call type:

E.nativeCall(addr, sig, data)

Description

ADVANCED: This is a great way to crash Espruino if you're not sure what you are doing

Create a native function that executes the code at the given address. Eg. E.nativeCall(0x08012345,'double (double,double)')(1.1, 2.2)

If you're executing a thumb function, you'll almost certainly need to set the bottom bit of the address to 1.

Note it's not guaranteed that the call signature you provide can be used - there are limits on the number of arguments allowed.

When supplying data, if it is a 'flat string' then it will be used directly, otherwise it'll be converted to a flat string and used.

Note: This is only available in some devices: not devices with low flash memory

Parameters

addr The address in memory of the function (or offset in data if it was supplied

sig The signature of the call, returnType (arg1,arg2,...). Allowed types are void,bool,int,double,Pin,JsVar

data (Optional) A string containing the function itself. If not supplied then 'addr' is used as an absolute address.

Returns

The native function

E.openFile

(top)

Call type:

E.openFile(path, mode)

Description

Open a file

Parameters

path the path to the file to open.

mode The mode to use when opening the file. Valid values for mode are 'r' for read, 'w' for write new, 'w+' for write existing, and 'a' for append. If not specified, the default is 'r'.

Returns

A File object

E.reverseByte

(top)

Call type:

E.reverseByte(x)

Description

Reverse the 8 bits in a byte, swapping MSB and LSB.

For example, E.reverseByte(0b10010000) == 0b00001001.

Note that you can reverse all the bytes in an array with: arr = arr.map(E.reverseByte)

Note: This is only available in some devices: not devices with low flash memory

Parameters

x A byte value to reverse the bits of

Returns

The byte with reversed bits

E.sum

(top)

Call type:

E.sum(arr)

Description

Sum the contents of the given Array, String or ArrayBuffer and return the result

Note: This is only available in some devices: not devices with low flash memory

Parameters

arr The array to sum

Returns

The sum of the given buffer

E.toArrayBuffer

(top)

Call type:

E.toArrayBuffer(str)

Description

Create an ArrayBuffer from the given string. This is done via a reference, not a copy - so it is very fast and memory efficient.

Note that this is an ArrayBuffer, not a Uint8Array. To get one of those, do: new Uint8Array(E.toArrayBuffer('....')).

Parameters

str The string to convert to an ArrayBuffer

Returns

An ArrayBuffer that uses the given string

E.toString

(top)

Call type:

E.toString(args, ...)

Description

This creates a string from the given arguments. If an argument is a String or an Array,

each element is traversed and added as an 8 bit character. If it is anything else, it is

converted to a character directly.

Parameters

args, ... The arguments to convert to a String

Returns

A String

E.toUint8Array

(top)

Call type:

E.toUint8Array(args, ...)

Description

This creates a Uint8Array from the given arguments. If an argument is a String or an Array,

each element is traversed and added as if it were an 8 bit value. If it is anything else, it is

converted to an 8 bit value directly.

Parameters

args, ... The arguments to convert to a Uint8Array

Returns

A String

E.unmountSD

(top)

Call type:

E.unmountSD()

Description

Unmount the SD card, so it can be removed. If you remove the SD card without calling this you may cause corruption, and you will be unable to access another SD card until you reset Espruino or call E.unmountSD().

Parameters

No parameters

Returns

No return value (undefined)

E.variance

(top)

Call type:

E.variance(arr, mean)

Description

Work out the variance of the contents of the given Array, String or ArrayBuffer and return the result. This is equivalent to v=0;for (i in arr) v+=Math.pow(mean-arr[i],2)

Note: This is only available in some devices: not devices with low flash memory

Parameters

arr The array to work out the variance for

mean The mean value of the array

Returns

The variance of the given buffer

Error Class

(top)

The base class for runtime errors

Methods and Fields

constructor Error

View MDN documentation

(top)

Call type:

new Error(message)

Description

Creates an Error object

Parameters

message An optional message string

Returns

An Error object

function Error.toString

View MDN documentation

(top)

Call type:

function Error.toString()

Parameters

No parameters

Returns

A String

Ethernet Class

(top)

An instantiation of an Ethernet network adaptor

Methods and Fields

function Ethernet.getIP

(top)

Call type:

function Ethernet.getIP()

Description

Get the current IP address, subnet, gateway and mac address.

Parameters

No parameters

Returns

See description above

function Ethernet.setIP

(top)

Call type:

function Ethernet.setIP(options)

Description

Set the current IP address or get an IP from DHCP (if no options object is specified)

If 'mac' is specified as an option, it must be a string of the form "00:01:02:03:04:05"

Parameters

options Object containing IP address options { ip : '1,2,3,4', subnet, gateway, dns, mac }, or do not supply an object in order to force DHCP.

Returns

True on success

File Class

(top)

This is the File object - it allows you to stream data to and from files (As opposed to the require('fs').readFile(..) style functions that read an entire file).

To create a File object, you must type

var fd = E.openFile('filepath','mode') - see E.openFile for more information.

Note: If you want to remove an SD card after you have started using it, you must call E.unmountSD() or you may cause damage to the card.

Methods and Fields

function File.close

(top)

Call type:

function File.close()

Description

Close an open file.

Parameters

No parameters

Returns

No return value (undefined)

function File.pipe

(top)

Call type:

function File.pipe(destination, options)

Description

Pipe this file to a stream (an object with a 'write' method)

Note: This is only available in some devices: not devices with low flash memory

Parameters

destination The destination file/stream that will receive content from the source.

options An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished

Returns

No return value (undefined)

function File.read

(top)

Call type:

function File.read(length)

Description

Read data in a file in byte size chunks

Parameters

length is an integer specifying the number of bytes to read.

Returns

A string containing the characters that were read

function File.seek

(top)

Call type:

function File.seek(nBytes)

Description

Seek to a certain position in the file

Parameters

nBytes is an integer specifying the number of bytes to skip forwards.

Returns

No return value (undefined)

function File.skip

(top)

Call type:

function File.skip(nBytes)

Description

Skip the specified number of bytes forward in the file

Parameters

nBytes is a positive integer specifying the number of bytes to skip forwards.

Returns

No return value (undefined)

function File.write

(top)

Call type:

function File.write(buffer)

Description

write data to a file

Parameters

buffer A string containing the bytes to write

Returns

the number of bytes written

Float32Array Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Float32Array

(top)

Call type:

new Float32Array(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

Float64Array Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Float64Array

(top)

Call type:

new Float64Array(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

Function Class

(top)

This is the built-in class for Functions

Methods and Fields

constructor Function

View MDN documentation

(top)

Call type:

new Function(args, ...)

Description

Creates a function

Parameters

args, ... Zero or more arguments (as strings), followed by a string representing the code to run

Returns

A Number object

function Function.apply

View MDN documentation

(top)

Call type:

function Function.apply(this, args)

Description

This executes the function with the supplied 'this' argument and parameters

Parameters

this The value to use as the 'this' argument when executing the function

args Optional Array of Arguments

Returns

The return value of executing this function

function Function.bind

(top)

Call type:

function Function.bind(this, params, ...)

Description

This executes the function with the supplied 'this' argument and parameters

Parameters

this The value to use as the 'this' argument when executing the function

params, ... Optional Default parameters that are prepended to the call

Returns

The 'bound' function

function Function.call

View MDN documentation

(top)

Call type:

function Function.call(this, params, ...)

Description

This executes the function with the supplied 'this' argument and parameters

Parameters

this The value to use as the 'this' argument when executing the function

params, ... Optional Parameters

Returns

The return value of executing this function

function Function.replaceWith

(top)

Call type:

function Function.replaceWith(newFunc)

Description

This replaces the function with the one in the argument - while keeping the old function's scope. This allows inner functions to be edited, and is used when edit() is called on an inner function.

Parameters

newFunc The new function to replace this function with

Returns

No return value (undefined)

Graphics Class

(top)

This class provides Graphics operations that can be applied to a surface.

Use Graphics.createXXX to create a graphics object that renders in the way you want.

NOTE: On boards that contain an LCD, there is a built-in 'LCD' object of type Graphics. For instance to draw a line you'd type:

LCD.drawLine(0,0,100,100)

Methods and Fields

function Graphics.clear

(top)

Call type:

function Graphics.clear()

Description

Clear the LCD with the Background Color

Parameters

No parameters

Returns

No return value (undefined)

Graphics.createArrayBuffer

(top)

Call type:

Graphics.createArrayBuffer(width, height, bpp, options)

Description

Create a Graphics object that renders to an Array Buffer. This will have a field called 'buffer' that can get used to get at the buffer itself

Parameters

width Pixels wide

height Pixels high

bpp Number of bits per pixel

options An object of other options. { zigzag : true/false(default), vertical_byte : true/false(default), msb : true/false(default), color_order: 'rgb'(default),'bgr',etc }
zigzag = whether to alternate the direction of scanlines for rows
vertical_byte = whether to align bits in a byte vertically or not
msb = when bits<8, store pixels msb first
color_order = re-orders the colour values that are supplied via setColor

Returns

The new Graphics object

Graphics.createCallback

(top)

Call type:

Graphics.createCallback(width, height, bpp, callback)

Description

Create a Graphics object that renders by calling a JavaScript callback function to draw pixels

Parameters

width Pixels wide

height Pixels high

bpp Number of bits per pixel

callback A function of the form function(x,y,col) that is called whenever a pixel needs to be drawn, or an object with: {setPixel:function(x,y,col),fillRect:function(x1,y1,x2,y2,col)}. All arguments are already bounds checked.

Returns

The new Graphics object

Graphics.createSDL

(top)

Call type:

Graphics.createSDL(width, height)

Description

Create a Graphics object that renders to SDL window (Linux-based devices only)

Note: This is only available in some devices: Linux with SDL support compiled in

Parameters

width Pixels wide

height Pixels high

Returns

The new Graphics object

function Graphics.drawImage

(top)

Call type:

function Graphics.drawImage(image, x, y)

Description

Draw an image at the specified position. If the image is 1 bit, the graphics foreground/background colours will be used. Otherwise color data will be copied as-is. Bitmaps are rendered MSB-first

Parameters

image An object with the following fields { width : int, height : int, bpp : int, buffer : ArrayBuffer, transparent: optional int }. bpp = bits per pixel, transparent (if defined) is the colour that will be treated as transparent

x The X offset to draw the image

y The Y offset to draw the image

Returns

No return value (undefined)

function Graphics.drawLine

(top)

Call type:

function Graphics.drawLine(x1, y1, x2, y2)

Description

Draw a line between x1,y1 and x2,y2 in the current foreground color

Parameters

x1 The left

y1 The top

x2 The right

y2 The bottom

Returns

No return value (undefined)

function Graphics.drawRect

(top)

Call type:

function Graphics.drawRect(x1, y1, x2, y2)

Description

Draw an unfilled rectangle 1px wide in the Foreground Color

Parameters

x1 The left

y1 The top

x2 The right

y2 The bottom

Returns

No return value (undefined)

function Graphics.drawString

(top)

Call type:

function Graphics.drawString(str, x, y)

Description

Draw a string of text in the current font

Parameters

str The string

x The left

y The top

Returns

No return value (undefined)

function Graphics.fillPoly

(top)

Call type:

function Graphics.fillPoly(poly)

Description

Draw a filled polygon in the current foreground color

Parameters

poly An array of vertices, of the form [x1,y1,x2,y2,x3,y3,etc]

Returns

No return value (undefined)

function Graphics.fillRect

(top)

Call type:

function Graphics.fillRect(x1, y1, x2, y2)

Description

Fill a rectangular area in the Foreground Color

Parameters

x1 The left

y1 The top

x2 The right

y2 The bottom

Returns

No return value (undefined)

function Graphics.getBgColor

(top)

Call type:

function Graphics.getBgColor()

Description

Get the background color to use for subsequent drawing operations

Parameters

No parameters

Returns

The integer value of the colour

function Graphics.getColor

(top)

Call type:

function Graphics.getColor()

Description

Get the color to use for subsequent drawing operations

Parameters

No parameters

Returns

The integer value of the colour

function Graphics.getHeight

(top)

Call type:

function Graphics.getHeight()

Description

The height of the LCD

Parameters

No parameters

Returns

The height of the LCD

function Graphics.getPixel

(top)

Call type:

function Graphics.getPixel(x, y)

Description

Get a pixel's color

Parameters

x The left

y The top

Returns

The color

function Graphics.getWidth

(top)

Call type:

function Graphics.getWidth()

Description

The width of the LCD

Parameters

No parameters

Returns

The width of the LCD

function Graphics.lineTo

(top)

Call type:

function Graphics.lineTo(x, y)

Description

Draw a line from the last position of lineTo or moveTo to this position

Parameters

x X value

y Y value

Returns

No return value (undefined)

function Graphics.moveTo

(top)

Call type:

function Graphics.moveTo(x, y)

Description

Move the cursor to a position - see lineTo

Parameters

x X value

y Y value

Returns

No return value (undefined)

function Graphics.setBgColor

(top)

Call type:

function Graphics.setBgColor(r, g, b)

Description

Set the background color to use for subsequent drawing operations

Parameters

r Red (between 0 and 1) OR an integer representing the color in the current bit depth and color order

g Green (between 0 and 1)

b Blue (between 0 and 1)

Returns

No return value (undefined)

function Graphics.setBgColorHSV

(top)

Call type:

function Graphics.setBgColorHSV(h, s, v)

Description

Set the background HSV color to use for subsequent drawing operations

Parameters

h Hue (between 0 and 1)

s Saturation (between 0 and 1)

v Value (between 0 and 1)

Returns

No return value (undefined)

function Graphics.setColor

(top)

Call type:

function Graphics.setColor(r, g, b)

Description

Set the color to use for subsequent drawing operations

Parameters

r Red (between 0 and 1) OR an integer representing the color in the current bit depth and color order

g Green (between 0 and 1)

b Blue (between 0 and 1)

Returns

No return value (undefined)

function Graphics.setColorHSV

(top)

Call type:

function Graphics.setColorHSV(h, s, v)

Description

Set the HSV color to use for subsequent drawing operations

Parameters

h Hue (between 0 and 1)

s Saturation (between 0 and 1)

v Value (between 0 and 1)

Returns

No return value (undefined)

function Graphics.setFontBitmap

(top)

Call type:

function Graphics.setFontBitmap()

Description

Set Graphics to draw with a Bitmapped Font

Parameters

No parameters

Returns

No return value (undefined)

function Graphics.setFontCustom

(top)

Call type:

function Graphics.setFontCustom(bitmap, firstChar, width, height)

Description

Set Graphics to draw with a Custom Font

Parameters

bitmap A column-first, MSB-first, 1bpp bitmap containing the font bitmap

firstChar The first character in the font - usually 32 (space)

width The width of each character in the font. Either an integer, or a string where each character represents the width

height The height as an integer

Returns

No return value (undefined)

function Graphics.setFontVector

(top)

Call type:

function Graphics.setFontVector(size)

Description

Set Graphics to draw with a Vector Font of the given size

Note: This is only available in some devices: not devices with low flash memory

Parameters

size The size as an integer

Returns

No return value (undefined)

function Graphics.setPixel

(top)

Call type:

function Graphics.setPixel(x, y, col)

Description

Set a pixel's color

Parameters

x The left

y The top

col The color

Returns

No return value (undefined)

function Graphics.setRotation

(top)

Call type:

function Graphics.setRotation(rotation, reflect)

Description

Set the current rotation of the graphics device.

Parameters

rotation The clockwise rotation. 0 for no rotation, 1 for 90 degrees, 2 for 180, 3 for 270

reflect Whether to reflect the image

Returns

No return value (undefined)

function Graphics.stringWidth

(top)

Call type:

function Graphics.stringWidth(str)

Description

Return the size in pixels of a string of text in the current font

Parameters

str The string

Returns

The length of the string in pixels

HASH Class

(top)

Note: This class is currently only included in builds for the original Espruino boards.

For other boards you will have to make build your own firmware.

Methods and Fields

function HASH.digest

(top)

Call type:

function HASH.digest(message)

Parameters

message part of message

Returns

Hash digest

function HASH.hexdigest

(top)

Call type:

function HASH.hexdigest(message)

Parameters

message part of message

Returns

Hash hexdigest

function HASH.update

(top)

Call type:

function HASH.update(message)

Parameters

message part of message

Returns

No return value (undefined)

I2C Class

(top)

This class allows use of the built-in I2C ports. Currently it allows I2C Master mode only.

All addresses are in 7 bit format. If you have an 8 bit address then you need to shift it one bit to the right.

Instances

Methods and Fields

function I2C.readFrom

(top)

Call type:

function I2C.readFrom(address, quantity)

Description

Request bytes from the given slave device, and return them as a Uint8Array (packed array of bytes). This is like using Arduino Wire's requestFrom, available and read functions. Sends a STOP

Parameters

address The 7 bit address of the device to request bytes from, or an object of the form {address:12, stop:false} to send this data without a STOP signal.

quantity The number of bytes to request

Returns

The data that was returned - as a Uint8Array

function I2C.setup

(top)

Call type:

function I2C.setup(options)

Description

Set up this I2C port

If not specified in options, the default pins are used (usually the lowest numbered pins on the lowest port that supports this peripheral)

Parameters

options An optional structure containing extra information on initialising the I2C port
{scl:pin, sda:pin, bitrate:100000}
You can find out which pins to use by looking at your board's reference page and searching for pins with the I2C marker. Note that 400000kHz is the maximum bitrate for most parts.

Returns

No return value (undefined)

function I2C.writeTo

(top)

Call type:

function I2C.writeTo(address, data, ...)

Description

Transmit to the slave device with the given address. This is like Arduino's beginTransmission, write, and endTransmission rolled up into one.

Parameters

address The 7 bit address of the device to transmit to, or an object of the form {address:12, stop:false} to send this data without a STOP signal.

data, ... One or more items to write. May be ints, strings, arrays, or objects of the form {data: ..., count:#}.

Returns

No return value (undefined)

Int16Array Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Int16Array

(top)

Call type:

new Int16Array(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

Int32Array Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Int32Array

(top)

Call type:

new Int32Array(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

Int8Array Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Int8Array

(top)

Call type:

new Int8Array(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

InternalError Class

(top)

The base class for internal errors

Methods and Fields

constructor InternalError

View MDN documentation

(top)

Call type:

new InternalError(message)

Description

Creates an InternalError object

Parameters

message An optional message string

Returns

An InternalError object

function InternalError.toString

(top)

Call type:

function InternalError.toString()

Parameters

No parameters

Returns

A String

JSON Class

(top)

An Object that handles conversion to and from the JSON data interchange format

Methods and Fields

JSON.parse

View MDN documentation

(top)

Call type:

JSON.parse(string)

Description

Parse the given JSON string into a JavaScript object

NOTE: This implementation uses eval() internally, and as such it is unsafe as it can allow arbitrary JS commands to be executed.

Parameters

string A JSON string

Returns

The JavaScript object created by parsing the data string

JSON.stringify

View MDN documentation

(top)

Call type:

JSON.stringify(data)

Description

Convert the given object into a JSON string which can subsequently be parsed with JSON.parse or eval

Parameters

data The data to be converted to a JSON string

Returns

A JSON string

Math Class

(top)

This is a standard JavaScript class that contains useful Maths routines

Methods and Fields

Math.E

View MDN documentation

(top)

Call type:

Math.E

Parameters

No parameters

Returns

The value of E - 2.718281828459045

Math.LN10

View MDN documentation

(top)

Call type:

Math.LN10

Parameters

No parameters

Returns

The natural logarithm of 10 - 2.302585092994046

Math.LN2

View MDN documentation

(top)

Call type:

Math.LN2

Parameters

No parameters

Returns

The natural logarithm of 2 - 0.6931471805599453

Math.LOG10E

View MDN documentation

(top)

Call type:

Math.LOG10E

Parameters

No parameters

Returns

The base 10 logarithm of e - 0.4342944819032518

Math.LOG2E

View MDN documentation

(top)

Call type:

Math.LOG2E

Parameters

No parameters

Returns

The base 2 logarithm of e - 1.4426950408889634

Math.PI

View MDN documentation

(top)

Call type:

Math.PI

Parameters

No parameters

Returns

The value of PI - 3.141592653589793

Math.SQRT1_2

View MDN documentation

(top)

Call type:

Math.SQRT1_2

Parameters

No parameters

Returns

The square root of 1/2 - 0.7071067811865476

Math.SQRT2

View MDN documentation

(top)

Call type:

Math.SQRT2

Parameters

No parameters

Returns

The square root of 2 - 1.4142135623730951

Math.abs

View MDN documentation

(top)

Call type:

Math.abs(x)

Parameters

x A floating point value

Returns

The absolute value of x (eg, Math.abs(2)==2, but also Math.abs(-2)==2)

Math.acos

View MDN documentation

(top)

Call type:

Math.acos(x)

Parameters

x The value to get the arc cosine of

Returns

The arc cosine of x, between 0 and PI

Math.asin

View MDN documentation

(top)

Call type:

Math.asin(x)

Parameters

x The value to get the arc sine of

Returns

The arc sine of x, between -PI/2 and PI/2

Math.atan

View MDN documentation

(top)

Call type:

Math.atan(x)

Parameters

x The value to get the arc tangent of

Returns

The arc tangent of x, between -PI/2 and PI/2

Math.atan2

View MDN documentation

(top)

Call type:

Math.atan2(y, x)

Parameters

y The Y-part of the angle to get the arc tangent of

x The X-part of the angle to get the arc tangent of

Returns

The arctangent of Y/X, between -PI and PI

Math.ceil

View MDN documentation

(top)

Call type:

Math.ceil(x)

Parameters

x The value to round up

Returns

x, rounded upwards to the nearest integer

Math.clip

(top)

Call type:

Math.clip(x, min, max)

Description

DEPRECATED - Please use E.clip() instead. Clip a number to be between min and max (inclusive)

Note: This is only available in some devices: not devices with low flash memory

Parameters

x A floating point value to clip

min The smallest the value should be

max The largest the value should be

Returns

The value of x, clipped so as not to be below min or above max.

Math.cos

View MDN documentation

(top)

Call type:

Math.cos(theta)

Parameters

theta The angle to get the cosine of

Returns

The cosine of theta

Math.exp

View MDN documentation

(top)

Call type:

Math.exp(x)

Parameters

x The value raise E to the power of

Returns

E^x

Math.floor

View MDN documentation

(top)

Call type:

Math.floor(x)

Parameters

x The value to round down

Returns

x, rounded downwards to the nearest integer

Math.log

View MDN documentation

(top)

Call type:

Math.log(x)

Parameters

x The value to take the logarithm (base E) root of

Returns

The log (base E) of x

Math.max

View MDN documentation

(top)

Call type:

Math.max(args, ...)

Description

Find the maximum of a series of numbers

Parameters

args, ... A floating point value to clip

Returns

The maximum of the supplied values

Math.min

View MDN documentation

(top)

Call type:

Math.min(args, ...)

Description

Find the minimum of a series of numbers

Parameters

args, ... A floating point value to clip

Returns

The minimum of the supplied values

Math.pow

View MDN documentation

(top)

Call type:

Math.pow(x, y)

Parameters

x The value to raise to the power

y The power x should be raised to

Returns

x raised to the power y (x^y)

Math.random

View MDN documentation

(top)

Call type:

Math.random()

Parameters

No parameters

Returns

A random number between 0 and 1

Math.round

View MDN documentation

(top)

Call type:

Math.round(x)

Parameters

x The value to round

Returns

x, rounded to the nearest integer

Math.sin

View MDN documentation

(top)

Call type:

Math.sin(theta)

Parameters

theta The angle to get the sine of

Returns

The sine of theta

Math.sqrt

View MDN documentation

(top)

Call type:

Math.sqrt(x)

Parameters

x The value to take the square root of

Returns

The square root of x

Math.tan

View MDN documentation

(top)

Call type:

Math.tan(theta)

Parameters

theta The angle to get the tangent of

Returns

The tangent of theta

Math.wrap

(top)

Call type:

Math.wrap(x, max)

Description

Wrap a number around if it is less than 0 or greater than or equal to max. For instance you might do:

Math.wrap(angleInDegrees, 360)

Note: This is only available in some devices: not devices with low flash memory

Parameters

x A floating point value to wrap

max The largest the value should be

Returns

The value of x, wrapped so as not to be below min or above max.

Modules Class

(top)

Built-in class that caches the modules used by the require command

Methods and Fields

Modules.addCached

(top)

Call type:

Modules.addCached(id, sourcecode)

Description

Add the given module to the cache

Parameters

id The module name to add

sourcecode The module's sourcecode

Returns

No return value (undefined)

Modules.getCached

(top)

Call type:

Modules.getCached()

Description

Return an array of module names that have been cached

Parameters

No parameters

Returns

An array of module names

Modules.removeAllCached

(top)

Call type:

Modules.removeAllCached()

Description

Remove all cached modules

Parameters

No parameters

Returns

No return value (undefined)

Modules.removeCached

(top)

Call type:

Modules.removeCached(id)

Description

Remove the given module from the list of cached modules

Parameters

id The module name to remove

Returns

No return value (undefined)

NetworkJS Class

(top)

Library that initialises a network device that calls into JavaScript

Methods and Fields

NetworkJS.create

(top)

Call type:

NetworkJS.create(obj)

Description

Initialise the network using the callbacks given and return the first argument. For instance:

require("NetworkJS").create({
  create : function(host,port) {
    // Create a socket and return its index, host is a string, port is an integer.
    // If host isn't defined, create a server socket
    console.log("Create",host,port);
    return 1;
  },
  close : function(sckt) {
    // Close the socket. returns nothing
  },
  accept : function(sckt) {
    // Accept the connection on the server socket. Returns socket number or -1 if no connection
    return -1;
  },
  recv : function(sckt, maxLen) {
    // Receive data. Returns a string (even if empty).
    // If non-string returned, socket is then closed
    return null;//or "";
  },
  send : function(sckt, data) {
    // Send data (as string). Returns the number of bytes sent - 0 is ok.
    // Less than 0
    return data.length;
  }
});

Parameters

obj An object containing functions to access the network device

Returns

The object passed in

Nucleo Class

(top)

This is the built-in class for the Arduino-style pin namings on ST Nucleo boards

Methods and Fields

Nucleo.A0

(top)

Call type:

Nucleo.A0

Parameters

No parameters

Returns

A Pin

Nucleo.A1

(top)

Call type:

Nucleo.A1

Parameters

No parameters

Returns

A Pin

Nucleo.A2

(top)

Call type:

Nucleo.A2

Parameters

No parameters

Returns

A Pin

Nucleo.A3

(top)

Call type:

Nucleo.A3

Parameters

No parameters

Returns

A Pin

Nucleo.A4

(top)

Call type:

Nucleo.A4

Parameters

No parameters

Returns

A Pin

Nucleo.A5

(top)

Call type:

Nucleo.A5

Parameters

No parameters

Returns

A Pin

Nucleo.D0

(top)

Call type:

Nucleo.D0

Parameters

No parameters

Returns

A Pin

Nucleo.D1

(top)

Call type:

Nucleo.D1

Parameters

No parameters

Returns

A Pin

Nucleo.D10

(top)

Call type:

Nucleo.D10

Parameters

No parameters

Returns

A Pin

Nucleo.D11

(top)

Call type:

Nucleo.D11

Parameters

No parameters

Returns

A Pin

Nucleo.D12

(top)

Call type:

Nucleo.D12

Parameters

No parameters

Returns

A Pin

Nucleo.D13

(top)

Call type:

Nucleo.D13

Parameters

No parameters

Returns

A Pin

Nucleo.D14

(top)

Call type:

Nucleo.D14

Parameters

No parameters

Returns

A Pin

Nucleo.D15

(top)

Call type:

Nucleo.D15

Parameters

No parameters

Returns

A Pin

Nucleo.D2

(top)

Call type:

Nucleo.D2

Parameters

No parameters

Returns

A Pin

Nucleo.D3

(top)

Call type:

Nucleo.D3

Parameters

No parameters

Returns

A Pin

Nucleo.D4

(top)

Call type:

Nucleo.D4

Parameters

No parameters

Returns

A Pin

Nucleo.D5

(top)

Call type:

Nucleo.D5

Parameters

No parameters

Returns

A Pin

Nucleo.D6

(top)

Call type:

Nucleo.D6

Parameters

No parameters

Returns

A Pin

Nucleo.D7

(top)

Call type:

Nucleo.D7

Parameters

No parameters

Returns

A Pin

Nucleo.D8

(top)

Call type:

Nucleo.D8

Parameters

No parameters

Returns

A Pin

Nucleo.D9

(top)

Call type:

Nucleo.D9

Parameters

No parameters

Returns

A Pin

Number Class

(top)

This is the built-in JavaScript class for numbers.

Methods and Fields

Number.MAX_VALUE

View MDN documentation

(top)

Call type:

Number.MAX_VALUE

Parameters

No parameters

Returns

Maximum representable value

Number.MIN_VALUE

View MDN documentation

(top)

Call type:

Number.MIN_VALUE

Parameters

No parameters

Returns

Smallest representable value

Number.NEGATIVE_INFINITY

View MDN documentation

(top)

Call type:

Number.NEGATIVE_INFINITY

Parameters

No parameters

Returns

Negative Infinity (-1/0)

Number.NaN

View MDN documentation

(top)

Call type:

Number.NaN

Parameters

No parameters

Returns

Not a Number

constructor Number

View MDN documentation

(top)

Call type:

new Number(value, ...)

Description

Creates a number

Parameters

value, ... A single value to be converted to a number

Returns

A Number object

Number.POSITIVE_INFINITY

View MDN documentation

(top)

Call type:

Number.POSITIVE_INFINITY

Parameters

No parameters

Returns

Positive Infinity (1/0)

function Number.toFixed

View MDN documentation

(top)

Call type:

function Number.toFixed(decimalPlaces)

Description

Format the number as a fixed point number

Parameters

decimalPlaces A number between 0 and 20 specifying the number of decimal digits after the decimal point

Returns

A string

Object Class

(top)

This is the built-in class for Objects

Methods and Fields

function Object.clone

(top)

Call type:

function Object.clone()

Description

Copy this object completely

Parameters

No parameters

Returns

A copy of this Object

Object.create

View MDN documentation

(top)

Call type:

Object.create(proto)

Description

Creates a new object with the specified prototype object and properties. properties are currently unsupported.

Parameters

proto A prototype object

Returns

A new object

function Object.emit

(top)

Call type:

function Object.emit(event, args, ...)

Description

Call the event listeners for this object, for instance

http.emit('data', 'Foo'). See Node.js's EventEmitter.

Parameters

event The name of the event, for instance 'data'

args, ... Optional arguments

Returns

No return value (undefined)

Object.getOwnPropertyDescriptor

View MDN documentation

(top)

Call type:

Object.getOwnPropertyDescriptor(obj, name)

Description

Get information on the given property in the object, or undefined

Parameters

obj The object

name The name of the property

Returns

An object with a description of the property. The values of writable/enumerable/configurable may not be entirely correct due to Espruino's implementation.

Object.getOwnPropertyNames

View MDN documentation

(top)

Call type:

Object.getOwnPropertyNames(object)

Description

Returns an array of all properties (enumerable or not) found directly on a given object.

Note: This doesn't currently work as it should for built-in objects and their prototypes. See bug #380

Parameters

object The Object to return a list of property names for

Returns

An array of the Object's own properties

function Object.hasOwnProperty

View MDN documentation

(top)

Call type:

function Object.hasOwnProperty(name)

Description

Return true if the object (not its prototype) has the given property.

NOTE: This currently returns false-positives for built-in functions in prototypes

Parameters

name The name of the property to search for

Returns

True if it exists, false if it doesn't

Object.keys

View MDN documentation

(top)

Call type:

Object.keys(object)

Description

Return all enumerable keys of the given object

Parameters

object The object to return keys for

Returns

An array of strings - one for each key on the given object

property Object.length

(top)

Call type:

property Object.length

Description

Find the length of the object

Parameters

No parameters

Returns

The length of the object

function Object.on

(top)

Call type:

function Object.on(event, listener)

Description

Register an event listener for this object, for instance

http.on('data', function(d) {...}). See Node.js's EventEmitter.

Parameters

event The name of the event, for instance 'data'

listener The listener to call when this event is received

Returns

No return value (undefined)

function Object.removeAllListeners

(top)

Call type:

function Object.removeAllListeners(event)

Description

Removes all listeners, or those of the specified event.

Parameters

event The name of the event, for instance 'data'

Returns

No return value (undefined)

function Object.toString

View MDN documentation

(top)

Call type:

function Object.toString(radix)

Description

Convert the Object to a string

Parameters

radix If the object is an integer, the radix (between 2 and 36) to use. NOTE: Setting a radix does not work on floating point numbers.

Returns

A String representing the object

function Object.valueOf

View MDN documentation

(top)

Call type:

function Object.valueOf()

Description

Returns the primitive value of this object.

Parameters

No parameters

Returns

The primitive value of this object

OneWire Class

(top)

This class provides a software-defined OneWire master. It is designed to be similar to Arduino's OneWire library.

Methods and Fields

constructor OneWire

(top)

Call type:

new OneWire(pin)

Description

Create a software OneWire implementation on the given pin

Parameters

pin The pin to implement OneWire on

Returns

A OneWire object

function OneWire.read

(top)

Call type:

function OneWire.read(count)

Description

Read a byte

Parameters

count (optional) The amount of bytes to read

Returns

The byte that was read, or a Uint8Array if count was specified and >=0

function OneWire.reset

(top)

Call type:

function OneWire.reset()

Description

Perform a reset cycle

Parameters

No parameters

Returns

True is a device was present (it held the bus low)

function OneWire.search

(top)

Call type:

function OneWire.search()

Description

Search for devices

Parameters

No parameters

Returns

An array of devices that were found

function OneWire.search

(top)

Call type:

function OneWire.search(command)

Description

Search for devices

Parameters

command (Optional) command byte. If not specified (or zero), this defaults to 0xF0. This can could be set to 0xEC to perform a DS18B20 'Alarm Search Command'

Returns

An array of devices that were found

function OneWire.select

(top)

Call type:

function OneWire.select(rom)

Description

Select a ROM - reset needs to be done first

Parameters

rom The device to select (get this using OneWire.search())

Returns

No return value (undefined)

function OneWire.skip

(top)

Call type:

function OneWire.skip()

Description

Skip a ROM

Parameters

No parameters

Returns

No return value (undefined)

function OneWire.write

(top)

Call type:

function OneWire.write(data, power)

Description

Write one or more bytes

Parameters

data A byte (or array of bytes) to write

power Whether to leave power on after write (default is false)

Returns

No return value (undefined)

Pin Class

(top)

This is the built-in class for Pins, such as D0,D1,LED1, or BTN

You can call the methods on Pin, or you can use Wiring-style functions such as digitalWrite

Methods and Fields

constructor Pin

(top)

Call type:

new Pin(value)

Description

Creates a pin from the given argument (or returns undefined if no argument)

Parameters

value A value to be converted to a pin. Can be a number, pin, or String.

Returns

A Pin object

function Pin.read

(top)

Call type:

function Pin.read()

Description

Returns the input state of the pin as a boolean

Parameters

No parameters

Returns

Whether pin is a logical 1 or 0

function Pin.reset

(top)

Call type:

function Pin.reset()

Description

Sets the output state of the pin to a 0

Parameters

No parameters

Returns

No return value (undefined)

function Pin.set

(top)

Call type:

function Pin.set()

Description

Sets the output state of the pin to a 1

Parameters

No parameters

Returns

No return value (undefined)

function Pin.write

(top)

Call type:

function Pin.write(value)

Description

Sets the output state of the pin to the parameter given

Parameters

value Whether to set output high (true/1) or low (false/0)

Returns

No return value (undefined)

function Pin.writeAtTime

(top)

Call type:

function Pin.writeAtTime(value, time)

Description

Sets the output state of the pin to the parameter given at the specified time. Note that this doesn't change the mode of the pin to an output. To do that, you need to use pin.write(0) or pinMode(pin, 'output').

Note: This is only available in some devices: not devices with low flash memory

Parameters

value Whether to set output high (true/1) or low (false/0)

time Time at which to write

Returns

No return value (undefined)

SPI Class

(top)

This class allows use of the built-in SPI ports. Currently it is SPI master only.

Instances

Methods and Fields

constructor SPI

(top)

Call type:

new SPI()

Description

Create a software SPI port. This has limited functionality (no baud rate), but it can work on any pins.

Parameters

No parameters

Returns

No return value (undefined)

function SPI.send

(top)

Call type:

function SPI.send(data, nss_pin)

Description

Send data down SPI, and return the result

Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.

For maximum speeds, please pass either Strings or Typed Arrays as arguments.

Parameters

data The data to send - either an integer, array, or string (which is the most efficient)

nss_pin An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised.

Returns

The data that was returned

function SPI.send4bit

(top)

Call type:

function SPI.send4bit(data, bit0, bit1, nss_pin)

Description

Send data down SPI, using 4 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols

Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.

Parameters

data The data to send - either an integer, array, or string

bit0 The 4 bits to send for a 0 (MSB first)

bit1 The 4 bits to send for a 1 (MSB first)

nss_pin An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised.

Returns

No return value (undefined)

function SPI.send8bit

(top)

Call type:

function SPI.send8bit(data, bit0, bit1, nss_pin)

Description

Send data down SPI, using 8 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols

Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.

Note: This is only available in some devices: not devices with low flash memory

Parameters

data The data to send - either an integer, array, or string

bit0 The 8 bits to send for a 0 (MSB first)

bit1 The 8 bits to send for a 1 (MSB first)

nss_pin An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised

Returns

No return value (undefined)

function SPI.setup

(top)

Call type:

function SPI.setup(options)

Description

Set up this SPI port as an SPI Master.

Parameters

options An optional structure containing extra information on initialising the SPI port
Please note that baud rate is set to the nearest that can be managed - which may be -+ 50%
{sck:pin, miso:pin, mosi:pin, baud:integer=100000, mode:integer=0, order:'msb'/'lsb'='msb' }
If sck,miso and mosi are left out, they will automatically be chosen. However if one or more is specified then the unspecified pins will not be set up.
You can find out which pins to use by looking at your board's reference page and searching for pins with the SPI marker.
The SPI mode is between 0 and 3 - see http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase
On
STM32F1-based parts, you cannot mix AF and non-AF pins (SPI pins are usually grouped on the chip - and you can't mix pins from two groups). Espruino will not warn you about this.

Returns

No return value (undefined)

function SPI.write

(top)

Call type:

function SPI.write(data, ...)

Description

Write a character or array of characters to SPI - without reading the result back.

For maximum speeds, please pass either Strings or Typed Arrays as arguments.

Parameters

data, ... One or more items to write. May be ints, strings, arrays, or objects of the form {data: ..., count:#}.
If the last argument is a pin, it is taken to be the NSS pin

Returns

No return value (undefined)

Serial Class

(top)

This class allows use of the built-in USARTs

Methods may be called on the USB, Serial1, Serial2, Serial3, Serial4, Serial5 and Serial6 objects. While different processors provide different numbers of USARTs, you can always rely on at least Serial1 and Serial2

Instances

Methods and Fields

function Serial.available

(top)

Call type:

function Serial.available()

Description

Return how many bytes are available to read. If there is already a listener for data, this will always return 0.

Parameters

No parameters

Returns

How many bytes are available

event Serial.data

(top)

Call type:

Serial.on('data', function(data) { ... });

Description

The 'data' event is called when data is received. If a handler is defined with X.on('data', function(data) { ... }) then it will be called, otherwise data will be stored in an internal buffer, where it can be retrieved with X.read()

Parameters

data A string containing one or more characters of received data

Returns

No return value (undefined)

function Serial.onData

(top)

Call type:

function Serial.onData(function)

Description

Serial.onData(func) has now been replaced with the event Serial.on(data, func)

Parameters

function

Returns

No return value (undefined)

function Serial.pipe

(top)

Call type:

function Serial.pipe(destination, options)

Description

Pipe this USART to a stream (an object with a 'write' method)

Note: This is only available in some devices: not devices with low flash memory

Parameters

destination The destination file/stream that will receive content from the source.

options An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished

Returns

No return value (undefined)

function Serial.print

(top)

Call type:

function Serial.print(string)

Description

Print a string to the serial port - without a line feed

Parameters

string A String to print

Returns

No return value (undefined)

function Serial.println

(top)

Call type:

function Serial.println(string)

Description

Print a line to the serial port (newline character sent are '

')

Parameters

string A String to print

Returns

No return value (undefined)

function Serial.read

(top)

Call type:

function Serial.read(chars)

Description

Return a string containing characters that have been received

Parameters

chars The number of characters to read, or undefined/0 for all available

Returns

A string containing the required bytes.

function Serial.setConsole

(top)

Call type:

function Serial.setConsole()

Description

Set this Serial port as the port for the console

Parameters

No parameters

Returns

No return value (undefined)

function Serial.setup

(top)

Call type:

function Serial.setup(baudrate, options)

Description

Setup this Serial port with the given baud rate and options.

If not specified in options, the default pins are used (usually the lowest numbered pins on the lowest port that supports this peripheral)

Parameters

baudrate The baud rate - the default is 9600

options An optional structure containing extra information on initialising the serial port.
{rx:pin,tx:pin,bytesize:8,parity:null/'none'/'o'/'odd'/'e'/'even',stopbits:1,flow:null/undefined/'none'/'xon'}
You can find out which pins to use by looking at your board's reference page and searching for pins with the UART/USART markers.
Note that even after changing the RX and TX pins, if you have called setup before then the previous RX and TX pins will still be connected to the Serial port as well - until you set them to something else using digitalWrite

Returns

No return value (undefined)

function Serial.write

(top)

Call type:

function Serial.write(data, ...)

Description

Write a character or array of characters to the serial port - without a line feed

Parameters

data, ... One or more items to write. May be ints, strings, arrays, or objects of the form {data: ..., count:#}.

Returns

No return value (undefined)

Server Class

(top)

The socket server created by require('net').createServer

Methods and Fields

function Server.close

(top)

Call type:

function Server.close()

Description

Stop listening for new connections

Parameters

No parameters

Returns

No return value (undefined)

function Server.listen

(top)

Call type:

function Server.listen(port)

Description

Start listening for new connections on the given port

Parameters

port The port to listen on

Returns

No return value (undefined)

Socket Class

(top)

An actual socket connection - allowing transmit/receive of TCP data

Methods and Fields

function Socket.available

(top)

Call type:

function Socket.available()

Description

Return how many bytes are available to read. If there is already a listener for data, this will always return 0.

Parameters

No parameters

Returns

How many bytes are available

event Socket.close

(top)

Call type:

Socket.on('close', function() { ... });

Description

Called when the connection closes.

Parameters

No parameters

Returns

No return value (undefined)

event Socket.data

(top)

Call type:

Socket.on('data', function(data) { ... });

Description

The 'data' event is called when data is received. If a handler is defined with X.on('data', function(data) { ... }) then it will be called, otherwise data will be stored in an internal buffer, where it can be retrieved with X.read()

Parameters

data A string containing one or more characters of received data

Returns

No return value (undefined)

event Socket.drain

(top)

Call type:

Socket.on('drain', function() { ... });

Description

An event that is fired when the buffer is empty and it can accept more data to send.

Parameters

No parameters

Returns

No return value (undefined)

function Socket.end

(top)

Call type:

function Socket.end(data)

Description

Close this socket - optional data to append as an argument

Parameters

data A string containing data to send

Returns

No return value (undefined)

function Socket.pipe

(top)

Call type:

function Socket.pipe(destination, options)

Description

Pipe this to a stream (an object with a 'write' method)

Note: This is only available in some devices: not devices with low flash memory

Parameters

destination The destination file/stream that will receive content from the source.

options An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished

Returns

No return value (undefined)

function Socket.read

(top)

Call type:

function Socket.read(chars)

Description

Return a string containing characters that have been received

Parameters

chars The number of characters to read, or undefined/0 for all available

Returns

A string containing the required bytes.

function Socket.write

(top)

Call type:

function Socket.write(data)

Parameters

data A string containing data to send

Returns

For note compatibility, the boolean false. When the send buffer is empty, a drain event will be sent

String Class

(top)

This is the built-in class for Text Strings.

Text Strings in Espruino are not zero-terminated, so you can store zeros in them.

Methods and Fields

constructor String

View MDN documentation

(top)

Call type:

new String(str, ...)

Description

Create a new String

Parameters

str, ... A value to turn into a string. If undefined or not supplied, an empty String is created.

Returns

A String

function String.charAt

View MDN documentation

(top)

Call type:

function String.charAt(pos)

Description

Return a single character at the given position in the String.

Parameters

pos The character number in the string. Negative values return characters from end of string (-1 = last char)

Returns

The character in the string

function String.charCodeAt

View MDN documentation

(top)

Call type:

function String.charCodeAt(pos)

Description

Return the integer value of a single character at the given position in the String.

Note that this returns 0 not 'NaN' for out of bounds characters

Parameters

pos The character number in the string. Negative values return characters from end of string (-1 = last char)

Returns

The integer value of a character in the string

String.fromCharCode

View MDN documentation

(top)

Call type:

String.fromCharCode(code, ...)

Description

Return the character(s) represented by the given character code(s).

Parameters

code, ... One or more character codes to create a string from (range 0-255).

Returns

The character

function String.indexOf

View MDN documentation

(top)

Call type:

function String.indexOf(substring, fromIndex)

Description

Return the index of substring in this string, or -1 if not found

Parameters

substring The string to search for

fromIndex Index to search from

Returns

The index of the string, or -1 if not found

function String.lastIndexOf

View MDN documentation

(top)

Call type:

function String.lastIndexOf(substring, fromIndex)

Description

Return the last index of substring in this string, or -1 if not found

Parameters

substring The string to search for

fromIndex Index to search from

Returns

The index of the string, or -1 if not found

property String.length

View MDN documentation

(top)

Call type:

property String.length

Description

Find the length of the string

Parameters

No parameters

Returns

The value of the string

function String.replace

View MDN documentation

(top)

Call type:

function String.replace(subStr, newSubStr)

Description

Search and replace ONE occurrance of subStr with newSubStr and return the result. This doesn't alter the original string. Regular expressions not supported.

Parameters

subStr The string to search for

newSubStr The string to replace it with

Returns

This string with subStr replaced

function String.slice

View MDN documentation

(top)

Call type:

function String.slice(start, end)

Parameters

start The start character index, if negative it is from the end of the string

end The end character index, if negative it is from the end of the string, and if omitted it is the end of the string

Returns

Part of this string from start for len characters

function String.split

View MDN documentation

(top)

Call type:

function String.split(separator)

Description

Return an array made by splitting this string up by the separator. eg.

'1,2,3'.split(',')==[1,2,3]

Parameters

separator The start character index

Returns

Part of this string from start for len characters

function String.substr

View MDN documentation

(top)

Call type:

function String.substr(start, len)

Parameters

start The start character index

len The number of characters

Returns

Part of this string from start for len characters

function String.substring

View MDN documentation

(top)

Call type:

function String.substring(start, end)

Parameters

start The start character index

end The end character index

Returns

The part of this string between start and end

function String.toLowerCase

View MDN documentation

(top)

Call type:

function String.toLowerCase()

Parameters

Returns

The lowercase version of this string

function String.toUpperCase

View MDN documentation

(top)

Call type:

function String.toUpperCase()

Parameters

Returns

The uppercase version of this string

function String.trim

View MDN documentation

(top)

Call type:

function String.trim()

Description

Return the integer value of a single character at the given position in the String.

Note that this returns 0 not 'NaN' for out of bounds characters

Parameters

No parameters

Returns

A String with Whitespace removed from the beginning and end

SyntaxError Class

(top)

The base class for syntax errors

Methods and Fields

constructor SyntaxError

View MDN documentation

(top)

Call type:

new SyntaxError(message)

Description

Creates a SyntaxError object

Parameters

message An optional message string

Returns

A SyntaxError object

function SyntaxError.toString

(top)

Call type:

function SyntaxError.toString()

Parameters

No parameters

Returns

A String

TypeError Class

(top)

The base class for type errors

Methods and Fields

constructor TypeError

View MDN documentation

(top)

Call type:

new TypeError(message)

Description

Creates a TypeError object

Parameters

message An optional message string

Returns

A TypeError object

Uint16Array Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Uint16Array

(top)

Call type:

new Uint16Array(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

Uint32Array Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Uint32Array

(top)

Call type:

new Uint32Array(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

Uint8Array Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Uint8Array

(top)

Call type:

new Uint8Array(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

Uint8ClampedArray Class

(top)

This is the built-in JavaScript class for a typed array.

Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).

Methods and Fields

constructor Uint8ClampedArray

View MDN documentation

(top)

Call type:

new Uint8ClampedArray(arr, byteOffset, length)

Description

Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.

Clamped arrays clamp their values to the allowed range, rather than 'wrapping'. e.g. after a[0]=12345;, a[0]==255.

Parameters

arr The array or typed array to base this off, or an integer which is the array length

byteOffset The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)

length The length (ONLY IF the first argument was an ArrayBuffer)

Returns

A typed array

WIZnet Class

(top)

Library for communication with the WIZnet Ethernet module

Methods and Fields

WIZnet.connect

(top)

Call type:

WIZnet.connect(spi, cs)

Description

Initialise the WIZnet module and return an Ethernet object

Parameters

spi Device to use for SPI (or undefined to use the default)

cs The pin to use for Chip Select

Returns

An Ethernet Object

WLAN Class

(top)

An instantiation of a WiFi network adaptor

Methods and Fields

function WLAN.connect

(top)

Call type:

function WLAN.connect(ap, key, callback)

Description

Connect to a wireless network

Parameters

ap Access point name

key WPA2 key (or undefined for unsecured connection)

callback Function to call back with connection status. It has one argument which is one of 'connect'/'disconnect'/'dhcp'

Returns

True if connection succeeded, false if it didn't.

function WLAN.disconnect

(top)

Call type:

function WLAN.disconnect()

Description

Completely uninitialise and power down the CC3000. After this you'll have to use

require("CC3000").connect() again.

Parameters

No parameters

Returns

No return value (undefined)

function WLAN.getIP

(top)

Call type:

function WLAN.getIP()

Description

Get the current IP address

Parameters

No parameters

Returns

See description above

function WLAN.reconnect

(top)

Call type:

function WLAN.reconnect()

Description

Completely uninitialise and power down the CC3000, then reconnect to the old access point.

Parameters

No parameters

Returns

No return value (undefined)

function WLAN.setIP

(top)

Call type:

function WLAN.setIP(options)

Description

Set the current IP address for get an IP from DHCP (if no options object is specified).

Note: Changes are written to non-volatile memory, but will only take effect after calling wlan.reconnect()

Parameters

options Object containing IP address options { ip : '1,2,3,4', subnet, gateway, dns }, or do not supply an object in otder to force DHCP.

Returns

True on success

Waveform Class

(top)

This class handles waveforms. In Espruino, a Waveform is a set of data that you want to input or output.

Methods and Fields

constructor Waveform

(top)

Call type:

new Waveform(samples, options)

Description

Create a waveform class. This allows high speed input and output of waveforms. It has an internal variable called buffer (as well as buffer2 when double-buffered - see options below) which contains the data to input/output.

When double-buffered, a 'buffer' event will be emitted each time a buffer is finished with (the argument is that buffer). When the recording stops, a 'finish' event will be emitted (with the first argument as the buffer).

Note: This is only available in some devices: not devices with low flash memory

Parameters

samples The number of samples

options Optional options struct {doubleBuffer:bool, bits : 8/16} where: doubleBuffer is whether to allocate two buffers or not (default false), and bits is the amount of bits to use (default 8).

Returns

An Waveform object

function Waveform.startInput

(top)

Call type:

function Waveform.startInput(output, freq, options)

Description

Will start inputting the waveform on the given pin that supports analog. If not repeating, it'll emit a finish event when it is done.

Note: This is only available in some devices: not devices with low flash memory

Parameters

output The pin to output on

freq The frequency to output each sample at

options Optional options struct {time:float,repeat:bool} where: time is the that the waveform with start output at, e.g. getTime()+1 (otherwise it is immediate), repeat is a boolean specifying whether to repeat the give sample

Returns

No return value (undefined)

function Waveform.startOutput

(top)

Call type:

function Waveform.startOutput(output, freq, options)

Description

Will start outputting the waveform on the given pin - the pin must have previously been initialised with analogWrite. If not repeating, it'll emit a finish event when it is done.

Note: This is only available in some devices: not devices with low flash memory

Parameters

output The pin to output on

freq The frequency to output each sample at

options Optional options struct {time:float,repeat:bool} where: time is the that the waveform with start output at, e.g. getTime()+1 (otherwise it is immediate), repeat is a boolean specifying whether to repeat the give sample

Returns

No return value (undefined)

function Waveform.stop

(top)

Call type:

function Waveform.stop()

Description

Stop a waveform that is currently outputting

Note: This is only available in some devices: not devices with low flash memory

Parameters

No parameters

Returns

No return value (undefined)

console Class

(top)

An Object that contains functions for writing to the interactive console

Methods and Fields

console.log

(top)

Call type:

console.log(text, ...)

Description

Print the supplied string(s) to the console

Note: If you're connected to a computer (not a wall adaptor) via USB but you are not running a terminal app then when you print data Espruino may pause execution and wait until the computer requests the data it is trying to print.

Parameters

text, ... One or more arguments to print

Returns

No return value (undefined)

fs Class

(top)

This library handles interfacing with a FAT32 filesystem on an SD card. The API is designed to be similar to node.js's - However Espruino does not currently support asynchronous file IO, so the functions behave like node.js's xxxxSync functions. Versions of the functions with 'Sync' after them are also provided for compatibility.

Currently this provides minimal file IO - it's great for logging and loading/saving settings, but not good for loading large amounts of data as you will soon fill your memory up.

It is currently only available on boards that contain an SD card slot, such as the Olimexino and the HY. It can not currently be added to boards that did not ship with a card slot.

To use this, you must type

var fs = require('fs') to get access to the library

Methods and Fields

fs.appendFile

(top)

Call type:

fs.appendFile(path, data)

Description

Append the data to the given file, created a new file if it doesn't exist

NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.

Parameters

path The path of the file to write

data The data to write to the file

Returns

True on success, false on failure

fs.appendFileSync

(top)

Call type:

fs.appendFileSync(path, data)

Description

Append the data to the given file, created a new file if it doesn't exist

Note: This is only available in some devices: not devices with low flash memory

Parameters

path The path of the file to write

data The data to write to the file

Returns

True on success, false on failure

fs.pipe

(top)

Call type:

fs.pipe(source, destination, options)

Parameters

source The source file/stream that will send content.

destination The destination file/stream that will receive content from the source.

options An optional object { chunkSize : int=64, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished

Returns

No return value (undefined)

fs.readFile

(top)

Call type:

fs.readFile(path)

Description

Read all data from a file and return as a string

NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.

Parameters

path The path of the file to read

Returns

A string containing the contents of the file (or undefined if the file doesn't exist)

fs.readFileSync

(top)

Call type:

fs.readFileSync(path)

Description

Read all data from a file and return as a string.

Note: The size of files you can load using this method is limited by the amount of available RAM. To read files a bit at a time, see the File class.

Note: This is only available in some devices: not devices with low flash memory

Parameters

path The path of the file to read

Returns

A string containing the contents of the file (or undefined if the file doesn't exist)

fs.readdir

(top)

Call type:

fs.readdir(path)

Description

List all files in the supplied directory, returning them as an array of strings.

NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.

Parameters

path The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory

Returns

An array of filename strings (or undefined if the directory couldn't be listed)

fs.readdirSync

(top)

Call type:

fs.readdirSync(path)

Description

List all files in the supplied directory, returning them as an array of strings.

Note: This is only available in some devices: not devices with low flash memory

Parameters

path The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory

Returns

An array of filename strings (or undefined if the directory couldn't be listed)

fs.statSync

(top)

Call type:

fs.statSync(path)

Description

Return information on the given file. This returns an object with the following

fields:

size: size in bytes

dir: a boolean specifying if the file is a directory or not

mtime: A Date structure specifying the time the file was last modified

Note: This is only available in some devices: not devices with low flash memory

Parameters

path The path of the file to get information on

Returns

An object describing the file, or undefined on failure

fs.unlink

(top)

Call type:

fs.unlink(path)

Description

Delete the given file

NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.

Note: This is only available in some devices: not devices with low flash memory

Parameters

path The path of the file to delete

Returns

True on success, or false on failure

fs.unlinkSync

(top)

Call type:

fs.unlinkSync(path)

Description

Delete the given file

Note: This is only available in some devices: not devices with low flash memory

Parameters

path The path of the file to delete

Returns

True on success, or false on failure

fs.writeFile

(top)

Call type:

fs.writeFile(path, data)

Description

Write the data to the given file

NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.

Parameters

path The path of the file to write

data The data to write to the file

Returns

True on success, false on failure

fs.writeFileSync

(top)

Call type:

fs.writeFileSync(path, data)

Description

Write the data to the given file

Note: This is only available in some devices: not devices with low flash memory

Parameters

path The path of the file to write

data The data to write to the file

Returns

True on success, false on failure

hashlib Class

(top)

Note: This library is currently only included in builds for the original Espruino boards.

For other boards you will have to make build your own firmware.

Methods and Fields

hashlib.sha224

(top)

Call type:

hashlib.sha224(message)

Parameters

message message to hash

Returns

Returns a new HASH SHA224 Object

hashlib.sha256

(top)

Call type:

hashlib.sha256(message)

Parameters

message message to hash

Returns

Returns a new HASH SHA256 Object

http Class

(top)

This library allows you to create http servers and make http requests

In order to use this, you will need an extra module to get network connectivity such as the TI CC3000 or WIZnet W5500.

This is designed to be a cut-down version of the node.js library. Please see the Internet page for more information on how to use it.

Methods and Fields

http.createServer

(top)

Call type:

http.createServer(callback)

Description

Create an HTTP Server

When a request to the server is made, the callback is called. In the callback you can use the methods on the response (httpSRs) to send data. You can also add request.on('data',function() { ... }) to listen for POSTed data

Parameters

callback A function(request,response) that will be called when a connection is made

Returns

Returns a new httpSrv object

http.get

(top)

Call type:

http.get(options, callback)

Description

Create an HTTP Request - convenience function for

http.request(). options.method is set to 'get', and end is called automatically. See the Internet page for more usage examples.

Parameters

options An object containing host,port,path,method fields

callback A function(res) that will be called when a connection is made. You can then call res.on('data', function(data) { ... }) and res.on('close', function() { ... }) to deal with the response.

Returns

Returns a new httpCRq object

http.request

(top)

Call type:

http.request(options, callback)

Description

Create an HTTP Request - end() must be called on it to complete the operation

Parameters

options An object containing host,port,path,method,headers fields

callback A function(res) that will be called when a connection is made. You can then call res.on('data', function(data) { ... }) and res.on('close', function() { ... }) to deal with the response.

Returns

Returns a new httpCRq object

httpCRq Class

(top)

The HTTP client request

Methods and Fields

event httpCRq.drain

(top)

Call type:

httpCRq.on('drain', function() { ... });

Description

An event that is fired when the buffer is empty and it can accept more data to send.

Parameters

No parameters

Returns

No return value (undefined)

function httpCRq.end

(top)

Call type:

function httpCRq.end(data)

Description

Finish this HTTP request - optional data to append as an argument

Parameters

data A string containing data to send

Returns

No return value (undefined)

function httpCRq.write

(top)

Call type:

function httpCRq.write(data)

Parameters

data A string containing data to send

Returns

For note compatibility, the boolean false. When the send buffer is empty, a drain event will be sent

httpCRs Class

(top)

The HTTP client response

Methods and Fields

function httpCRs.available

(top)

Call type:

function httpCRs.available()

Description

Return how many bytes are available to read. If there is already a listener for data, this will always return 0.

Parameters

No parameters

Returns

How many bytes are available

event httpCRs.close

(top)

Call type:

httpCRs.on('close', function() { ... });

Description

Called when the connection closes.

Parameters

No parameters

Returns

No return value (undefined)

event httpCRs.data

(top)

Call type:

httpCRs.on('data', function(data) { ... });

Description

The 'data' event is called when data is received. If a handler is defined with X.on('data', function(data) { ... }) then it will be called, otherwise data will be stored in an internal buffer, where it can be retrieved with X.read()

Parameters

data A string containing one or more characters of received data

Returns

No return value (undefined)

function httpCRs.pipe

(top)

Call type:

function httpCRs.pipe(destination, options)

Description

Pipe this to a stream (an object with a 'write' method)

Note: This is only available in some devices: not devices with low flash memory

Parameters

destination The destination file/stream that will receive content from the source.

options An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished

Returns

No return value (undefined)

function httpCRs.read

(top)

Call type:

function httpCRs.read(chars)

Description

Return a string containing characters that have been received

Parameters

chars The number of characters to read, or undefined/0 for all available

Returns

A string containing the required bytes.

httpSRq Class

(top)

The HTTP server request

Methods and Fields

function httpSRq.available

(top)

Call type:

function httpSRq.available()

Description

Return how many bytes are available to read. If there is already a listener for data, this will always return 0.

Parameters

No parameters

Returns

How many bytes are available

event httpSRq.close

(top)

Call type:

httpSRq.on('close', function() { ... });

Description

Called when the connection closes.

Parameters

No parameters

Returns

No return value (undefined)

event httpSRq.data

(top)

Call type:

httpSRq.on('data', function(data) { ... });

Description

The 'data' event is called when data is received. If a handler is defined with X.on('data', function(data) { ... }) then it will be called, otherwise data will be stored in an internal buffer, where it can be retrieved with X.read()

Parameters

data A string containing one or more characters of received data

Returns

No return value (undefined)

function httpSRq.pipe

(top)

Call type:

function httpSRq.pipe(destination, options)

Description

Pipe this to a stream (an object with a 'write' method)

Note: This is only available in some devices: not devices with low flash memory

Parameters

destination The destination file/stream that will receive content from the source.

options An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished

Returns

No return value (undefined)

function httpSRq.read

(top)

Call type:

function httpSRq.read(chars)

Description

Return a string containing characters that have been received

Parameters

chars The number of characters to read, or undefined/0 for all available

Returns

A string containing the required bytes.

httpSRs Class

(top)

The HTTP server response

Methods and Fields

event httpSRs.close

(top)

Call type:

httpSRs.on('close', function() { ... });

Description

Called when the connection closes.

Parameters

No parameters

Returns

No return value (undefined)

event httpSRs.drain

(top)

Call type:

httpSRs.on('drain', function() { ... });

Description

An event that is fired when the buffer is empty and it can accept more data to send.

Parameters

No parameters

Returns

No return value (undefined)

function httpSRs.end

(top)

Call type:

function httpSRs.end(data)

Parameters

data A string containing data to send

Returns

No return value (undefined)

function httpSRs.write

(top)

Call type:

function httpSRs.write(data)

Parameters

data A string containing data to send

Returns

For note compatibility, the boolean false. When the send buffer is empty, a drain event will be sent

function httpSRs.writeHead

(top)

Call type:

function httpSRs.writeHead(statusCode, headers)

Parameters

statusCode The HTTP status code

headers An object containing the headers

Returns

No return value (undefined)

httpSrv Class

(top)

The HTTP server created by require('http').createServer

Methods and Fields

function httpSrv.close

(top)

Call type:

function httpSrv.close()

Description

Stop listening for new HTTP connections

Parameters

No parameters

Returns

No return value (undefined)

function httpSrv.listen

(top)

Call type:

function httpSrv.listen(port)

Description

Start listening for new HTTP connections on the given port

Parameters

port The port to listen on

Returns

No return value (undefined)

net Class

(top)

This library allows you to create TCPIP servers and clients

In order to use this, you will need an extra module to get network connectivity.

This is designed to be a cut-down version of the node.js library. Please see the Internet page for more information on how to use it.

Methods and Fields

net.connect

(top)

Call type:

net.connect(options, callback)

Description

Create a socket connection

Parameters

options An object containing host,port fields

callback A function(res) that will be called when a connection is made. You can then call res.on('data', function(data) { ... }) and res.on('close', function() { ... }) to deal with the response.

Returns

Returns a new net.Socket object

net.createServer

(top)

Call type:

net.createServer(callback)

Description

Create a Server

When a request to the server is made, the callback is called. In the callback you can use the methods on the connection to send data. You can also add connection.on('data',function() { ... }) to listen for received data

Parameters

callback A function(connection) that will be called when a connection is made

Returns

Returns a new Server Object

process Class

(top)

This class contains information about Espruino itself

Methods and Fields

process.env

(top)

Call type:

process.env

Description

Returns an Object containing various pre-defined variables. standard ones are BOARD, VERSION

Parameters

No parameters

Returns

An object

process.memory

(top)

Call type:

process.memory()

Description

Run a Garbage Collection pass, and return an object containing information on memory usage.

free : Memory that is available to be used

usage : Memory that has been used

total : Total memory

history : Memory used for command history - that is freed if memory is low. Note that this is INCLUDED in the figure for 'free'

stackEndAddress : (on ARM) the address (that can be used with peek/poke/etc) of the END of the stack. The stack grows down, so unless you do a lot of recursion the bytes above this can be used.

Memory units are specified in 'blocks', which are around 16 bytes each (depending on your device). See http://www.espruino.com/Performance for more information.

Parameters

No parameters

Returns

Information about memory usage

process.version

(top)

Call type:

process.version

Description

Returns the version of Espruino as a String

Parameters

No parameters

Returns

The version of Espruino

tv Class

(top)

This library provides TV out capability on the Espruino and Espruino Pico.

See the [[Television]] page for more information.

Methods and Fields

tv.setup

(top)

Call type:

tv.setup(options, width)

Description

This initialises the TV output. Options for PAL are as follows:

var g = require('tv').setup({ type : "pal",
  video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
  sync : A6, // Pin - Timer pin to use for video sync
  width : 384,
  height : 270, // max 270
});

and for VGA:

var g = require('tv').setup({ type : "vga",
  video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
  hsync : A6, // Pin - Timer pin to use for video sync
  vsync : A5, // Pin - pin to use for video sync
  width : 220,
  height : 480,
});

See the [[Television]] page for more information.

Parameters

options Various options for the TV output

width

Returns

A graphics object

url Class

(top)

This class helps to convert URLs into Objects of information ready for http.request/get

Methods and Fields

url.parse

(top)

Call type:

url.parse(urlStr, parseQuery)

Description

A utility function to split a URL into parts

This is useful in web servers for instance when handling a request.

For instance url.parse("/a?b=c&d=e",true) returns {"method":"GET","host":"","path":"/a?b=c&d=e","pathname":"/a","search":"?b=c&d=e","port":80,"query":{"b":"c","d":"e"}}

Parameters

urlStr A URL to be parsed

parseQuery Whether to parse the query string into an object not (default = false)

Returns

An object containing options for http.request or http.get. Contains method, host, path, pathname, search, port and query