Version 1v98
function acceleration()
Note: This function is only available on the BBC micro:bit board
Get the current acceleration of the micro:bit from the on-board accelerometer
An object with x, y, and z fields in it
function analogRead(pin)
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)
Note: if you didn't call pinMode
beforehand then this function will also reset pin's state to "analog"
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.
The analog Value of the Pin between 0 and 1
This function is used in the following places in Espruino's documentation
function analogWrite(pin, value, options)
Set the analog Value of a pin. It will be output using PWM.
Objects can contain:
freq
- pulse frequency in Hz, eg. analogWrite(A0,0.5,{ freq : 10 });
- specifying a frequency will force PWM output, even if the pin has a DACsoft
- boolean, If true software PWM is used if available.forceSoft
- boolean, If true software PWM is used evenNote: if you didn't call pinMode
beforehand then this function will also reset pin's state to "output"
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 for analog output - see below
This function is used in the following places in Espruino's documentation
variable arguments
A variable containing the arguments given to the function:
function hello() {
console.log(arguments.length, JSON.stringify(arguments));
}
hello() // 0 []
hello("Test") // 1 ["Test"]
hello(1,2,3) // 3 [1,2,3]
Note: Due to the way Espruino works this is doesn't behave exactly
the same as in normal JavaScript. The length of the arguments array
will never be less than the number of arguments specified in the
function declaration: (function(a){ return arguments.length; })() == 1
.
Normal JavaScript interpreters would return 0
in the above case.
An array containing all the arguments given to the function
function atob(base64Data)
Decode the supplied base64 string into a normal string
Note: This is not available in devices with low flash memory
base64Data
- A string of base64 data to decode
A string containing the decoded data
This function is used in the following places in Espruino's documentation
Serial
The Bluetooth Serial port - used when data is sent or received over Bluetooth Smart on nRF51/nRF52 chips.
Note: This is only available in devices with Bluetooth LE capability
function btoa(binaryData)
Encode the supplied string (or array) into a base64 string
Note: This is not available in devices with low flash memory
binaryData
- A string of data to encode
A base64 encoded string
function changeInterval(id, time)
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 immediately and resets the timeout, so in the example above,
regardless of when you call changeInterval
, the next interval will occur 1500ms
after it.
id
- The id returned by a previous call to setInterval
time
- The new time period in ms
This function is used in the following places in Espruino's documentation
function clearInterval(id)
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
id
- The id returned by a previous call to setInterval
This function is used in the following places in Espruino's documentation
function clearTimeout(id)
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
id
- The id returned by a previous call to setTimeout
This function is used in the following places in Espruino's documentation
function clearWatch(id)
Clear the Watch that was created with setWatch. If no parameter is supplied, all watches will be removed.
id
- The id returned by a previous call to setWatch
This function is used in the following places in Espruino's documentation
function compass()
Note: This function is only available on the BBC micro:bit board
Get the current compass position for the micro:bit from the on-board magnetometer
An object with x, y, and z fields in it
This function is used in the following places in Espruino's documentation
function decodeURIComponent(str)
Convert any groups of characters of the form '%ZZ', into characters with hex code '0xZZ'
Note: This is not available in devices with low flash memory
str
- A string to decode from a URI
A string containing the decoded data
function digitalPulse(pin, value, time)
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
Note: if you didn't call pinMode
beforehand then this function will also reset pin's state to "output"
digitalPulse is for SHORT pulses that need to be very accurate. If you're doing anything over a few milliseconds, use setTimeout instead.
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')
This function is used in the following places in Espruino's documentation
function digitalRead(pin)
Get the digital value of the given pin.
Note: if you didn't call pinMode
beforehand then this function will also reset pin's state to "input"
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
If the pin argument is an object with a read
method, the read
method will be called and the integer value it returns
passed back.
pin
- The pin to use
The digital Value of the Pin
This function is used in the following places in Espruino's documentation
function digitalWrite(pin, value)
Set the digital value of the given pin.
Note: if you didn't call pinMode
beforehand then this function will also reset pin's state to "output"
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 least 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.
If the pin argument is an object with a write
method, the write
method will
be called with the value passed through.
pin
- The pin to use
value
- Whether to pulse high (true) or low (false)
This function is used in the following places in Espruino's documentation
function dump()
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.
Note: This is not available in devices with low flash memory
function echo(echoOn)
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.
echoOn
-
function edit(funcName)
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.
funcName
- The name of the function to edit (either a string or just the unquoted name)
This function is used in the following places in Espruino's documentation
function encodeURIComponent(str)
Convert a string with any character not alphanumeric or - _ . ! ~ * ' ( )
converted to the form %XY
where XY
is its hexadecimal representation
Note: This is not available in devices with low flash memory
str
- A string to encode as a URI
A string containing the encoded data
This function is used in the following places in Espruino's documentation
function eval(code)
Evaluate a string containing JavaScript code
code
-
The result of evaluating the string
This function is used in the following places in Espruino's documentation
function getPinMode(pin)
Return the current mode of the given pin. See pinMode
for more information on returned values.
Note: This is not available in devices with low flash memory
pin
- The pin to check
The pin mode, as a string
function getSerial()
Get the serial number of this board
The board's serial number
function getTime()
Return the current system time in Seconds (as a floating point number)
See description above
This function is used in the following places in Espruino's documentation
variable global
A reference to the global scope, where everything is defined.
The global scope
variable HIGH
Logic 1 for Arduino compatibility - this is the same as just typing 1
I2C
The first I2C port
Note: This is only available in devices with more than 1 I2C peripherals
I2C
The second I2C port
Note: This is only available in devices with more than 2 I2C peripherals
I2C
The third I2C port
Note: This is only available in devices with more than 3 I2C peripherals
variable Infinity
Positive Infinity (1/0)
function isNaN(x)
Whether the x is NaN (Not a Number) or not
x
-
True is the value is NaN, false if not.
function load()
Restart and load the program out of flash - this has an effect similar to completely rebooting Espruino (power off/power on), but without actually performing a full reset of the hardware.
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), add an init
event handler to E
with
E.on('init', function() { ... your_code ... });
. This will then be automatically
executed by Espruino every time it starts.
Serial
A loopback serial device. Data sent to LoopbackA comes out of LoopbackB and vice versa
Serial
A loopback serial device. Data sent to LoopbackA comes out of LoopbackB and vice versa
variable LOW
Logic 0 for Arduino compatibility - this is the same as just typing 0
variable NaN
Not a Number
function parseFloat(string)
Convert a string representing a number into an float
string
-
The value of the string
This function is used in the following places in Espruino's documentation
function parseInt(string, radix)
Convert a string representing a number into an integer
string
-
radix
- The Radix of the string (optional)
The integer value of the string (or NaN)
This function is used in the following places in Espruino's documentation
function peek16(addr, count)
Read 16 bits of memory at the given location - DANGEROUS!
addr
- The address in memory to read
count
- (optional) the number of items to read. If >1 a Uint16Array will be returned.
The value of memory at the given location
This function is used in the following places in Espruino's documentation
function peek32(addr, count)
Read 32 bits of memory at the given location - DANGEROUS!
addr
- The address in memory to read
count
- (optional) the number of items to read. If >1 a Uint32Array will be returned.
The value of memory at the given location
This function is used in the following places in Espruino's documentation
function peek8(addr, count)
Read 8 bits of memory at the given location - DANGEROUS!
addr
- The address in memory to read
count
- (optional) the number of items to read. If >1 a Uint8Array will be returned.
The value of memory at the given location
function pinMode(pin, mode, automatic)
Set the mode of the given pin.
auto
/undefined
- Don't change state, but allow digitalWrite
/etc to automatically change state as appropriateanalog
- Analog inputinput
- Digital inputinput_pullup
- Digital input with internal ~40k pull-up resistorinput_pulldown
- Digital input with internal ~40k pull-down resistoroutput
- Digital outputopendrain
- Digital output that only ever pulls down to 0v. Sending a logical 1
leaves the pin open circuitopendrain_pullup
- Digital output that pulls down to 0v. Sending a logical 1
enables internal ~40k pull-up resistoraf_output
- Digital output from built-in peripheralaf_opendrain
- Digital output from built-in peripheral that only ever pulls down to 0v. Sending a logical 1
leaves the pin open circuitNote: digitalRead
/digitalWrite
/etc set the pin mode 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)
), auto
as the argument (pinMode(pin, "auto")
), or with the 3rd 'automatic'
argument set to true (pinMode(pin, "output", true)
).
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 or use 'auto' if you want to revert to automatic pin mode setting.
automatic
- Optional, default is false. If true, subsequent commands will automatically change the state (see notes below)
This function is used in the following places in Espruino's documentation
function poke16(addr, value)
Write 16 bits of memory at the given location - VERY DANGEROUS!
addr
- The address in memory to write
value
- The value to write, or an array of values
This function is used in the following places in Espruino's documentation
function poke32(addr, value)
Write 32 bits of memory at the given location - VERY DANGEROUS!
addr
- The address in memory to write
value
- The value to write, or an array of values
This function is used in the following places in Espruino's documentation
function poke8(addr, value)
Write 8 bits of memory at the given location - VERY DANGEROUS!
addr
- The address in memory to write
value
- The value to write, or an array of values
function print(text, ...)
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.
text, ...
-
This function is used in the following places in Espruino's documentation
function require(moduleName)
Load the given module, and return the exported functions
moduleName
- A String containing the name of the given module
The result of evaluating the string
This function is used in the following places in Espruino's documentation
function reset(clearFlash)
Reset the interpreter - clear program memory in RAM, 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.
If reset()
is called with no arguments, it will reset the board's state in
RAM but will not reset the state in flash. When next powered on (or when
load()
is called) the board will load the previously saved code.
Calling reset(true)
will cause all saved code in flash memory to
be cleared as well.
clearFlash
- Remove saved code from flash as well
This function is used in the following places in Espruino's documentation
function save()
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), add an init
event handler to E
with
E.on('init', function() { ... your_code ... });
. This will then be automatically
executed by Espruino every time it starts.
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.
variable SCL
The pin marked SDA on the Arduino pin footprint. This is connected directly to pin A5.
Note: This is only available in Pixl.js boards
See description above
variable SDA
The pin marked SDA on the Arduino pin footprint. This is connected directly to pin A4.
Note: This is only available in Pixl.js boards
See description above
Serial
The first Serial (USART) port
Note: This is only available in devices with more than 1 USART peripherals
Serial
The second Serial (USART) port
Note: This is only available in devices with more than 2 USART peripherals
Serial
The third Serial (USART) port
Note: This is only available in devices with more than 3 USART peripherals
Serial
The fourth Serial (USART) port
Note: This is only available in devices with more than 4 USART peripherals
Serial
The fifth Serial (USART) port
Note: This is only available in devices with more than 5 USART peripherals
Serial
The sixth Serial (USART) port
Note: This is only available in devices with more than 6 USART peripherals
function setBusyIndicator(pin)
When Espruino is busy, set the pin specified here high. Set this to undefined to disable the feature.
Note: This is not available in devices with low flash memory
pin
-
function setDeepSleep(sleep)
Set whether we can enter deep sleep mode, which reduces power consumption to around 100uA. This only works on STM32 Espruino Boards (nRF52 boards sleep automatically).
Please see http://www.espruino.com/Power+Consumption for more details on this.
Note: This is only available in STM32 devices (including Espruino Original, Pico and WiFi) and EFM32 devices
sleep
-
This function is used in the following places in Espruino's documentation
function setInterval(function, timeout, args, ...)
Call the function (or evaluate the string) specified REPEATEDLY after the timeout in milliseconds.
For instance:
setInterval(function () {
console.log("Hello World");
}, 1000);
// or
setInterval('console.log("Hello World");', 1000);
// both print 'Hello World' every second
You can also specify extra arguments that will be sent to the function when it is executed. For example:
setInterval(function (a,b) {
console.log(a+" "+b);
}, 1000, "Hello", "World");
// prints 'Hello World' every second
If you want to stop your function from being called, pass the number that
was returned by setInterval
into the clearInterval
function.
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.
function
- A Function or String to be executed
timeout
- The time between calls to the function (max 3153600000000 = 100 years
args, ...
- Optional arguments to pass to the function when executed
An ID that can be passed to clearInterval
function setSleepIndicator(pin)
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.
Note: This is not available in devices with low flash memory
pin
-
This function is used in the following places in Espruino's documentation
function setTime(time)
Set the current system time in seconds (to the nearest second).
This is used with getTime
, the time reported from setWatch
, as
well as when using new Date()
.
To set the timezone for all new Dates, use E.setTimeZone(hours)
.
time
-
function setTimeout(function, timeout, args, ...)
Call the function (or evaluate the string) specified ONCE after the timeout in milliseconds.
For instance:
setTimeout(function () {
console.log("Hello World");
}, 1000);
// or
setTimeout('console.log("Hello World");', 1000);
// both print 'Hello World' after a second
You can also specify extra arguments that will be sent to the function when it is executed. For example:
setTimeout(function (a,b) {
console.log(a+" "+b);
}, 1000, "Hello", "World");
// prints 'Hello World' after 1 second
If you want to stop the function from being called, pass the number that
was returned by setTimeout
into the clearInterval
function.
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.
function
- A Function or String to be executed
timeout
- The time until the function will be executed (max 3153600000000 = 100 years
args, ...
- Optional arguments to pass to the function when executed
An ID that can be passed to clearTimeout
function setWatch(function, pin, options)
Call the function specified when the pin changes. Watches set with setWatch
can be removed using clearWatch
.
If the options
parameter is an object, it can contain the following information (all optional):
{
// Whether to keep producing callbacks, or remove the watch after the first callback
repeat: true/false(default),
// Trigger on the rising or falling edge of the signal. Can be a string, or 1='rising', -1='falling', 0='both'
edge:'rising'(default for built-in buttons)/'falling'/'both'(default for pins),
// Use software-debouncing to stop multiple calls if a switch bounces
// This is the time in milliseconds to wait for bounces to subside, or 0 to disable
debounce:10 (0 is default for pins, 25 is default for built-in buttons),
// Advanced: If the function supplied is a 'native' function (compiled or assembly)
// setting irq:true will call that function in the interrupt itself
irq : false(default)
// Advanced: If specified, the given pin will be read whenever the watch is called
// and the state will be included as a 'data' field in the callback
data : pin
}
The function
callback is called with an argument, which is an object of type {state:bool, time:float, lastTime:float}
.
state
is whether the pin is currently a 1
or a 0
time
is the time in seconds at which the pin changed statelastTime
is the time in seconds at which the pin last changed state. When using edge:'rising'
or edge:'falling'
, this is not the same as when the function was last called.data
is included if data:pin
was specified in the options, and can be used for reading in clocked dataFor 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' });
.
This will only be called on the falling edge of the pulse, but will be able to measure the width of the pulse because e.lastTime
is the time of the rising edge.
Internally, an interrupt writes the time of the pin's state change into a queue with the exact
time that it happened, and the function supplied to setWatch
is executed only from the main
message loop. However, if the callback is a native function void (bool state)
then you can
add irq:true
to options, which will cause the function to be called from within the IRQ.
When doing this, interrupts will happen on both edges and there will be no debouncing.
Note: if you didn't call pinMode
beforehand then this function will reset pin's state to "input"
Note: The STM32 chip (used in the Espruino Board and Pico) cannot
watch two pins with the same number - eg A0
and B0
.
function
- A Function or String to be executed
pin
- The pin to watch
options
- If a boolean or integer, it determines whether to call this once (false = default) or every time a change occurs (true). Can be an object of the form { repeat: true/false(default), edge:'rising'/'falling'/'both'(default), debounce:10}
- see below for more information.
An ID that can be passed to clearWatch
function shiftOut(pins, options, data)
Shift an array of data out using the pins supplied least significant bit first, for example:
// shift out to single clk+data
shiftOut(A0, { clk : A1 }, [1,0,1,0]);
// shift out a whole byte (like software SPI)
shiftOut(A0, { clk : A1, repeat: 8 }, [1,2,3,4]);
// shift out via 4 data pins
shiftOut([A3,A2,A1,A0], { clk : A4 }, [1,2,3,4]);
options
is an object of the form:
{
clk : pin, // a pin to use as the clock (undefined = no pin)
clkPol : bool, // clock polarity - default is 0 (so 1 normally, pulsing to 0 to clock data in)
repeat : int, // number of clocks per array item
}
Each item in the data
array will be output to the pins, with the first
pin in the array being the MSB and the last the LSB, then the clock will be
pulsed in the polarity given.
repeat
is the amount of times shift data out for each array item. For instance
we may want to shift 8 bits out through 2 pins - in which case we need to set
repeat to 4.
pins
- A pin, or an array of pins to use
options
- Options, for instance the clock (see below)
data
- The data to shift out
function show(image)
Note: This function is only available on the BBC micro:bit board
Show an image on the in-built 5x5 LED screen.
Image can be:
5
or 0x1FFFFFF
show("10001")
. Newlines are ignored, and anything that is not
a space or 0
is treated as a 1.show([1,2,3,0])
For instance the following works for images:
show("# #"+
" # "+
" # "+
"# #"+
" ### ")
This means you can also use Espruino's graphics library:
var g = Graphics.createArrayBuffer(5,5,1)
g.drawString("E",0,0)
show(g.buffer)
image
- The image to show
SPI
The first SPI port
Note: This is only available in devices with more than 1 SPI peripherals
SPI
The second SPI port
Note: This is only available in devices with more than 2 SPI peripherals
SPI
The third SPI port
Note: This is only available in devices with more than 3 SPI peripherals
Serial
A telnet serial device that maps to the built-in telnet console server (devices that have built-in wifi only).
Note: This is only available in devices with Telnet enabled (Linux, ESP8266 and ESP32)
Serial
A simple VT100 terminal emulator.
When data is sent to this, it searches for a Graphics variable called either
g
or LCD
and starts writing characters to it.
Note: This is only available in devices with VT100 terminal emulation enabled (Pixl.js only)
function trace(root)
Output debugging information
Note: This is not included on boards with low amounts of flash memory, or the Espruino board.
Note: This is not available in devices with low flash memory
root
- The symbol to output (optional). If nothing is specified, everything will be output
Serial
The USB Serial port
Note: This is only available in devices with USB
Class containing AES encryption/decryption
Note: This library is currently only included in builds for the Espruino Pico and Espruino WiFi. For other boards you will have to make build your own firmware, and you may need to remove other features in order to make room.
AES.decrypt(passphrase, key, options)
passphrase
- Message to decrypt
key
- Key to encrypt message - must be an ArrayBuffer of 128, 192, or 256 BITS
options
- An optional object, may specify { iv : new Uint8Array(16), mode : 'CBC|CFB|CTR|OFB|ECB' }
Returns an ArrayBuffer
AES.encrypt(passphrase, key, options)
passphrase
- Message to encrypt
key
- Key to encrypt message - must be an ArrayBuffer of 128, 192, or 256 BITS
options
- An optional object, may specify { iv : new Uint8Array(16), mode : 'CBC|CFB|CTR|OFB|ECB' }
Returns an ArrayBuffer
This is the built-in JavaScript class for arrays.
Arrays can be defined with []
, new Array()
, or new Array(length)
new Array(args, ...)
Create an Array. Either give it one integer argument (>=0) which is the length of the array, or any number of arguments
args, ...
- The length of the array OR any number of items to add to the array
An Array
function Array.concat(args, ...)
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 not available in devices with low flash memory
args, ...
- Any items to add to the array
An Array
function Array.every(function, thisArg)
Return 'true' if the callback returns 'true' for every element in the array
function
- Function to be executed
thisArg
- if specified, the function is called with 'this' set to thisArg (optional)
A boolean containing the result
function Array.fill(value, start, end)
Fill this array with the given value, for every index >= start
and < end
Note: This is not available in devices with low flash memory
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.
This array
function Array.filter(function, thisArg)
Return an array which contains only those elements for which the callback function returns 'true'
function
- Function to be executed
thisArg
- if specified, the function is called with 'this' set to thisArg (optional)
An array containing the results
function Array.forEach(function, thisArg)
Executes a provided function once per array element.
function
- Function to be executed
thisArg
- if specified, the function is called with 'this' set to thisArg (optional)
function Array.indexOf(value, startIndex)
Return the index of the value in the array, or -1
value
- The value to check for
startIndex
- (optional) the index to search from, or 0 if not specified
the index of the value in the array, or -1
This function is used in the following places in Espruino's documentation
Array.isArray(var)
Returns true if the provided object is an array
var
- The variable to be tested
True if var is an array, false if not.
function Array.join(separator)
Join all elements of this array together into one string, using 'separator' between them. eg. [1,2,3].join(' ')=='1 2 3'
separator
- The separator
A String representing the Joined array
property Array.length
Find the length of the array
The value of the array
function Array.map(function, thisArg)
Return an array which is made from the following: A.map(function) = [function(A[0]), function(A[1]), ...]
function
- Function used to map one item to another
thisArg
- if specified, the function is called with 'this' set to thisArg (optional)
An array containing the results
function Array.pop()
Remove and return the value on the end of this array.
This is the opposite of [1,2,3].shift()
, which removes an element from the beginning of the array.
The value that is popped off
function Array.push(arguments, ...)
Push a new value onto the end of this array'
This is the opposite of [1,2,3].unshift(0)
, which adds one or more elements to the beginning of the array.
arguments, ...
- One or more arguments to add
The new size of the array
This function is used in the following places in Espruino's documentation
function Array.reduce(callback, initialValue)
Execute previousValue=initialValue
and then previousValue = callback(previousValue, currentValue, index, array)
for each element in the array, and finally return previousValue.
Note: This is not available in devices with low flash memory
callback
- Function used to reduce the array
initialValue
- if specified, the initial value to pass to the function
The value returned by the last function called
function Array.reverse()
Reverse all elements in this array (in place)
Note: This is not available in devices with low flash memory
The array, but reversed.
function Array.shift()
Remove and return the first element of the array.
This is the opposite of [1,2,3].pop()
, which takes an element off the end.
Note: This is not available in devices with low flash memory
The element that was removed
function Array.slice(start, end)
Return a copy of a portion of this array (in a new array)
start
- Start index
end
- End index (optional)
A new array
function Array.some(function, thisArg)
Return 'true' if the callback returns 'true' for any of the elements in the array
function
- Function to be executed
thisArg
- if specified, the function is called with 'this' set to thisArg (optional)
A boolean containing the result
function Array.sort(var)
Do an in-place quicksort of the array
Note: This is not available in devices with low flash memory
var
- A function to use to compare array elements (or undefined)
This array object
function Array.splice(index, howMany, elements, ...)
Both remove and add items to an array
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
An array containing the removed elements. If only one element is removed, an array of one element is returned.
function Array.toString(radix)
Convert the Array to a string
radix
- unused
A String representing the array
function Array.unshift(elements, ...)
Add one or more items to the start of the array, and return its new length.
This is the opposite of [1,2,3].push(4)
, which puts one or more elements on the end.
Note: This is not available in devices with low flash memory
elements, ...
- One or more items to add to the beginning of the array
The new array length
This is the built-in JavaScript class for array buffers.
If you want to access arrays of differing types of data you may also find /Reference#DataView useful.
new ArrayBuffer(byteLength)
Create an Array Buffer object
byteLength
- The length in Bytes
An ArrayBuffer object
property ArrayBuffer.byteLength
The length, in bytes, of the ArrayBuffer
The Length in bytes
This is the built-in JavaScript class that is the prototype for:
If you want to access arrays of differing types of data you may also find DataView useful.
property ArrayBufferView.buffer
The buffer this view references
An ArrayBuffer object
property ArrayBufferView.byteLength
The length, in bytes, of the view
The Length
property ArrayBufferView.byteOffset
The offset, in bytes, to the first byte of the view within the ArrayBuffer
The byte Offset
function ArrayBufferView.fill(value, start, end)
Fill this array with the given value, for every index >= start
and < end
Note: This is not available in devices with low flash memory
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.
This array
This function is used in the following places in Espruino's documentation
function ArrayBufferView.forEach(function, thisArg)
Executes a provided function once per array element.
function
- Function to be executed
thisArg
- if specified, the function is called with 'this' set to thisArg (optional)
function ArrayBufferView.indexOf(value)
Return the index of the value in the array, or -1
value
- The value to check for
the index of the value in the array, or -1
function ArrayBufferView.join(separator)
Join all elements of this array together into one string, using 'separator' between them. eg. [1,2,3].join(' ')=='1 2 3'
separator
- The separator
A String representing the Joined array
function ArrayBufferView.map(function, thisArg)
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
function
- Function used to map one item to another
thisArg
- if specified, the function is called with 'this' set to thisArg (optional)
An array containing the results
function ArrayBufferView.reduce(callback, initialValue)
Execute previousValue=initialValue
and then previousValue = callback(previousValue, currentValue, index, array)
for each element in the array, and finally return previousValue.
Note: This is not available in devices with low flash memory
callback
- Function used to reduce the array
initialValue
- if specified, the initial value to pass to the function
The value returned by the last function called
function ArrayBufferView.reverse()
Reverse the contents of this arraybuffer in-place
Note: This is not available in devices with low flash memory
This array
function ArrayBufferView.set(arr, offset)
Copy the contents of array
into this one, mapping this[x+offset]=array[x];
arr
- Floating point index to access
offset
- The offset in this array at which to write the values (optional)
This function is used in the following places in Espruino's documentation
function ArrayBufferView.slice(start, end)
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 not available in devices with low flash memory
start
- Start index
end
- End index (optional)
A new array
function ArrayBufferView.sort(var)
Do an in-place quicksort of the array
Note: This is not available in devices with low flash memory
var
- A function to use to compare array elements (or undefined)
This array object
A Web Bluetooth-style device - you can request one using NRF.requestDevice(address)
For example:
var gatt;
NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) {
console.log("found device");
return device.gatt.connect();
}).then(function(g) {
gatt = g;
console.log("connected");
return gatt.startBonding();
}).then(function() {
console.log("bonded", gatt.getSecurityStatus());
gatt.disconnect();
}).catch(function(e) {
console.log("ERROR",e);
});
property BluetoothDevice.gatt
A BluetoothRemoteGATTServer
for this device
BluetoothDevice.on('gattserverdisconnected', function(reason) { ... });
Called when the device gets disconnected.
To connect and then print Disconnected
when the device is
disconnected, just do the following:
var gatt;
NRF.connect("aa:bb:cc:dd:ee:ff").then(function(gatt) {
gatt.device.on('gattserverdisconnected', function(reason) {
console.log("Disconnected ",reason);
});
});
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
reason
- The reason code reported back by the BLE stack - see Nordic's ble_hci.h
file for more information
Web Bluetooth-style GATT characteristic - get this using BluetoothRemoteGATTService.getCharacteristic(s)
https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattcharacteristic
BluetoothRemoteGATTCharacteristic.on('characteristicvaluechanged', function() { ... });
Called when a characteristic's value changes, after BluetoothRemoteGATTCharacteristic.startNotifications
has been called.
See that for an example.
The first argument is of the form {target : BluetoothRemoteGATTCharacteristic}
BluetoothRemoteGATTCharacteristic.value
will then contain the new value.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
function BluetoothRemoteGATTCharacteristic.readValue()
Read a characteristic's value, return a promise containing a DataView
var device;
NRF.connect(device_address).then(function(d) {
device = d;
return d.getPrimaryService("service_uuid");
}).then(function(s) {
console.log("Service ",s);
return s.getCharacteristic("characteristic_uuid");
}).then(function(c) {
return c.readValue();
}).then(function(d) {
console.log("Got:", JSON.stringify(d.buffer));
device.disconnect();
}).catch(function() {
console.log("Something's broken.");
});
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
A Promise that is resolved (or rejected) with a DataView
when the characteristic is read
function BluetoothRemoteGATTCharacteristic.startNotifications()
Starts notifications - whenever this characteristic's value changes, a characteristicvaluechanged
event is fired.
var device;
NRF.connect(device_address).then(function(d) {
device = d;
return d.getPrimaryService("service_uuid");
}).then(function(s) {
console.log("Service ",s);
return s.getCharacteristic("characteristic_uuid");
}).then(function(c) {
c.on('characteristicvaluechanged', function(event) {
console.log("-> "+event.target.value);
});
return c.startNotifications();
}).then(function(d) {
console.log("Waiting for notifications"));
}).catch(function() {
console.log("Something's broken.");
});
For example, to listen to the output of another Puck.js's Nordic Serial port service, you can use:
var gatt;
NRF.connect("pu:ck:js:ad:dr:es random").then(function(g) {
gatt = g;
return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
}).then(function(service) {
return service.getCharacteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
}).then(function(characteristic) {
characteristic.on('characteristicvaluechanged', function(event) {
console.log("RX: "+JSON.stringify(event.target.value.buffer));
});
return characteristic.startNotifications();
}).then(function() {
console.log("Done!");
});
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
A Promise that is resolved (or rejected) with data when notifications have been added
function BluetoothRemoteGATTCharacteristic.stopNotifications()
Stop notifications (that were requested with BluetoothRemoteGATTCharacteristic.startNotifications
)
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
A Promise that is resolved (or rejected) with data when notifications have been removed
function BluetoothRemoteGATTCharacteristic.writeValue(data)
Write a characteristic's value
var device;
NRF.connect(device_address).then(function(d) {
device = d;
return d.getPrimaryService("service_uuid");
}).then(function(s) {
console.log("Service ",s);
return s.getCharacteristic("characteristic_uuid");
}).then(function(c) {
return c.writeValue("Hello");
}).then(function(d) {
device.disconnect();
}).catch(function() {
console.log("Something's broken.");
});
data
- The data to write
A Promise that is resolved (or rejected) when the characteristic is written
Web Bluetooth-style GATT server - get this using NRF.connect(address)
or NRF.requestDevice(options)
and response.gatt.connect
https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver
function BluetoothRemoteGATTServer.connect()
Connect to a BLE device - returns a promise,
the argument of which is the BluetoothRemoteGATTServer
connection.
See NRF.requestDevice
for usage examples.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
A Promise that is resolved (or rejected) when the connection is complete
function BluetoothRemoteGATTServer.disconnect()
Disconnect from a previously connected BLE device connected with
NRF.connect
- this does not disconnect from something that has
connected to the Espruino.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
function BluetoothRemoteGATTServer.getPrimaryService(service)
See NRF.connect
for usage examples.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
service
- The service UUID
A Promise that is resolved (or rejected) when the primary service is found (the argument contains a BluetoothRemoteGATTService
)
function BluetoothRemoteGATTServer.getPrimaryServices()
A Promise that is resolved (or rejected) when the primary services are found (the argument contains an array of BluetoothRemoteGATTService
)
function BluetoothRemoteGATTServer.getSecurityStatus()
Return an object with information about the security state of the current connection:
{
connected // The connection is active (not disconnected).
encrypted // Communication on this link is encrypted.
mitm_protected // The encrypted communication is also protected against man-in-the-middle attacks.
bonded // The peer is bonded with us
}
See BluetoothRemoteGATTServer.startBonding
for information about
negotiating a secure connection.
This is not part of the Web Bluetooth Specification. It has been added specifically for Puck.js.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
An object
function BluetoothRemoteGATTServer.setRSSIHandler(callback)
Start/stop listening for RSSI values on the active GATT connection
// Start listening for RSSI value updates
gattServer.setRSSIHandler(function(rssi) {
console.log(rssi); // prints -85 (or similar)
});
// Stop listening
gattServer.setRSSIHandler();
RSSI is the 'Received Signal Strength Indication' in dBm
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
callback
- The callback to call with the RSSI value, or undefined to stop
function BluetoothRemoteGATTServer.startBonding(forceRePair)
Start negotiating bonding (secure communications) with the connected device, and return a Promise that is completed on success or failure.
var gatt;
NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) {
console.log("found device");
return device.gatt.connect();
}).then(function(g) {
gatt = g;
console.log("connected");
return gatt.startBonding();
}).then(function() {
console.log("bonded", gatt.getSecurityStatus());
gatt.disconnect();
}).catch(function(e) {
console.log("ERROR",e);
});
This is not part of the Web Bluetooth Specification. It has been added specifically for Puck.js.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
forceRePair
- If the device is already bonded, re-pair it
A Promise that is resolved (or rejected) when the bonding is complete
Web Bluetooth-style GATT service - get this using BluetoothRemoteGATTServer.getPrimaryService(s)
https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice
function BluetoothRemoteGATTService.getCharacteristic(characteristic)
See NRF.connect
for usage examples.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
characteristic
- The characteristic UUID
A Promise that is resolved (or rejected) when the characteristic is found (the argument contains a BluetoothRemoteGATTCharacteristic
)
function BluetoothRemoteGATTService.getCharacteristics()
A Promise that is resolved (or rejected) when the characteristic is found (the argument contains an array of BluetoothRemoteGATTCharacteristic
)
new Boolean(value)
Creates a boolean
value
- A single value to be converted to a number
A Boolean object
CC3000.connect(spi, cs, en, irq)
Initialise the CC3000 and return a WLAN object
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
A WLAN Object
This function is used in the following places in Espruino's documentation
An Object that contains functions for writing to the interactive console
console.log(text, ...)
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.
text, ...
- One or more arguments to print
This function is used in the following places in Espruino's documentation
Cryptographic functions
Note: This library is currently only included in builds for the Espruino Pico and Espruino WiFi. For other boards you will have to make build your own firmware, and you may need to remove other features in order to make room.
crypto.AES
Class containing AES encryption/decryption
Note: This is only available in devices that support AES (Espruino Pico, Espruino WiFi or Linux)
See description above
crypto.PBKDF2(passphrase, salt, options)
Password-Based Key Derivation Function 2 algorithm, using SHA512
Note: This is only available in devices with TLS and SSL support (Espruino Pico and Espruino WiFi only)
passphrase
- Passphrase
salt
- Salt for turning passphrase into a key
options
- Object of Options, { keySize: 8 (in 32 bit words), iterations: 10, hasher: 'SHA1'/'SHA224'/'SHA256'/'SHA384'/'SHA512' }
Returns an ArrayBuffer
crypto.SHA1(message)
Performs a SHA1 hash and returns the result as a 20 byte ArrayBuffer
Note: This is only available in devices that support Crypto Functionality (Espruino Pico, Original, Espruino WiFi, Espruino BLE devices, Linux or ESP8266)
message
- The message to apply the hash to
Returns a 20 byte ArrayBuffer
crypto.SHA224(message)
Performs a SHA224 hash and returns the result as a 28 byte ArrayBuffer
Note: This is only available in devices that support SHA256 (Espruino Pico, Espruino WiFi, Espruino BLE devices or Linux)
message
- The message to apply the hash to
Returns a 20 byte ArrayBuffer
crypto.SHA256(message)
Performs a SHA256 hash and returns the result as a 32 byte ArrayBuffer
Note: This is only available in devices that support SHA256 (Espruino Pico, Espruino WiFi, Espruino BLE devices or Linux)
message
- The message to apply the hash to
Returns a 20 byte ArrayBuffer
crypto.SHA384(message)
Performs a SHA384 hash and returns the result as a 48 byte ArrayBuffer
Note: This is only available in devices that support SHA512 (Espruino Pico, Espruino WiFi, Espruino BLE devices or Linux)
message
- The message to apply the hash to
Returns a 20 byte ArrayBuffer
crypto.SHA512(message)
Performs a SHA512 hash and returns the result as a 64 byte ArrayBuffer
Note: This is only available in devices that support SHA512 (Espruino Pico, Espruino WiFi, Espruino BLE devices or Linux)
message
- The message to apply the hash to
Returns a 32 byte ArrayBuffer
This class helps
new DataView(buffer, byteOffset, byteLength)
Create a DataView object
Note: This is not available in devices with low flash memory
buffer
- The ArrayBuffer to base this on
byteOffset
- (optional) The offset of this view in bytes
byteLength
- (optional) The length in bytes
A DataView object
function DataView.getFloat32(byteOffset, littleEndian)
byteOffset
- The offset in bytes to read from
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
the index of the value in the array, or -1
function DataView.getFloat64(byteOffset, littleEndian)
byteOffset
- The offset in bytes to read from
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
the index of the value in the array, or -1
function DataView.getInt16(byteOffset, littleEndian)
byteOffset
- The offset in bytes to read from
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
the index of the value in the array, or -1
function DataView.getInt32(byteOffset, littleEndian)
byteOffset
- The offset in bytes to read from
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
the index of the value in the array, or -1
function DataView.getInt8(byteOffset, littleEndian)
byteOffset
- The offset in bytes to read from
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
the index of the value in the array, or -1
function DataView.getUint16(byteOffset, littleEndian)
byteOffset
- The offset in bytes to read from
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
the index of the value in the array, or -1
function DataView.getUint32(byteOffset, littleEndian)
byteOffset
- The offset in bytes to read from
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
the index of the value in the array, or -1
function DataView.getUint8(byteOffset, littleEndian)
byteOffset
- The offset in bytes to read from
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
the index of the value in the array, or -1
function DataView.setFloat32(byteOffset, value, littleEndian)
byteOffset
- The offset in bytes to read from
value
- The value to write
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
function DataView.setFloat64(byteOffset, value, littleEndian)
byteOffset
- The offset in bytes to read from
value
- The value to write
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
function DataView.setInt16(byteOffset, value, littleEndian)
byteOffset
- The offset in bytes to read from
value
- The value to write
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
function DataView.setInt32(byteOffset, value, littleEndian)
byteOffset
- The offset in bytes to read from
value
- The value to write
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
function DataView.setInt8(byteOffset, value, littleEndian)
byteOffset
- The offset in bytes to read from
value
- The value to write
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
function DataView.setUint16(byteOffset, value, littleEndian)
byteOffset
- The offset in bytes to read from
value
- The value to write
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
function DataView.setUint32(byteOffset, value, littleEndian)
byteOffset
- The offset in bytes to read from
value
- The value to write
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
function DataView.setUint8(byteOffset, value, littleEndian)
byteOffset
- The offset in bytes to read from
value
- The value to write
littleEndian
- (optional) Whether to read in little endian - if false or undefined data is read as big endian
The built-in class for handling Dates.
Note: By default the time zone is GMT+0, however you can change the
timezone using the E.setTimeZone(...)
function.
For example E.setTimeZone(1)
will be GMT+0100
new Date(args, ...)
Creates a date object
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]
A Date object
This function is used in the following places in Espruino's documentation
function Date.getDate()
Day of the month 1..31
See description above
function Date.getDay()
Day of the week (0=sunday, 1=monday, etc)
See description above
function Date.getFullYear()
The year, eg. 2014
See description above
function Date.getHours()
0..23
See description above
function Date.getMilliseconds()
0..999
See description above
function Date.getMinutes()
0..59
See description above
function Date.getMonth()
Month of the year 0..11
See description above
function Date.getSeconds()
0..59
See description above
function Date.getTime()
Return the number of milliseconds since 1970
See description above
function Date.getTimezoneOffset()
The getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.
The difference, in minutes, between UTC and local time
Date.now()
Get the number of milliseconds elapsed since 1970 (or on embedded platforms, since startup)
See description above
This function is used in the following places in Espruino's documentation
Date.parse(str)
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'
str
- A String
The number of milliseconds since 1970
This function is used in the following places in Espruino's documentation
function Date.setDate(dayValue)
Day of the month 1..31
Note: This is not available in devices with low flash memory
dayValue
- the day of the month, between 0 and 31
The number of milliseconds since 1970
function Date.setFullYear(yearValue, yearValue, dayValue)
yearValue
- The full year - eg. 1989
yearValue
- optional - the month, between 0 and 11
dayValue
- optional - the day, between 0 and 31
The number of milliseconds since 1970
function Date.setHours(hoursValue, minutesValue, secondsValue, millisecondsValue)
0..23
Note: This is not available in devices with low flash memory
hoursValue
- number of hours, 0..23
minutesValue
- number of minutes, 0..59
secondsValue
- optional - number of seconds, 0..59
millisecondsValue
- optional - number of milliseconds, 0..999
The number of milliseconds since 1970
function Date.setMilliseconds(millisecondsValue)
millisecondsValue
- number of milliseconds, 0..999
The number of milliseconds since 1970
function Date.setMinutes(minutesValue, secondsValue, millisecondsValue)
0..59
Note: This is not available in devices with low flash memory
minutesValue
- number of minutes, 0..59
secondsValue
- optional - number of seconds, 0..59
millisecondsValue
- optional - number of milliseconds, 0..999
The number of milliseconds since 1970
function Date.setMonth(yearValue, dayValue)
Month of the year 0..11
Note: This is not available in devices with low flash memory
yearValue
- The month, between 0 and 11
dayValue
- optional - the day, between 0 and 31
The number of milliseconds since 1970
function Date.setSeconds(secondsValue, millisecondsValue)
0..59
Note: This is not available in devices with low flash memory
secondsValue
- number of seconds, 0..59
millisecondsValue
- optional - number of milliseconds, 0..999
The number of milliseconds since 1970
function Date.setTime(timeValue)
Set the time/date of this Date class
timeValue
- the number of milliseconds since 1970
the number of milliseconds since 1970
function Date.toISOString()
Converts to a ISO 8601 String, eg: 2014-06-20T14:52:20.123Z
Note: This always assumes a timezone of GMT
A String
function Date.toString()
Converts to a String, eg: Fri Jun 20 2014 14:52:20 GMT+0000
Note: This uses whatever timezone was set with E.setTimeZone()
A String
function Date.toUTCString()
Converts to a String, eg: Fri, 20 Jun 2014 14:52:20 GMT
Note: This always assumes a timezone of GMT
A String
function Date.valueOf()
Return the number of milliseconds since 1970
See description above
This library allows you to create UDP/DATAGRAM 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.
dgram.createSocket(type, callback)
Create a UDP socket
type
- Socket type to create e.g. 'udp4'
callback
- A function(sckt)
that will be called with the socket when a connection is made. You can then call sckt.send(...)
to send data, and sckt.on('message', function(data) { ... })
and sckt.on('close', function() { ... })
to deal with the response.
Returns a new dgram.Socket object
An actual socket connection - allowing transmit/receive of TCP data
function dgramSocket.addMembership(group, ip)
group
- A string containing the group ip to join
ip
- A string containing the ip to join with
function dgramSocket.bind(port, callback)
port
- The port to bind at
callback
- A function(res) that will be called when the socket is bound. You can then call res.on('message', function(message, info) { ... })
and res.on('close', function() { ... })
to deal with the response.
The dgramSocket instance that 'bind' was called on
function dgramSocket.close()
Close the socket
dgramSocket.on('close', function(had_error) { ... });
Called when the connection closes.
had_error
- A boolean indicating whether the connection had an error (use an error event handler to get error details).
dgramSocket.on('message', function(msg, rinfo) { ... });
The 'message' event is called when a datagram message is received. If a handler is defined with X.on('message', function(msg) { ... })
then it will be called`
msg
- A string containing the received message
rinfo
- Sender address,port containing information
function dgramSocket.send(buffer, offset, length, args, ...)
buffer
- A string containing message to send
offset
- Offset in the passed string where the message starts [optional]
length
- Number of bytes in the message [optional]
args, ...
- Destination port number, Destination IP address string
This is the built-in JavaScript class for Espruino utility functions.
E.asm(callspec, assemblycode, ...)
Provide assembly to Espruino.
This function is not part of Espruino. Instead, it is detected
by the Espruino IDE (or command-line tools) at upload time and is
replaced with machine code and an E.nativeCall
call.
See the documentation on the Assembler for more information.
Note: This is not available in devices with low flash memory
callspec
- The arguments this assembly takes - eg void(int)
assemblycode, ...
- One of more strings of assembler code
This function is used in the following places in Espruino's documentation
E.clip(x, min, max)
Clip a number to be between min and max (inclusive)
Note: This is not available in devices with low flash memory
x
- A floating point value to clip
min
- The smallest the value should be
max
- The largest the value should be
The value of x, clipped so as not to be below min or above max.
This function is used in the following places in Espruino's documentation
E.connectSDCard(spi, csPin)
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:
// DI/CMD = C7
// DO/DAT0 = C8
// CK/CLK = C9
// CD/CS/DAT3 = C6
var spi = new SPI();
spi.setup({mosi:C7, miso:C8, sck:C9});
E.connectSDCard(spi, C6);
console.log(require("fs").readdirSync());
See the page on File IO for more information.
Note: We'd strongly suggest you add a pullup resistor from CD/CS pin to 3.3v. It is good practise to avoid accidental writes before Espruino is initialised, and some cards will not work reliably without one.
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.
Note: This is not available in devices with low flash memory
spi
- The SPI object to use for communication
csPin
- The pin to use for Chip Select
E.convolve(arr1, arr2, offset)
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 not available in devices with low flash memory
arr1
- An array to convolve
arr2
- An array to convolve
offset
- The mean value of the array
The variance of the given buffer
E.dumpFreeList()
Dump any locked variables that aren't referenced from global
- for debugging memory leaks only.
Note: This is not available in release builds
E.dumpLockedVars()
Dump any locked variables that aren't referenced from global
- for debugging memory leaks only.
Note: This is not available in release builds
E.dumpStr()
Get the current interpreter state in a text form such that it can be copied to a new device
Note: This is not available in devices with low flash memory
A String
E.dumpTimers()
Output the current list of Utility Timer Tasks - for debugging only
Note: This is not available in release builds
E.enableWatchdog(timeout, isAuto)
Enable the watchdog timer. This will reset Espruino if it isn't able to return to the idle loop within the timeout.
If isAuto
is false, you must call E.kickWatchdog()
yourself every so often or the chip will reset.
E.enableWatchdog(0.5); // automatic mode
while(1); // Espruino will reboot because it has not been idle for 0.5 sec
E.enableWatchdog(1, false);
setInterval(function() {
if (everything_ok)
E.kickWatchdog();
}, 500);
// Espruino will now reset if everything_ok is false,
// or if the interval fails to be called
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 implemented on STM32 and nRF5x devices (all official Espruino boards).
Note: This is not available in devices with low flash memory
timeout
- The timeout in seconds before a watchdog reset
isAuto
- If undefined or true, the watchdog is kicked automatically. If not, you must call E.kickWatchdog()
yourself
E.on('errorFlag', function(errorFlags) { ... });
This event is called when an error is created by Espruino itself (rather
than JS code) which changes the state of the error flags reported by
E.getErrorFlags()
This could be low memory, full buffers, UART overflow, etc. E.getErrorFlags()
has a full description of each type of error.
This event will only be emitted when error flag is set. If the error
flag was already set nothing will be emitted. To clear error flags
so that you do get a callback each time a flag is set, call E.getErrorFlags()
.
errorFlags
- An array of new error flags, as would be returned by E.getErrorFlags()
. Error flags that were present before won't be reported.
E.FFT(arrReal, arrImage, inverse)
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(r*r+i*i)
.
Note: This is not available in devices with low flash memory
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
This function is used in the following places in Espruino's documentation
E.flashFatFS(options)
Change the paramters used for the flash filesystem. The default address is the last 1Mb of 4Mb Flash, 0x300000, with total size of 1Mb.
Before first use the media needs to be formatted.
fs=require("fs");
try {
fs.readdirSync();
} catch (e) { //'Uncaught Error: Unable to mount media : NO_FILESYSTEM'
console.log('Formatting FS - only need to do once');
E.flashFatFS({ format: true });
}
fs.writeFileSync("bang.txt", "This is the way the world ends\nnot with a bang but a whimper.\n");
fs.readdirSync();
This will create a drive of 100 * 4096 bytes at 0x300000. Be careful with the selection of flash addresses as you can overwrite firmware! You only need to format once, as each will erase the content.
E.flashFatFS({ addr:0x300000,sectors:100,format:true });
Note: This is only available in devices with filesystem in Flash support enabled (ESP32 only)
options
- An optional object { addr : int=0x300000, sectors : int=256, format : bool=false }
addr : start address in flash
sectors: number of sectors to use
format: Format the media
True on success, or false on failure
E.getAddressOf(v, flatAddress)
Return the address in memory of the given variable. This can then
be used with peek
and poke
functions. However, changing data in
JS variables directly (flatAddress=false) will most likely result in a crash.
This functions exists to allow embedded targets to set up peripherals such as DMA so that they write directly to JS variables.
See http://www.espruino.com/Internals for more information
Note: This is not available in devices with low flash memory
v
- A variable to get the address of
flatAddress
- If a flat String or flat ArrayBuffer is supplied, return the address of the data inside it - otherwise 0
The address of the given variable
E.getAnalogVRef()
Check the internal voltage reference. To work out an actual voltage of an input pin, you can use analogRead(pin)*E.getAnalogVRef()
Note: This value is calculated by reading the voltage on an internal voltage reference with the ADC. It will be slightly noisy, so if you need this for accurate measurements we'd recommend that you call this function several times and average the results.
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 available in devices with low flash memory
The voltage (in Volts) that a reading of 1 from analogRead
actually represents - usually around 3.3v
This function is used in the following places in Espruino's documentation
E.getBattery()
In devices that come with batteries, this function returns the battery charge percentage as an integer between 0 and 100.
Note: this is an estimation only, based on battery voltage.
The temperature of the battery (as well as the load being drawn
from it at the time E.getBattery
is called) will affect the
readings.
Note: This is only available in Puck.js devices and Pixl.js boards
A percentage between 0 and 100
E.getErrorFlags()
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.
'UART_OVERFLOW'
: A UART received data but it was not read in time and was lost
Note: This is not available in devices with low flash memory
An array of error flags
E.getFlags()
Get Espruino's interpreter flags that control the way it handles your JavaScript code.
deepSleep
- Allow deep sleep modes (also set by setDeepSleep)pretokenise
- When adding functions, pre-minify them and tokenise reserved wordsunsafeFlash
- Some platforms stop writes/erases to interpreter memory to stop you bricking the device accidentally - this removes that protectionunsyncFiles
- When writing files, don't flush all data to the SD card after each command (the default is to flush). This is much faster, but can cause filesystem damage if power is lost without the filesystem unmounted.An object containing flag names and their values
E.getSizeOf(v, depth)
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.
If depth>0
and the variable can be recursed into, an array listing all property
names (including internal Espruino names) and their sizes is returned. If
depth>1
there is also a more
field that inspects the objects's children's
children.
For instance E.getSizeOf(function(a,b) { })
returns 5
.
But E.getSizeOf(function(a,b) { }, 1)
returns:
[
{
"name": "a",
"size": 1 },
{
"name": "b",
"size": 1 },
{
"name": "\xFFcod",
"size": 2 }
]
In this case setting depth to 2
will make no difference as there are
no more children to traverse.
See http://www.espruino.com/Internals for more information
Note: This is not available in devices with low flash memory
v
- A variable to get the size of
depth
- The depth that detail should be provided for. If depth<=0 or undefined, a single integer will be returned
Information about the variable size - see below
E.getTemperature()
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.
The temperature in degrees C
This function is used in the following places in Espruino's documentation
E.HSBtoRGB(hue, sat, bri, asArray)
Convert hue, saturation and brightness to red, green and blue (packed into an integer if asArray==false
or an array if asArray==true
).
This replaces Graphics.setColorHSB
and Graphics.setBgColorHSB
. On devices with 24 bit colour it can
be used as: Graphics.setColor(E.HSBtoRGB(h, s, b))
You can quickly set RGB items in an Array or Typed Array using array.set(E.HSBtoRGB(h, s, b,true), offset)
,
which can be useful with arrays used with require("neopixel").write
.
Note: This is not available in devices with low flash memory
hue
- The hue, as a value between 0 and 1
sat
- The saturation, as a value between 0 and 1
bri
- The brightness, as a value between 0 and 1
asArray
- If true, return an array of [R,G,B] values betwen 0 and 255
A 24 bit number containing bytes representing red, green, and blue 0xBBGGRR
. Or if asArray
is true, an array [R,G,B]
E.hwRand()
Unlike 'Math.random()' which uses a pseudo-random number generator, this method reads from the internal voltage reference several times, xoring and rotating to try and make a relatively random value from the noise in the signal.
Note: This is not available in devices with low flash memory
A random number
E.on('init', function() { ... });
This event is called right after the board starts up, and has a similar effect
to creating a function called onInit
.
For example to write "Hello World"
every time Espruino starts, use:
E.on('init', function() {
console.log("Hello World!");
});
Note: that subsequent calls to E.on('init',
will add a new handler,
rather than replacing the last one. This allows you to write modular code -
something that was not possible with onInit
.
E.interpolate(array, index)
Interpolate between two adjacent values in the Typed Array
Note: This is not available in devices with low flash memory
array
- A Typed Array to interpolate between
index
- Floating point index to access
The result of interpolating between (int)index and (int)(index+1)
E.interpolate2d(array, width, x, y)
Interpolate between four adjacent values in the Typed Array, in 2D.
Note: This is not available in devices with low flash memory
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
The result of interpolating in 2d between the 4 surrounding cells
E.kickWatchdog()
Kicks a Watchdog timer set up with E.enableWatchdog(..., false)
. See
E.enableWatchdog
for more information.
NOTE: This is only implemented on STM32 and nRF5x devices (all official Espruino boards).
Note: This is not available in devices with low flash memory
E.lockConsole()
If a password has been set with E.setPassword()
, this will lock the console
so the password needs to be entered to unlock it.
E.mapInPlace(from, to, map, bits)
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 not available in devices with low flash memory
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
E.memoryArea(addr, len)
This creates and returns a special type of string, which actually references
a specific memory address. It can be used in order to use sections of
Flash memory directly in Espruino (for example to execute code straight
from flash memory with eval(E.memoryArea( ... ))
)
Note: This is only tested on STM32-based platforms (Espruino Original and Espruino Pico) at the moment.
addr
- The address of the memory area
len
- The length (in bytes) of the memory area
A String
This function is used in the following places in Espruino's documentation
E.nativeCall(addr, sig, data)
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 not available in devices with low flash memory
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.
The native function
This function is used in the following places in Espruino's documentation
E.openFile(path, mode)
Open a file
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'.
A File object
This function is used in the following places in Espruino's documentation
E.reverseByte(x)
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 not available in devices with low flash memory
x
- A byte value to reverse the bits of
The byte with reversed bits
E.sendUSBHID(data)
data
- An array of bytes to send as a USB HID packet
1 on success, 0 on failure
E.setBootCode(code, alwaysExec)
This writes JavaScript code into Espruino's flash memory, to be executed on
startup. It differs from save()
in that save()
saves the whole state of
the interpreter, whereas this just saves JS code that is executed at boot.
Code will be executed before onInit()
and E.on('init', ...)
.
If alwaysExec
is true
, the code will be executed even after a call to
reset()
. This is useful if you're making something that you want to
program, but you want some code that is always built in (for instance
setting up a display or keyboard).
To remove boot code that has been saved previously, use E.setBootCode("")
Note: this removes any code that was previously saved with save()
code
- The code to execute (as a string)
alwaysExec
- Whether to always execute the code (even after a reset)
E.setClock(options)
This sets the clock frequency of Espruino's processor. It will return 0
if
it is unimplemented or the clock speed cannot be changed.
Note: On pretty much all boards, UART, SPI, I2C, PWM, etc will change frequency and will need setting up again in order to work.
Options is of the form { M: int, N: int, P: int, Q: int }
- see the 'Clocks'
section of the microcontroller's reference manual for what these mean.
Optional arguments are:
latency
- flash latency from 0..15PCLK1
- Peripheral clock 1 divisor (default: 2)PCLK2
- Peripheral clock 2 divisor (default: 4)The Pico's default is {M:8, N:336, P:4, Q:7, PCLK1:2, PCLK2:4}
, use
{M:8, N:336, P:8, Q:7, PCLK:1, PCLK2:2}
to halve the system clock speed
while keeping the peripherals running at the same speed (omitting PCLK1/2
will lead to the peripherals changing speed too).
On STM32F4 boards (eg. Espruino Pico), the USB clock needs to be kept at 48Mhz or USB will fail to work. You'll also experience USB instability if the processor clock falls much below 48Mhz.
Just specify an integer value, either 80 or 160 (for 80 or 160Mhz)
Note: This is not available in devices with low flash memory
options
- Platform-specific options for setting clock speed
The actual frequency the clock has been set to
E.setFlags(flags)
Set the Espruino interpreter flags that control the way it handles your JavaScript code.
Run E.getFlags()
and check its description for a list of available flags and their values.
flags
- An object containing flag names and boolean values. You need only specify the flags that you want to change.
E.setPassword(password)
Set a password on the console (REPL). When powered on, Espruino will
then demand a password before the console can be used. If you want to
lock the console immediately after this you can call E.lockConsole()
To remove the password, call this function with no arguments.
Note: There is no protection against multiple password attempts, so someone could conceivably try every password in a dictionary.
Note: This password is stored in memory in plain text. If someone is able
to execute arbitrary JavaScript code on the device (eg, you use eval
on input
from unknown sources) or read the device's firmware then they may be able to
obtain it.
password
- The password - max 20 chars
E.setTimeZone(zone)
Set the time zone to be used with Date
objects.
For example E.setTimeZone(1)
will be GMT+0100
Time can be set with setTime
.
Note: This is not available in devices with low flash memory
zone
- The time zone in hours
E.setUSBHID(opts)
USB HID will only take effect next time you unplug and re-plug your Espruino. If you're
disconnecting it from power you'll have to make sure you have save()
d after calling
this function.
Note: This is only available in devices that support USB HID (Espruino Pico and Espruino WiFi)
opts
- An object containing at least reportDescriptor, an array representing the report descriptor. Pass undefined to disable HID.
E.srand(v)
Set the seed for the random number generator used by Math.random()
.
Note: This is not available in devices with low flash memory
v
- The 32 bit integer seed to use for the random number generator
E.sum(arr)
Sum the contents of the given Array, String or ArrayBuffer and return the result
Note: This is not available in devices with low flash memory
arr
- The array to sum
The sum of the given buffer
This function is used in the following places in Espruino's documentation
E.toArrayBuffer(str)
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('....'))
.
str
- The string to convert to an ArrayBuffer
An ArrayBuffer that uses the given string
This function is used in the following places in Espruino's documentation
E.toString(args, ...)
Returns a 'flat' string representing the data in the arguments, or return undefined
if a flat string cannot be created.
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.
In the case where there's one argument which is an 8 bit typed array backed by a flat string of the same length, the backing string will be returned without doing a copy or other allocation. The same applies if there's a single argument which is itself a flat string.
args, ...
- The arguments to convert to a String
A String
This function is used in the following places in Espruino's documentation
E.toUint8Array(args, ...)
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.
args, ...
- The arguments to convert to a Uint8Array
A Uint8Array
E.unmountSD()
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()
.
E.variance(arr, mean)
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 not available in devices with low flash memory
arr
- The array to work out the variance for
mean
- The mean value of the array
The variance of the given buffer
The base class for runtime errors
new Error(message)
Creates an Error object
message
- An optional message string
An Error object
This function is used in the following places in Espruino's documentation
function Error.toString()
A String
ESP32.deepSleep(us)
Put device in deepsleep state for "us" microseconds.
us
- Sleeptime in us
ESP32.getState()
Returns an object that contains details about the state of the ESP32 with the following fields:
sdkVersion
- Version of the SDK.freeHeap
- Amount of free heap in bytes.The state of the ESP32
ESP32.reboot()
Perform a hardware reset/reboot of the ESP32.
ESP32.setAtten(pin, atten)
pin
- Pin for Analog read
atten
- Attenuate factor
ESP32.setBLE_Debug(level)
level
- which events should be shown (GATTS, GATTC, GAP)
The ESP8266 library is specific to the ESP8266 version of Espruino, i.e., running Espruino on an ESP8266 module (not to be confused with using the ESP8266 as Wifi add-on to an Espruino board). This library contains functions to handle ESP8266-specific actions.
For example: var esp8266 = require('ESP8266'); esp8266.reboot();
performs a hardware reset of the module.
ESP8266.crc32(arrayOfData)
arrayOfData
- Array of data to CRC
32-bit CRC
ESP8266.deepSleep(micros, option)
Put the ESP8266 into 'deep sleep' for the given number of microseconds, reducing power consumption drastically.
meaning of option values:
0 - the 108th Byte of init parameter decides whether RF calibration will be performed or not.
1 - run RF calibration after waking up. Power consumption is high.
2 - no RF calibration after waking up. Power consumption is low.
4 - no RF after waking up. Power consumption is the lowest.
Note: unlike normal Espruino boards' 'deep sleep' mode, ESP8266 deep sleep actually turns off the processor. After the given number of microseconds have elapsed, the ESP8266 will restart as if power had been turned off and then back on. All contents of RAM will be lost. Connect GPIO 16 to RST to enable wakeup.
Special: 0 microseconds cause sleep forever until external wakeup RST pull down occurs.
micros
- Number of microseconds to sleep.
option
- posible values are 0, 1, 2 or 4
ESP8266.dumpSocketInfo()
Dumps info about all sockets to the log. This is for troubleshooting the socket implementation.
ESP8266.getFreeFlash()
Note: This is deprecated. Use require("Flash").getFree()
Array of objects with addr
and length
properties describing the free flash areas available
ESP8266.getResetInfo()
At boot time the esp8266's firmware captures the cause of the reset/reboot. This function returns this information in an object with the following fields:
reason
: "power on", "wdt reset", "exception", "soft wdt", "restart", "deep sleep", or "reset pin"exccause
: exception causeepc1
, epc2
, epc3
: instruction pointersexcvaddr
: address being accesseddepc
: (?)An object with the reset cause information
ESP8266.getState()
Returns an object that contains details about the state of the ESP8266 with the following fields:
sdkVersion
- Version of the SDK.cpuFrequency
- CPU operating frequency in Mhz.freeHeap
- Amount of free heap in bytes.maxCon
- Maximum number of concurrent connections.flashMap
- Configured flash size&map: '512KB:256/256' .. '4MB:512/512'flashKB
- Configured flash size in KB as integerflashChip
- Type of flash chip as string with manufacturer & chip, ex: '0xEF 0x4016`The state of the ESP8266
ESP8266.logDebug(enable)
Enable or disable the logging of debug information. A value of true
enables debug logging while a value of false
disables debug logging. Debug output is sent to UART1 (gpio2).
enable
- Enable or disable the debug logging.
ESP8266.neopixelWrite(pin, arrayOfData)
This function is deprecated. Please use require("neopixel").write(pin, data)
instead
pin
- Pin for output signal.
arrayOfData
- Array of LED data.
ESP8266.ping(ipAddr, pingCallback)
DEPRECATED - please use Wifi.ping
instead.
Perform a network ping request. The parameter can be either a String or a numeric IP address.
ipAddr
- A string representation of an IP address.
pingCallback
- Optional callback function.
ESP8266.printLog()
Prints the contents of the debug log to the console.
ESP8266.readLog()
Returns one line from the log or up to 128 characters.
ESP8266.reboot()
Perform a hardware reset/reboot of the esp8266.
ESP8266.setCPUFreq(freq)
Note: This is deprecated. Use E.setClock(80/160)
Note:
Set the operating frequency of the ESP8266 processor. The default is 160Mhz.
Warning: changing the cpu frequency affects the timing of some I/O operations, notably of software SPI and I2C, so things may be a bit slower at 80Mhz.
freq
- Desired frequency - either 80 or 160.
ESP8266.setLog(mode)
Set the debug logging mode. It can be disabled (which frees ~1.2KB of heap), enabled in-memory only, or in-memory and output to a UART.
mode
- Debug log mode: 0=off, 1=in-memory only, 2=in-mem and uart0, 3=in-mem and uart1.
An instantiation of an Ethernet network adaptor
function Ethernet.getIP()
Get the current IP address, subnet, gateway and mac address.
See description above
function Ethernet.setIP(options)
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"
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.
True on success
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.
function File.close()
Close an open file.
function File.pipe(destination, options)
Pipe this file to a stream (an object with a 'write' method)
Note: This is not available in devices with low flash memory
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
function File.read(length)
Read data in a file in byte size chunks
length
- is an integer specifying the number of bytes to read.
A string containing the characters that were read
This function is used in the following places in Espruino's documentation
function File.seek(nBytes)
Seek to a certain position in the file
nBytes
- is an integer specifying the number of bytes to skip forwards.
function File.skip(nBytes)
Skip the specified number of bytes forward in the file
nBytes
- is a positive integer specifying the number of bytes to skip forwards.
function File.write(buffer)
Write data to a file.
Note: By default this function flushes all changes to the
SD card, which makes it slow (but also safe!). You can use
E.setFlags({unsyncFiles:1})
to disable this behaviour and
really speed up writes - but then you must be sure to close
all files you are writing before power is lost or you will
cause damage to your SD card's filesystem.
buffer
- A string containing the bytes to write
the number of bytes written
This function is used in the following places in Espruino's documentation
This module allows you to read and write the nonvolatile flash memory of your device.
Also see the Storage
library, which provides a safer file-like
interface to nonvolatile storage.
It should be used with extreme caution, as it is easy to overwrite parts of Flash
memory belonging to Espruino or even its bootloader. If you damage the bootloader
then you may need external hardware such as a USB-TTL converter to restore it. For
more information on restoring the bootloader see Advanced Reflashing
in your
board's reference pages.
To see which areas of memory you can and can't overwrite, look at the values
reported by process.memory()
.
Note: On Nordic platforms there are checks in place to help you avoid
'bricking' your device be damaging the bootloader. You can disable these with E.setFlags({unsafeFlash:1})
Flash.erasePage(addr)
Erase a page of flash memory
Note: This is not available in devices with low flash memory
addr
- An address in the page that is to be erased
Flash.getFree()
This method returns an array of objects of the form {addr : #, length : #}
, representing
contiguous areas of flash memory in the chip that are not used for anything.
The memory areas returned are on page boundaries. This means that you can safely erase the page containing any address here, and you won't risk deleting part of the Espruino firmware.
Note: This is not available in devices with low flash memory
Array of objects with addr
and length
properties
Flash.getPage(addr)
Returns the start and length of the flash page containing the given address.
Note: This is not available in devices with low flash memory
addr
- An address in memory
An object of the form { addr : #, length : #}
, where addr
is the start address of the page, and length
is the length of it (in bytes). Returns undefined if no page at address
Flash.read(length, addr)
Read flash memory from the given address
Note: This is not available in devices with low flash memory
length
- The amount of data to read (in bytes)
addr
- The address to start reading from
A Uint8Array of data
Flash.write(data, addr)
Write data into memory at the given address - IN MULTIPLES OF 4 BYTES.
In flash memory you may only turn bits that are 1 into bits that are 0. If
you're writing data into an area that you have already written (so read
doesn't return all 0xFF
) you'll need to call erasePage
to clear the
entire page.
Note: This is not available in devices with low flash memory
data
- The data to write. This must be a multiple of 4 bytes.
addr
- The address to start writing from, this must be on a word boundary (a multiple of 4)
This is the built-in JavaScript class for a typed array of 32 bit floating point values.
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).
Arrays of this type include all the methods from ArrayBufferView
new Float32Array(arr, byteOffset, length)
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.
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)
A typed array
This is the built-in JavaScript class for a typed array of 64 bit floating point values.
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).
Arrays of this type include all the methods from ArrayBufferView
new Float64Array(arr, byteOffset, length)
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.
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)
A typed array
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.
To use this, you must type var fs = require('fs')
to get access to the library
See the page on File IO for more information, and for examples on wiring up an SD card if your device doesn't come with one.
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.
fs.appendFile(path, data)
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.
path
- The path of the file to write
data
- The data to write to the file
True on success, false on failure
fs.appendFileSync(path, data)
Append the data to the given file, created a new file if it doesn't exist
Note: This is not available in devices with low flash memory
path
- The path of the file to write
data
- The data to write to the file
True on success, false on failure
This function is used in the following places in Espruino's documentation
fs.mkdir(path)
Create the directory
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
Note: This is not available in devices with low flash memory
path
- The name of the directory to create
True on success, or false on failure
fs.mkdirSync(path)
Create the directory
Note: This is not available in devices with low flash memory
path
- The name of the directory to create
True on success, or false on failure
fs.pipe(source, destination, options)
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
fs.readdir(path)
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.
path
- The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory
An array of filename strings (or undefined if the directory couldn't be listed)
This function is used in the following places in Espruino's documentation
fs.readdirSync(path)
List all files in the supplied directory, returning them as an array of strings.
Note: This is not available in devices with low flash memory
path
- The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory
An array of filename strings (or undefined if the directory couldn't be listed)
This function is used in the following places in Espruino's documentation
fs.readFile(path)
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.
path
- The path of the file to read
A string containing the contents of the file (or undefined if the file doesn't exist)
This function is used in the following places in Espruino's documentation
fs.readFileSync(path)
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 not available in devices with low flash memory
path
- The path of the file to read
A string containing the contents of the file (or undefined if the file doesn't exist)
This function is used in the following places in Espruino's documentation
fs.statSync(path)
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 not available in devices with low flash memory
path
- The path of the file to get information on
An object describing the file, or undefined on failure
fs.unlink(path)
Delete the given file
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
Note: This is not available in devices with low flash memory
path
- The path of the file to delete
True on success, or false on failure
fs.unlinkSync(path)
Delete the given file
Note: This is not available in devices with low flash memory
path
- The path of the file to delete
True on success, or false on failure
fs.writeFile(path, data)
Write the data to the given file
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
path
- The path of the file to write
data
- The data to write to the file
True on success, false on failure
fs.writeFileSync(path, data)
Write the data to the given file
Note: This is not available in devices with low flash memory
path
- The path of the file to write
data
- The data to write to the file
True on success, false on failure
This function is used in the following places in Espruino's documentation
This is the built-in class for Functions
function Function.apply(this, args)
This executes the function with the supplied 'this' argument and parameters
this
- The value to use as the 'this' argument when executing the function
args
- Optional Array of Arguments
The return value of executing this function
function Function.bind(this, params, ...)
This executes the function with the supplied 'this' argument and parameters
this
- The value to use as the 'this' argument when executing the function
params, ...
- Optional Default parameters that are prepended to the call
The 'bound' function
This function is used in the following places in Espruino's documentation
function Function.call(this, params, ...)
This executes the function with the supplied 'this' argument and parameters
this
- The value to use as the 'this' argument when executing the function
params, ...
- Optional Parameters
The return value of executing this function
new Function(args, ...)
Creates a function
args, ...
- Zero or more arguments (as strings), followed by a string representing the code to run
A Number object
function Function.replaceWith(newFunc)
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.
newFunc
- The new function to replace this function with
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. See the Graphics page for more information.
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)
function Graphics.clear()
Clear the LCD with the Background Color
This function is used in the following places in Espruino's documentation
Graphics.createArrayBuffer(width, height, bpp, options)
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
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
The new Graphics object
This function is used in the following places in Espruino's documentation
Graphics.createCallback(width, height, bpp, callback)
Create a Graphics object that renders by calling a JavaScript callback function to draw pixels
Note: This is not available in devices with low flash memory
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.
The new Graphics object
This function is used in the following places in Espruino's documentation
Graphics.createSDL(width, height)
Create a Graphics object that renders to SDL window (Linux-based devices only)
Note: This is only available in Linux with SDL support compiled in
width
- Pixels wide
height
- Pixels high
The new Graphics object
function Graphics.drawCircle(x, y, rad)
Draw an unfilled circle 1px wide in the Foreground Color
x
- The X axis
y
- The Y axis
rad
- The circle radius
function Graphics.drawImage(image, x, y)
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
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
This function is used in the following places in Espruino's documentation
function Graphics.drawLine(x1, y1, x2, y2)
Draw a line between x1,y1 and x2,y2 in the current foreground color
x1
- The left
y1
- The top
x2
- The right
y2
- The bottom
This function is used in the following places in Espruino's documentation
function Graphics.drawRect(x1, y1, x2, y2)
Draw an unfilled rectangle 1px wide in the Foreground Color
x1
- The left
y1
- The top
x2
- The right
y2
- The bottom
function Graphics.drawString(str, x, y)
Draw a string of text in the current font
str
- The string
x
- The X position of the leftmost pixel
y
- The Y position of the topmost pixel
function Graphics.fillCircle(x, y, rad)
Draw a filled circle in the Foreground Color
x
- The X axis
y
- The Y axis
rad
- The circle radius
function Graphics.fillPoly(poly)
Draw a filled polygon in the current foreground color
poly
- An array of vertices, of the form [x1,y1,x2,y2,x3,y3,etc]
function Graphics.fillRect(x1, y1, x2, y2)
Fill a rectangular area in the Foreground Color
x1
- The left
y1
- The top
x2
- The right
y2
- The bottom
function Graphics.getBgColor()
Get the background color to use for subsequent drawing operations
The integer value of the colour
function Graphics.getColor()
Get the color to use for subsequent drawing operations
The integer value of the colour
function Graphics.getHeight()
The height of the LCD
The height of the LCD
function Graphics.getModified(reset)
Return the area of the Graphics canvas that has been modified, and optionally clear the modified area to 0.
For instance if g.setPixel(10,20)
was called, this would return {x1:10, y1:20, x2:10, y2:20}
Note: This is not available in devices with low flash memory
reset
- Whether to reset the modified area or not
An object {x1,y1,x2,y2} containing the modified area, or undefined if not modified
function Graphics.getPixel(x, y)
Get a pixel's color
x
- The left
y
- The top
The color
function Graphics.getWidth()
The width of the LCD
The width of the LCD
function Graphics.lineTo(x, y)
Draw a line from the last position of lineTo or moveTo to this position
x
- X value
y
- Y value
function Graphics.moveTo(x, y)
Move the cursor to a position - see lineTo
x
- X value
y
- Y value
function Graphics.scroll(x, y)
Scroll the contents of this graphics in a certain direction. The remaining area is filled with the background color.
Note: This uses repeated pixel reads and writes, so will not work on platforms that don't support pixel reads.
x
- X direction. >0 = to right
y
- Y direction. >0 = down
function Graphics.setBgColor(r, g, b)
Set the background color to use for subsequent drawing operations
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)
function Graphics.setColor(r, g, b)
Set the color to use for subsequent drawing operations
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)
This function is used in the following places in Espruino's documentation
function Graphics.setFontAlign(x, y, rotation)
Set the alignment for subsequent calls to drawString
Note: This is not available in devices with low flash memory
x
- X alignment. -1=left (default), 0=center, 1=right
y
- Y alignment. -1=top (default), 0=center, 1=bottom
rotation
- Rotation of the text. 0=normal, 1=90 degrees clockwise, 2=180, 3=270
function Graphics.setFontBitmap()
Make subsequent calls to drawString
use the built-in 4x6 pixel bitmapped Font
function Graphics.setFontCustom(bitmap, firstChar, width, height)
Make subsequent calls to drawString
use a Custom Font of the given height. See the Fonts page for more
information about custom fonts and how to create them.
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
function Graphics.setFontVector(size)
Make subsequent calls to drawString
use a Vector Font of the given height
Note: This is not available in devices with low flash memory
size
- The height of the font, as an integer
This function is used in the following places in Espruino's documentation
function Graphics.setPixel(x, y, col)
Set a pixel's color
x
- The left
y
- The top
col
- The color
function Graphics.setRotation(rotation, reflect)
Set the current rotation of the graphics device.
rotation
- The clockwise rotation. 0 for no rotation, 1 for 90 degrees, 2 for 180, 3 for 270
reflect
- Whether to reflect the image
function Graphics.stringWidth(str)
Return the size in pixels of a string of text in the current font
str
- The string
The length of the string in pixels
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.
function HASH.digest(message)
message
- part of message
Hash digest
function HASH.hexdigest(message)
message
- part of message
Hash hexdigest
function HASH.update(message)
message
- part of message
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.
hashlib.sha224(message)
message
- message to hash
Returns a new HASH SHA224 Object
hashlib.sha256(message)
message
- message to hash
Returns a new HASH SHA256 Object
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.
http.createServer(callback)
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
callback
- A function(request,response) that will be called when a connection is made
Returns a new httpSrv object
This function is used in the following places in Espruino's documentation
http.get(options, callback)
Request a webpage over HTTP - a convenience function for http.request()
that makes sure the HTTP command is 'GET', and that calls end
automatically.
require("http").get("http://pur3.co.uk/hello.txt", function(res) {
res.on('data', function(data) {
console.log("HTTP> "+data);
});
res.on('close', function(data) {
console.log("Connection closed");
});
});
See http.request()
and the Internet page and ` for more usage examples.
options
- A simple URL, or 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 a new httpCRq object
http.request(options, callback)
Create an HTTP Request - end()
must be called on it to complete the operation. options
is of the form:
var options = {
host: 'example.com', // host name
port: 80, // (optional) port, defaults to 80
path: '/', // path sent to server
method: 'GET', // HTTP command sent to server (must be uppercase 'GET', 'POST', etc)
protocol: 'http:', // optional protocol - https: or http:
headers: { key : value, key : value } // (optional) HTTP headers
};
require("http").request(options, function(res) {
res.on('data', function(data) {
console.log("HTTP> "+data);
});
res.on('close', function(data) {
console.log("Connection closed");
});
});
You can easily pre-populate options
from a URL using var options = url.parse("http://www.example.com/foo.html")
Note: if TLS/HTTPS is enabled, options can have ca
, key
and cert
fields. See tls.connect
for
more information about these and how to use them.
options
- An object containing host,port,path,method,headers fields (and also ca,key,cert if HTTPS is enabled)
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 a new httpCRq object
The HTTP client request, returned by http.request()
and http.get()
.
httpCRq.on('drain', function() { ... });
An event that is fired when the buffer is empty and it can accept more data to send.
function httpCRq.end(data)
Finish this HTTP request - optional data to append as an argument
See Socket.write
for more information about the data argument
data
- A string containing data to send
httpCRq.on('error', function() { ... });
An event that is fired if there is an error making the request and the response callback has not been invoked. In this case the error event concludes the request attempt. The error event function receives an error object as parameter with a code
field and a message
field.
function httpCRq.write(data)
This function writes the data
argument as a string. Data that is passed in
(including arrays) will be converted to a string with the normal JavaScript
toString
method. For more information about sending binary data see Socket.write
data
- A string containing data to send
For node.js compatibility, returns the boolean false. When the send buffer is empty, a drain
event will be sent
The HTTP client response, passed to the callback of http.request()
an http.get()
.
function httpCRs.available()
Return how many bytes are available to read. If there is a 'data' event handler, this will always return 0.
How many bytes are available
httpCRs.on('close', function() { ... });
Called when the connection closes with one hadError
boolean parameter, which indicates whether an error occurred.
httpCRs.on('data', function(data) { ... });
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()
data
- A string containing one or more characters of received data
httpCRs.on('error', function() { ... });
An event that is fired if there is an error receiving the response. The error event function receives an error object as parameter with a code
field and a message
field. After the error event the close even will also be triggered to conclude the HTTP request/response.
function httpCRs.pipe(destination, options)
Pipe this to a stream (an object with a 'write' method)
Note: This is not available in devices with low flash memory
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
function httpCRs.read(chars)
Return a string containing characters that have been received
chars
- The number of characters to read, or undefined/0 for all available
A string containing the required bytes.
The HTTP server request
function httpSRq.available()
Return how many bytes are available to read. If there is already a listener for data, this will always return 0.
How many bytes are available
httpSRq.on('close', function() { ... });
Called when the connection closes.
httpSRq.on('data', function(data) { ... });
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()
data
- A string containing one or more characters of received data
function httpSRq.pipe(destination, options)
Pipe this to a stream (an object with a 'write' method)
Note: This is not available in devices with low flash memory
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
function httpSRq.read(chars)
Return a string containing characters that have been received
chars
- The number of characters to read, or undefined/0 for all available
A string containing the required bytes.
The HTTP server response
httpSRs.on('close', function() { ... });
Called when the connection closes.
httpSRs.on('drain', function() { ... });
An event that is fired when the buffer is empty and it can accept more data to send.
function httpSRs.end(data)
See Socket.write
for more information about the data argument
data
- A string containing data to send
function httpSRs.write(data)
This function writes the data
argument as a string. Data that is passed in
(including arrays) will be converted to a string with the normal JavaScript
toString
method. For more information about sending binary data see Socket.write
data
- A string containing data to send
For node.js compatibility, returns the boolean false. When the send buffer is empty, a drain
event will be sent
function httpSRs.writeHead(statusCode, headers)
statusCode
- The HTTP status code
headers
- An object containing the headers
The HTTP server created by require('http').createServer
function httpSrv.close()
Stop listening for new HTTP connections
function httpSrv.listen(port)
Start listening for new HTTP connections on the given port
port
- The port to listen on
The HTTP server instance that 'listen' was called on
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.
I2C.find(pin)
Try and find an I2C hardware device that will work on this pin (eg. I2C1
)
May return undefined if no device can be found.
pin
- A pin to search with
An object of type I2C
, or undefined
if one couldn't be found.
new I2C()
Create a software I2C port. This has limited functionality (no baud rate), but it can work on any pins.
Use I2C.setup
to configure this port.
function I2C.readFrom(address, quantity)
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
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
The data that was returned - as a Uint8Array
function I2C.setup(options)
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)
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 400kHz is the maximum bitrate for most parts.
This function is used in the following places in Espruino's documentation
function I2C.writeTo(address, data, ...)
Transmit to the slave device with the given address. This is like Arduino's beginTransmission, write, and endTransmission rolled up into one.
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:#}
.
This is the built-in JavaScript class for a typed array of 16 bit signed integers.
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).
Arrays of this type include all the methods from ArrayBufferView
new Int16Array(arr, byteOffset, length)
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.
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)
A typed array
This is the built-in JavaScript class for a typed array of 32 bit signed integers.
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).
Arrays of this type include all the methods from ArrayBufferView
new Int32Array(arr, byteOffset, length)
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.
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)
A typed array
This is the built-in JavaScript class for a typed array of 8 bit signed integers.
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).
Arrays of this type include all the methods from ArrayBufferView
new Int8Array(arr, byteOffset, length)
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.
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)
A typed array
The base class for internal errors
new InternalError(message)
Creates an InternalError object
message
- An optional message string
An InternalError object
function InternalError.toString()
A String
An Object that handles conversion to and from the JSON data interchange format
JSON.parse(string)
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.
string
- A JSON string
The JavaScript object created by parsing the data string
This function is used in the following places in Espruino's documentation
JSON.stringify(data, replacer, space)
Convert the given object into a JSON string which can subsequently be parsed with JSON.parse or eval.
Note: This differs from JavaScript's standard JSON.stringify
in that:
replacer
argument is ignorednew Uint8Array(5)
will be dumped as if they were arrays, not as if they were objects (since it is more compact)data
- The data to be converted to a JSON string
replacer
- This value is ignored
space
- The number of spaces to use for padding, a string, or null/undefined for no whitespace
A JSON string
This function is used in the following places in Espruino's documentation
This is a standard JavaScript class that contains useful Maths routines
Math.abs(x)
x
- A floating point value
The absolute value of x (eg, Math.abs(2)==2
, but also Math.abs(-2)==2
)
This function is used in the following places in Espruino's documentation
Math.acos(x)
x
- The value to get the arc cosine of
The arc cosine of x, between 0 and PI
Math.asin(x)
x
- The value to get the arc sine of
The arc sine of x, between -PI/2 and PI/2
Math.atan(x)
x
- The value to get the arc tangent of
The arc tangent of x, between -PI/2 and PI/2
Math.atan2(y, x)
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
The arctangent of Y/X, between -PI and PI
Math.ceil(x)
x
- The value to round up
x, rounded upwards to the nearest integer
Math.clip(x, min, max)
DEPRECATED - Please use E.clip()
instead. Clip a number to be between min and max (inclusive)
Note: This is not available in devices with low flash memory
x
- A floating point value to clip
min
- The smallest the value should be
max
- The largest the value should be
The value of x, clipped so as not to be below min or above max.
Math.cos(theta)
theta
- The angle to get the cosine of
The cosine of theta
This function is used in the following places in Espruino's documentation
Math.E
The value of E - 2.718281828459045
Math.exp(x)
x
- The value raise E to the power of
E^x
Math.floor(x)
x
- The value to round down
x, rounded downwards to the nearest integer
This function is used in the following places in Espruino's documentation
Math.LN10
The natural logarithm of 10 - 2.302585092994046
Math.LN2
The natural logarithm of 2 - 0.6931471805599453
Math.log(x)
x
- The value to take the logarithm (base E) root of
The log (base E) of x
This function is used in the following places in Espruino's documentation
Math.LOG10E
The base 10 logarithm of e - 0.4342944819032518
Math.LOG2E
The base 2 logarithm of e - 1.4426950408889634
Math.max(args, ...)
Find the maximum of a series of numbers
args, ...
- Floating point values to clip
The maximum of the supplied values
This function is used in the following places in Espruino's documentation
Math.min(args, ...)
Find the minimum of a series of numbers
args, ...
- Floating point values to clip
The minimum of the supplied values
This function is used in the following places in Espruino's documentation
Math.PI
The value of PI - 3.141592653589793
Math.pow(x, y)
x
- The value to raise to the power
y
- The power x should be raised to
x raised to the power y (x^y)
Math.random()
A random number between 0 and 1
This function is used in the following places in Espruino's documentation
Math.round(x)
x
- The value to round
x, rounded to the nearest integer
This function is used in the following places in Espruino's documentation
Math.sin(theta)
theta
- The angle to get the sine of
The sine of theta
This function is used in the following places in Espruino's documentation
Math.sqrt(x)
x
- The value to take the square root of
The square root of x
This function is used in the following places in Espruino's documentation
Math.SQRT1_2
The square root of 1/2 - 0.7071067811865476
Math.SQRT2
The square root of 2 - 1.4142135623730951
Math.tan(theta)
theta
- The angle to get the tangent of
The tangent of theta
Math.wrap(x, max)
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 not available in devices with low flash memory
x
- A floating point value to wrap
max
- The largest the value should be
The value of x, wrapped so as not to be below min or above max.
This function is used in the following places in Espruino's documentation
Built-in class that caches the modules used by the require
command
Modules.addCached(id, sourcecode)
Add the given module to the cache
id
- The module name to add
sourcecode
- The module's sourcecode
This function is used in the following places in Espruino's documentation
Modules.getCached()
Return an array of module names that have been cached
An array of module names
Modules.removeAllCached()
Remove all cached modules
Modules.removeCached(id)
Remove the given module from the list of cached modules
id
- The module name to remove
This library allows you to write to Neopixel/WS281x/APA10x LED strips
These use a high speed single-wire protocol which needs platform-specific implementation on some devices - hence this library to simplify things.
neopixel.write(pin, data)
Write to a strip of NeoPixel/WS281x/APA104/APA106/SK6812-style LEDs attached to the given pin.
// set just one pixel, red, green, blue
require("neopixel").write(B15, [255,0,0]);
// Produce an animated rainbow over 25 LEDs
var rgb = new Uint8ClampedArray(25*3);
var pos = 0;
function getPattern() {
pos++;
for (var i=0;i<rgb.length;) {
rgb[i++] = (1 + Math.sin((i+pos)*0.1324)) * 127;
rgb[i++] = (1 + Math.sin((i+pos)*0.1654)) * 127;
rgb[i++] = (1 + Math.sin((i+pos)*0.1)) * 127;
}
return rgb;
}
setInterval(function() {
require("neopixel").write(B15, getPattern());
}, 100);
Note:
Different types of LED have the data in different orders - so don't be surprised by RGB or BGR orderings!
On some platforms like STM32, pins capable of hardware SPI MOSI are required.
Espruino devices tend to have 3.3v IO, while WS2812/etc run
off of 5v. Many WS2812 will only register a logic '1' at 70%
of their input voltage - so if powering them off 5v you will not
be able to send them data reliably. You can work around this by
powering the LEDs off a lower voltage (for example 3.7v from a LiPo
battery), can put the output into the af_opendrain
state and use
a pullup resistor to 5v on STM32 based boards (nRF52 are not 5v tolerant
so you can't do this), or can use a level shifter to shift the voltage up
into the 5v range.
pin
- The Pin the LEDs are connected to
data
- The data to write to the LED strip
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.
net.connect(options, callback)
Create a TCP socket connection
options
- An object containing host,port fields
callback
- A function(sckt)
that will be called with the socket when a connection is made. You can then call sckt.write(...)
to send data, and sckt.on('data', function(data) { ... })
and sckt.on('close', function() { ... })
to deal with the response.
Returns a new net.Socket object
This function is used in the following places in Espruino's documentation
net.createServer(callback)
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
callback
- A function(connection)
that will be called when a connection is made
Returns a new Server Object
This function is used in the following places in Espruino's documentation
Library that initialises a network device that calls into JavaScript
NetworkJS.create(obj)
Initialise the network using the callbacks given and return the first argument. For instance:
require("NetworkJS").create({
create : function(host, port, socketType, options) {
// 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, socketType) {
// Receive data. Returns a string (even if empty).
// If non-string returned, socket is then closed
return null;//or "";
},
send : function(sckt, data, socketType) {
// Send data (as string). Returns the number of bytes sent - 0 is ok.
// Less than 0
return data.length;
}
});
socketType
is an integer - 2 for UDP, or see SocketType in https://github.com/espruino/Espruino/blob/master/libs/network/network.h
for more information.
obj
- An object containing functions to access the network device
The object passed in
This is a built-in class to allow you to use the ESP8266 NodeMCU boards's pin namings to access pins. It is only available on ESP8266-based boards.
NodeMCU.A0
A Pin
NodeMCU.D0
A Pin
NodeMCU.D1
A Pin
NodeMCU.D10
A Pin
NodeMCU.D2
A Pin
NodeMCU.D3
A Pin
NodeMCU.D4
A Pin
NodeMCU.D5
A Pin
NodeMCU.D6
A Pin
NodeMCU.D7
A Pin
NodeMCU.D8
A Pin
NodeMCU.D9
A Pin
The NRF class is for controlling functionality of the Nordic nRF51/nRF52 chips. This is used in Puck.js, Pixl.js, MDBT42Q, and a variety of other Bluetooth-based boards.
Most functionality is related to Bluetooth Low Energy, however there are also some functions related to NFC that apply to NRF52-based devices.
NRF.on('characteristicsDiscover', function() { ... });
Called with discovered characteristics when discovery is finished
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
NRF.on('connect', function(addr) { ... });
Called when a host device connects to Espruino. The first argument contains the address.
addr
- The address of the device that has connected
NRF.connect(mac)
Connect to a BLE device by MAC address. Returns a promise,
the argument of which is the BluetoothRemoteGATTServer
connection.
NRF.connect("aa:bb:cc:dd:ee").then(function(server) {
// ...
});
You can use it as follows - this would connect to another Puck device and turn its LED on:
var gatt;
NRF.connect("aa:bb:cc:dd:ee random").then(function(g) {
gatt = g;
return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
}).then(function(service) {
return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
}).then(function(characteristic) {
return characteristic.writeValue("LED1.set()\n");
}).then(function() {
gatt.disconnect();
console.log("Done!");
});
Note: Espruino Bluetooth devices use a type of BLE address known as 'random static',
which is different to a 'public' address. To connect to an Espruino device you'll need
to use an address string of the form "aa:bb:cc:dd:ee random"
rather than just
"aa:bb:cc:dd:ee"
. If you scan for devices with NRF.findDevices
/NRF.setScan
then
addresses are already reported in the correct format.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
mac
- The MAC address to connect to
A Promise that is resolved (or rejected) when the connection is complete
NRF.on('disconnect', function(reason) { ... });
Called when a host device disconnects from Espruino.
reason
- The reason code reported back by the BLE stack - see Nordic's ble_hci.h
file for more information
This function is used in the following places in Espruino's documentation
NRF.disconnect()
If a device is connected to Espruino, disconnect from it.
This function is used in the following places in Espruino's documentation
NRF.findDevices(callback, time)
Utility function to return a list of BLE devices detected in range. Behind the scenes,
this uses NRF.setScan(...)
and collates the results.
NRF.findDevices(function(devices) {
console.log(devices);
}, 1000);
prints something like:
[
BluetoothDevice {
"id": "e7:e0:57:ad:36:a2 random",
"rssi": -45,
"services": [ "4567" ],
"serviceData" : { "0123" : [ 1 ] },
"manufacturerData" : [...],
"data": new ArrayBuffer([ ... ]),
"name": "Puck.js 36a2"
},
BluetoothDevice {
"id": "c0:52:3f:50:42:c9 random",
"rssi": -65,
"data": new ArrayBuffer([ ... ]),
"name": "Puck.js 8f57"
}
]
For more information on the structure, see NRF.setScan
.
You could then use BluetoothDevice.gatt.connect(...)
on
the device returned, to make a connection.
You can also use NRF.connect(...)
on just the id
string returned, which
may be useful if you always want to connect to a specific device.
Note: Using findDevices turns the radio's receive mode on for 2000ms (or however long you specify). This can draw a lot of power (12mA or so), so you should use it sparingly or you can run your battery down quickly.
Note: The 'data' field contains the data of the last packet received. There may have been more
packets. To get data for each packet individually use NRF.setScan
instead.
callback
- The callback to call with received advertising packets, or undefined to stop
time
- The time in milliseconds to scan for (defaults to 2000)
NRF.getAddress()
Get this device's default Bluetooth MAC address.
For Puck.js, the last 5 characters of this (eg. ee:ff
)
are used in the device's advertised Bluetooth name.
MAC address - a string of the form 'aa:bb:cc:dd:ee:ff'
NRF.getAdvertisingData(data, options)
This is just like NRF.setAdvertising
, except instead of advertising
the data, it returns the packet that would be advertised as an array.
data
- The data to advertise as an object
options
- An optional object of options
An array containing the advertising data
NRF.getBattery()
Get the battery level in volts (the voltage that the NRF chip is running off of).
This is the battery level of the device itself - it has nothing to with any device that might be connected.
Battery level in volts
NRF.on('NFCoff', function() { ... });
Called when an NFC field is no longer detected
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
NRF.on('NFCon', function() { ... });
Called when an NFC field is detected
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
NRF.nfcRaw(payload)
Enables NFC and starts advertising with Raw data. For example:
NRF.nfcRaw(new Uint8Array([193, 1, 0, 0, 0, 13, 85, 3, 101, 115, 112, 114, 117, 105, 110, 111, 46, 99, 111, 109]));
// same as NRF.nfcURL("http://espruino.com");
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
payload
- The NFC NDEF message to deliver to the reader
NRF.on('NFCrx', function(arr) { ... });
When NFC is started with NRF.nfcStart
, this is fired
when NFC data is received. It doesn't get called if
NFC is started with NRF.nfcURL
or NRF.nfcRaw
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
arr
- An ArrayBuffer containign the received data
NRF.nfcSend(payload)
Advanced NFC Functionality. If you just want to advertise a URL, use NRF.nfcURL
instead.
Acknowledges the last frame and optionally transmits a response.
If payload is an array, then a array.length byte nfc frame is sent.
If payload is a int, then a 4bit ACK/NACK is sent.
Note: nfcSend
should always be called after an NFCrx
event.
NRF.nfcSend(new Uint8Array([0x01, 0x02, ...]));
// or
NRF.nfcSend(0x0A);
// or
NRF.nfcSend();
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
payload
- Optional tx data
NRF.nfcStart(payload)
Advanced NFC Functionality. If you just want to advertise a URL, use NRF.nfcURL
instead.
Enables NFC and starts advertising. NFCrx
events will be
fired when data is received.
NRF.nfcStart();
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
payload
- Optional 7 byte UID
Internal tag memory (first 10 bytes of tag data)
NRF.nfcStop()
Advanced NFC Functionality. If you just want to advertise a URL, use NRF.nfcURL
instead.
Disables NFC.
NRF.nfcStop();
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
NRF.nfcURL(url)
Enables NFC and starts advertising the given URL. For example:
NRF.nfcURL("http://espruino.com");
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
url
- The URL string to expose on NFC, or undefined
to disable NFC
NRF.requestDevice(options)
Search for available devices matching the given filters. Since we have no UI here,
Espruino will pick the FIRST device it finds, or it'll call catch
.
The following filter types are implemented:
services
- list of services as strings (all of which must match). 128 bit services must be in the form '01230123-0123-0123-0123-012301230123'name
- exact device namenamePrefix
- starting characters of device nameNRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) { ... });
// or
NRF.requestDevice({ filters: [{ services: ['1823'] }] }).then(function(device) { ... });
You can also specify a timeout to wait for devices in milliseconds. The default is 2 seconds (2000):
NRF.requestDevice({ timeout:2000, filters: [ ... ] })
As a full example, to send data to another Puck.js to turn an LED on:
var gatt;
NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) {
return device.gatt.connect();
}).then(function(g) {
gatt = g;
return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
}).then(function(service) {
return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
}).then(function(characteristic) {
return characteristic.writeValue("LED1.set()\n");
}).then(function() {
gatt.disconnect();
console.log("Done!");
});
Or slightly more concisely, using ES6 arrow functions:
var gatt;
NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }]}).then(
device => device.gatt.connect()).then(
g => (gatt=g).getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e")).then(
service => service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e")).then(
characteristic => characteristic.writeValue("LED1.reset()\n")).then(
() => { gatt.disconnect(); console.log("Done!"); } );
Note that you'll have to keep track of the gatt
variable so that you can
disconnect the Bluetooth connection when you're done.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
options
- Options used to filter the device to use
A Promise that is resolved (or rejected) when the connection is complete
NRF.restart()
Restart the Bluetooth softdevice (if there is currently a BLE connection, it will queue a restart to be done when the connection closes).
You shouldn't need to call this function in normal usage. However, Nordic's BLE softdevice has some settings that cannot be reset. For example there are only a certain number of unique UUIDs. Once these are all used the only option is to restart the softdevice to clear them all out.
NRF.sendHIDReport(data, callback)
Send a USB HID report. HID must first be enabled with NRF.setServices({}, {hid: hid_report})
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
data
- Input report data as an array
callback
- A callback function to be called when the data is sent
This function is used in the following places in Espruino's documentation
NRF.on('servicesDiscover', function() { ... });
Called with discovered services when discovery is finished
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q) and ESP32 boards
NRF.setAddress(addr)
Set this device's default Bluetooth MAC address:
NRF.setAddress("ff:ee:dd:cc:bb:aa random");
Addresses take the form:
"ff:ee:dd:cc:bb:aa"
or "ff:ee:dd:cc:bb:aa public"
for a public address"ff:ee:dd:cc:bb:aa random"
for a random static address (the default for Espruino)This may throw a INVALID_BLE_ADDR
error if the upper two bits
of the address don't match the address type.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
addr
- The address to use (as a string)
NRF.setAdvertising(data, options)
Change the data that Espruino advertises.
Data can be of the form { UUID : data_as_byte_array }
. The UUID should be
a Bluetooth Service ID.
For example to return battery level at 95%, do:
NRF.setAdvertising({
0x180F : [95]
});
Or you could report the current temperature:
setInterval(function() {
NRF.setAdvertising({
0x1809 : [Math.round(E.getTemperature())]
});
}, 30000);
You can also supply the raw advertising data in an array. For example to advertise as an Eddystone beacon:
NRF.setAdvertising([0x03, // Length of Service List
0x03, // Param: Service List
0xAA, 0xFE, // Eddystone ID
0x13, // Length of Service Data
0x16, // Service Data
0xAA, 0xFE, // Eddystone ID
0x10, // Frame type: URL
0xF8, // Power
0x03, // https://
'g','o','o','.','g','l','/','B','3','J','0','O','c'],
{interval:100});
(However for Eddystone we'd advise that you use the Espruino Eddystone library)
Note: When specifying data as an array, certain advertising options such as
discoverable
and showName
won't have any effect.
Note: The size of Bluetooth LE advertising packets is limited to 31 bytes. If
you want to advertise more data, consider using an array for data
(See below), or
NRF.setScanResponse
.
You can even specify an array of arrays or objects, in which case each advertising packet will be used in turn - for instance to make your device advertise both Eddystone and iBeacon:
NRF.setAdvertising([
{0x180F : [Puck.getBatteryPercentage()]}, // normal advertising, with battery %
require("ble_ibeacon").get(...), // iBeacon
require("ble_eddystone").get(...), // eddystone
],{interval:500});
options
is an object, which can contain:
{
name: "Hello" // The name of the device
showName: true/false // include full name, or nothing
discoverable: true/false // general discoverable, or limited - default is limited
connectable: true/false // whether device is connectable - default is true
interval: 600 // Advertising interval in msec, between 20 and 10000
manufacturer: 0x0590 // IF sending manufacturer data, this is the manufacturer ID
manufacturerData: [...] // IF sending manufacturer data, this is an array of data
}
So for instance to set the name of Puck.js without advertising any other data you can just use the command:
NRF.setAdvertising({},{name:"Hello"});
You can also specify 'manufacturer data', which is another form of advertising data. We've registered the Manufacturer ID 0x0590 (as Pur3 Ltd) for use with Official Espruino devices - use it to advertise whatever data you'd like, but we'd recommend using JSON.
data
- The data to advertise as an object - see below for more info
options
- An optional object of options
NRF.setLowPowerConnection(lowPower)
This sets the connection parameters - these affect the transfer speed and power usage when the device is connected.
When low power connection is enabled, transfers of data over Bluetooth will be very slow, however power usage while connected will be drastically decreased.
This will only take effect after the connection is disconnected and re-established.
lowPower
- Whether the connection is low power or not
NRF.setRSSIHandler(callback)
Start/stop listening for RSSI values on the currently active connection (where This device is a peripheral and is being connected to by a 'central' device)
// Start scanning
NRF.setRSSIHandler(function(rssi) {
console.log(rssi); // prints -85 (or similar)
});
// Stop Scanning
NRF.setRSSIHandler();
RSSI is the 'Received Signal Strength Indication' in dBm
callback
- The callback to call with the RSSI value, or undefined to stop
NRF.setScan(callback)
Start/stop listening for BLE advertising packets within range. Returns a
BluetoothDevice
for each advertsing packet. This is not an active scan, so
Scan Response advertising data is not included
// Start scanning
packets=10;
NRF.setScan(function(d) {
packets--;
if (packets<=0)
NRF.setScan(); // stop scanning
else
console.log(d); // print packet info
});
Each BluetoothDevice
will look a bit like:
BluetoothDevice {
"id": "aa:bb:cc:dd:ee:ff", // address
"rssi": -89, // signal strength
"services": [ "128bit-uuid", ... ], // zero or more service UUIDs
"data": new Uint8Array([ ... ]).buffer, // ArrayBuffer of returned data
"serviceData" : { "0123" : [ 1 ] }, // if service data is in 'data', it's extracted here
"manufacturer" : 0x1234, // if manufacturer data is in 'data', the 16 bit manufacturer ID is extracted here
"manufacturerData" : [...], // if manufacturer data is in 'data', the data is extracted here
"name": "DeviceName" // the advertised device name
}
Note: BLE advertising packets can arrive quickly - faster than you'll
be able to print them to the console. It's best only to print a few, or
to use a function like NRF.findDevices(..)
which will collate a list
of available devices.
Note: Using setScan turns the radio's receive mode on constantly. This can draw a lot of power (12mA or so), so you should use it sparingly or you can run your battery down quickly.
callback
- The callback to call with received advertising packets, or undefined to stop
NRF.setScanResponse(data)
The raw scan response data should be supplied as an array. For example to return "Sample" for the device name:
NRF.setScanResponse([0x07, // Length of Data
0x09, // Param: Complete Local Name
'S', 'a', 'm', 'p', 'l', 'e']);
Note: NRF.setServices(..., {advertise:[ ... ]})
writes advertised
services into the scan response - so you can't use both advertise
and NRF.setServices
or one will overwrite the other.
data
- The data to for the scan response
NRF.setServices(data, options)
Change the services and characteristics Espruino advertises.
If you want to change the value of a characteristic, you need
to use NRF.updateServices()
instead
To expose some information on Characteristic ABCD
on service BCDE
you could do:
NRF.setServices({
0xBCDE : {
0xABCD : {
value : "Hello",
readable : true
}
}
});
Or to allow the 3 LEDs to be controlled by writing numbers 0 to 7 to a
characteristic, you can do the following. evt.data
is an array of
bytes.
NRF.setServices({
0xBCDE : {
0xABCD : {
writable : true,
onWrite : function(evt) {
digitalWrite([LED3,LED2,LED1], evt.data[0]);
}
}
}
});
You can supply many different options:
NRF.setServices({
0xBCDE : {
0xABCD : {
value : "Hello", // optional
maxLen : 5, // optional (otherwise is length of initial value)
broadcast : false, // optional, default is false
readable : true, // optional, default is false
writable : true, // optional, default is false
notify : true, // optional, default is false
indicate : true, // optional, default is false
description: "My Characteristic", // optional, default is null
onWrite : function(evt) { // optional
console.log("Got ", evt.data);
}
}
// more characteristics allowed
}
// more services allowed
});
Note: UUIDs can be integers between 0
and 0xFFFF
, strings of
the form "ABCD"
, or strings of the form "ABCDABCD-ABCD-ABCD-ABCD-ABCDABCDABCD"
options
can be of the form:
NRF.setServices(undefined, {
hid : new Uint8Array(...), // optional, default is undefined. Enable BLE HID support
uart : true, // optional, default is true. Enable BLE UART support
advertise: [ '180D' ] // optional, list of service UUIDs to advertise
});
To enable BLE HID, you must set hid
to an array which is the BLE report
descriptor. The easiest way to do this is to use the ble_hid_controls
or ble_hid_keyboard
modules.
Note: Just creating a service doesn't mean that the service will
be advertised. It will only be available after a device connects. To
advertise, specify the UUIDs you wish to advertise in the advertise
field of the second options
argument. For example this will create
and advertise a heart rate service:
NRF.setServices({
0x180D: { // heart_rate
0x2A37: { // heart_rate_measurement
notify: true,
value : [0x06, heartrate],
}
}
}, { advertise: [ '180D' ] });
You may specify 128 bit UUIDs to advertise, however you may get a DATA_SIZE
exception because there is insufficient space in the Bluetooth LE advertising
packet for the 128 bit UART UUID as well as the UUID you specified. In this
case you can add uart:false
after the advertise
element to disable the
UART, however you then be unable to connect to Puck.js's console via Bluetooth.
If you absolutely require two or more 128 bit UUIDs then you will have to
specify your own raw advertising data packets with NRF.setAdvertising
data
- The service (and characteristics) to advertise
options
- Optional object containing options
NRF.setTxPower(power)
Set the BLE radio transmit power. The default TX power is 0 dBm.
power
- Transmit power. Accepted values are -40, -30, -20, -16, -12, -8, -4, 0, and 4 dBm. Others will give an error code.
NRF.setWhitelist(whitelisting)
If set to true, whenever a device bonds it will be added to the whitelist.
When set to false, the whitelist is cleared and newly bonded devices will not be added to the whitelist.
Note: This is remembered between reset()
s but isn't
remembered after power-on (you'll have to add it to onInit()
.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
whitelisting
- Are we using a whitelist? (default false)
NRF.sleep()
Disable Bluetooth advertising and disconnect from any device that connected to Puck.js as a peripheral (this won't affect any devices that Puck.js initiated connections to).
This makes Puck.js undiscoverable, so it can't be connected to.
Use NRF.wake()
to wake up and make Puck.js connectable again.
This function is used in the following places in Espruino's documentation
NRF.updateServices(data)
Update values for the services and characteristics Espruino advertises.
Only services and characteristics previously declared using setServices
are affected.
To update the '0xABCD' characteristic in the '0xBCDE' service:
NRF.updateServices({
0xBCDE : {
0xABCD : {
value : "World"
}
}
});
You can also use 128 bit UUIDs, for example "b7920001-3c1b-4b40-869f-3c0db9be80c6"
.
To define a service and characteristic and then notify connected clients of a change to it when a button is pressed:
NRF.setServices({
0xBCDE : {
0xABCD : {
value : "Hello",
maxLen : 20,
notify: true
}
}
});
setWatch(function() {
NRF.updateServices({
0xBCDE : {
0xABCD : {
value : "World!",
notify: true
}
}
});
}, BTN, { repeat:true, edge:"rising", debounce: 50 });
This only works if the characteristic was created with notify: true
using setServices
,
otherwise the characteristic will be updated but no notification will be sent.
Also note that maxLen
was specified. If it wasn't then the maximum length of
the characteristic would have been 5 - the length of "Hello"
.
To indicate (i.e. notify with ACK) connected clients of a change to the '0xABCD' characteristic in the '0xBCDE' service:
NRF.updateServices({
0xBCDE : {
0xABCD : {
value : "World",
indicate: true
}
}
});
This only works if the characteristic was created with indicate: true
using setServices
,
otherwise the characteristic will be updated but no notification will be sent.
Note: See NRF.setServices
for more information
data
- The service (and characteristics) to update
NRF.wake()
Enable Bluetooth advertising (this is enabled by default), which allows other devices to discover and connect to Puck.js.
Use NRF.sleep()
to disable advertising.
This is the built-in class for the Arduino-style pin namings on ST Nucleo boards
Nucleo.A0
A Pin
Nucleo.A1
A Pin
Nucleo.A2
A Pin
Nucleo.A3
A Pin
Nucleo.A4
A Pin
Nucleo.A5
A Pin
Nucleo.D0
A Pin
Nucleo.D1
A Pin
Nucleo.D10
A Pin
Nucleo.D11
A Pin
Nucleo.D12
A Pin
Nucleo.D13
A Pin
Nucleo.D14
A Pin
Nucleo.D15
A Pin
Nucleo.D2
A Pin
Nucleo.D3
A Pin
Nucleo.D4
A Pin
Nucleo.D5
A Pin
Nucleo.D6
A Pin
Nucleo.D7
A Pin
Nucleo.D8
A Pin
Nucleo.D9
A Pin
This is the built-in JavaScript class for numbers.
Number.MAX_VALUE
Maximum representable value
Number.MIN_VALUE
Smallest representable value
Number.NaN
Not a Number
Number.NEGATIVE_INFINITY
Negative Infinity (-1/0)
new Number(value, ...)
Creates a number
value, ...
- A single value to be converted to a number
A Number object
Number.POSITIVE_INFINITY
Positive Infinity (1/0)
function Number.toFixed(decimalPlaces)
Format the number as a fixed point number
decimalPlaces
- A number between 0 and 20 specifying the number of decimal digits after the decimal point
A string
This is the built-in class for Objects
Object.assign(args, ...)
Appends all keys and values in any subsequent objects to the first object
Note: Unlike the standard ES6 Object.assign
, this will throw an exception
if given raw strings, bools or numbers rather than objects.
args, ...
- The target object, then any items objects to use as sources of keys
The target object
function Object.clone()
Copy this object completely
A copy of this Object
Object.create(proto, propertiesObject)
Creates a new object with the specified prototype object and properties. properties are currently unsupported.
proto
- A prototype object
propertiesObject
- An object containing properties. NOT IMPLEMENTED
A new object
Object.defineProperties(obj, props)
Adds new properties to the Object. See Object.defineProperty
for more information
obj
- An object
props
- An object whose fields represent property names, and whose values are property descriptors.
The object, obj.
Object.defineProperty(obj, name, desc)
Add a new property to the Object. 'Desc' is an object with the following fields:
configurable
(bool = false) - can this property be changed/deletedenumerable
(bool = false) - can this property be enumeratedvalue
(anything) - the value of this propertywritable
(bool = false) - can the value be changed with the assignment operator?get
(function) - the getter function, or undefined if no getterset
(function) - the setter function, or undefined if no setter
*
Note: configurable
, enumerable
, writable
, get
, and set
are not implemented and will be ignored.obj
- An object
name
- The name of the property
desc
- The property descriptor
The object, obj.
function Object.emit(event, args, ...)
Call the event listeners for this object, for instance http.emit('data', 'Foo')
. See Node.js's EventEmitter.
event
- The name of the event, for instance 'data'
args, ...
- Optional arguments
Object.getOwnPropertyDescriptor(obj, name)
Get information on the given property in the object, or undefined
obj
- The object
name
- The name of the property
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(object)
Returns an array of all properties (enumerable or not) found directly on a given object.
object
- The Object to return a list of property names for
An array of the Object's own properties
Object.getPrototypeOf(object)
Get the prototype of the given object - this is like writing object.__proto__
but is the 'proper' ES6 way of doing it
object
- An object
The prototype
function Object.hasOwnProperty(name)
Return true if the object (not its prototype) has the given property.
NOTE: This currently returns false-positives for built-in functions in prototypes
name
- The name of the property to search for
True if it exists, false if it doesn't
Object.keys(object)
Return all enumerable keys of the given object
object
- The object to return keys for
An array of strings - one for each key on the given object
property Object.length
Find the length of the object
The length of the object
new Object(value)
Creates an Object from the supplied argument
value
- A single value to be converted to an object
An Object
function Object.on(event, listener)
Register an event listener for this object, for instance http.on('data', function(d) {...})
. See Node.js's EventEmitter.
event
- The name of the event, for instance 'data'
listener
- The listener to call when this event is received
This function is used in the following places in Espruino's documentation
function Object.removeAllListeners(event)
Removes all listeners, or those of the specified event.
event
- The name of the event, for instance 'data'
This function is used in the following places in Espruino's documentation
function Object.removeListener(event, listener)
Removes the specified event listener.
function foo(d) {
console.log(d);
}
Serial1.on("data", foo);
Serial1.removeListener("data", foo);
event
- The name of the event, for instance 'data'
listener
- The listener to remove
Object.setPrototypeOf(object, prototype)
Set the prototype of the given object - this is like writing
object.__proto__ = prototype
but is the 'proper' ES6 way of doing it
object
- An object
prototype
- The prototype to set on the object
The object passed in
function Object.toString(radix)
Convert the Object to a string
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.
A String representing the object
This function is used in the following places in Espruino's documentation
function Object.valueOf()
Returns the primitive value of this object.
The primitive value of this object
This class provides a software-defined OneWire master. It is designed to be similar to Arduino's OneWire library.
new OneWire(pin)
Create a software OneWire implementation on the given pin
pin
- The pin to implement OneWire on
A OneWire object
function OneWire.read(count)
Read a byte
count
- (optional) The amount of bytes to read
The byte that was read, or a Uint8Array if count was specified and >=0
function OneWire.reset()
Perform a reset cycle
True is a device was present (it held the bus low)
function OneWire.search()
Search for devices
An array of devices that were found
This function is used in the following places in Espruino's documentation
function OneWire.search(command)
Search for devices
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'
An array of devices that were found
This function is used in the following places in Espruino's documentation
function OneWire.select(rom)
Select a ROM - always performs a reset first
rom
- The device to select (get this using OneWire.search()
)
function OneWire.skip()
Skip a ROM
function OneWire.write(data, power)
Write one or more bytes
data
- A byte (or array of bytes) to write
power
- Whether to leave power on after write (default is false)
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
function Pin.getInfo()
Get information about this pin and its capabilities. Of the form:
{
"port" : "A", // the Pin's port on the chip
"num" : 12, // the Pin's number
"in_addr" : 0x..., // (if available) the address of the pin's input address in bit-banded memory (can be used with peek)
"out_addr" : 0x..., // (if available) the address of the pin's output address in bit-banded memory (can be used with poke)
"analog" : { ADCs : [1], channel : 12 }, // If analog input is available
"functions" : {
"TIM1":{type:"CH1, af:0},
"I2C3":{type:"SCL", af:1}
}
}
Will return undefined if pin is not valid.
Note: This is not available in devices with low flash memory
An object containing information about this pins
function Pin.getMode()
Return the current mode of the given pin. See pinMode
for more information.
The pin mode, as a string
function Pin.mode(mode)
Set the mode of the given pin. See pinMode
for more information on pin modes.
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.
new Pin(value)
Creates a pin from the given argument (or returns undefined if no argument)
value
- A value to be converted to a pin. Can be a number, pin, or String.
A Pin object
function Pin.read()
Returns the input state of the pin as a boolean.
Note: if you didn't call pinMode
beforehand then this function will also reset the pin's state to "input"
Whether pin is a logical 1 or 0
This function is used in the following places in Espruino's documentation
function Pin.reset()
Sets the output state of the pin to a 0
Note: if you didn't call pinMode
beforehand then this function will also reset the pin's state to "output"
function Pin.set()
Sets the output state of the pin to a 1
Note: if you didn't call pinMode
beforehand then this function will also reset the pin's state to "output"
function Pin.toggle()
Toggles the state of the pin from off to on, or from on to off.
Note: This method doesn't currently work on the ESP8266 port of Espruino.
Note: if you didn't call pinMode
beforehand then this function will also reset the pin's state to "output"
True if the pin is high after calling the function
function Pin.write(value)
Sets the output state of the pin to the parameter given
Note: if you didn't call pinMode
beforehand then this function will also reset the pin's state to "output"
value
- Whether to set output high (true/1) or low (false/0)
function Pin.writeAtTime(value, time)
Sets the output state of the pin to the parameter given at the specified time.
Note: 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')
first.
Note: This is not available in devices with low flash memory
value
- Whether to set output high (true/1) or low (false/0)
time
- Time at which to write
Class containing utility functions for Pixl.js
Pixl.getBatteryPercentage()
DEPRECATED - Please use E.getBattery()
instead.
Return an approximate battery percentage remaining based on a normal CR2032 battery (2.8 - 2.2v)
A percentage between 0 and 100
Pixl.lcdw(c)
Writes a command directly to the ST7567 LCD controller
c
-
Pixl.menu(menu)
Display a menu on Pixl.js's screen, and set up the buttons to navigate through it.
Supply an object containing menu items. When an item is selected, the function it references will be executed. For example:
``` // First menu var mainmenu = { "" : { "title" : "-- Main Menu --" }, "Backlight On" : function() { LED1.set(); }, "Backlight Off" : function() { LED1.reset(); }, "Submenu" : function() { Pixl.menu(submenu); }, "Exit" : function() { Pixl.menu(); }, };
// Submenu var submenu = { "" : { "title" : "-- SubMenu --" }, "One" : undefined, // do nothing "Two" : undefined, // do nothing "< Back" : function() { Pixl.menu(mainmenu); }, };
Pixl.menu(mainmenu); ```
See http://www.espruino.com/graphical_menu for more detailed information.
menu
- An object containing name->function mappings to to be used in a menu
A menu object with draw
, move
and select
functions
Pixl.setContrast(c)
Set the LCD's contrast
c
- Contrast between 0 and 1
This class contains information about Espruino itself
process.env
Returns an Object containing various pre-defined variables. standard ones are BOARD, VERSION
An object
process.memory()
Run a Garbage Collection pass, and return an object containing information on memory usage.
free
: Memory that is available to be used (in blocks)usage
: Memory that has been used (in blocks)total
: Total memory (in blocks)history
: Memory used for command history - that is freed if memory is low. Note that this is INCLUDED in the figure for 'free'gc
: Memory freed during the GC passgctime
: Time taken for GC pass (in milliseconds)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.flash_start
: (on ARM) the address of the start of flash memory (usually 0x8000000
)flash_binary_end
: (on ARM) the address in flash memory of the end of Espruino's firmware.flash_code_start
: (on ARM) the address in flash memory of pages that store any code that you save with save()
.flash_length
: (on ARM) the amount of flash memory this firmware was built for (in bytes). Note: Some STM32 chips actually have more memory than is advertised.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.
Note: To find free areas of flash memory, see require('Flash').getFree()
Information about memory usage
This function is used in the following places in Espruino's documentation
process.on('uncaughtException', function() { ... });
This event is called when an exception gets thrown and isn't caught (eg. it gets all the way back to the event loop).
You can use this for logging potential problems that might occur during execution.
Note: When this is used, exceptions will cease to be reported on the console - which may make debugging difficult!
process.version
Returns the version of Espruino as a String
The version of Espruino
This is the built-in class for ES6 Promises
Promise.all(promises)
Return a new promise that is resolved when all promises in the supplied array are resolved.
Note: This is not available in devices with low flash memory
promises
- An array of promises
A new Promise
function Promise.catch(onRejected)
onRejected
- A callback that is called when this promise is rejected
The original Promise
new Promise(executor)
Create a new Promise. The executor function is executed immediately (before the constructor even returns) and
Note: This is not available in devices with low flash memory
executor
- A function of the form function (resolve, reject)
A Promise
Promise.reject(promises)
Return a new promise that is already rejected (at idle it'll
call .catch
)
Note: This is not available in devices with low flash memory
promises
- Data to pass to the .catch
handler
A new Promise
Promise.resolve(promises)
Return a new promise that is already resolved (at idle it'll
call .then
)
Note: This is not available in devices with low flash memory
promises
- Data to pass to the .then
handler
A new Promise
function Promise.then(onFulfilled, onRejected)
onFulfilled
- A callback that is called when this promise is resolved
onRejected
- A callback that is called when this promise is rejected (or nothing)
The original Promise
Class containing Puck.js's utility functions.
Puck.capSense(tx, rx)
Capacitive sense - the higher the capacitance, the higher the number returned.
If called without arguments, a value depending on the capacitance of what is attached to pin D11 will be returned. If you attach a length of wire to D11, you'll be able to see a higher value returned when your hand is near the wire than when it is away.
You can also supply pins to use yourself, however if you do this then the TX pin must be connected to RX pin and sense plate via a roughly 1MOhm resistor.
When not supplying pins, Puck.js uses an internal resistor between D12(tx) and D11(rx).
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
tx
-
rx
-
Capacitive sense counter
Puck.getBatteryPercentage()
DEPRECATED - Please use E.getBattery()
instead.
Return an approximate battery percentage remaining based on a normal CR2032 battery (2.8 - 2.2v).
A percentage between 0 and 100
Puck.IR(data, cathode, anode)
Transmit the given set of IR pulses - data should be an array of pulse times
in milliseconds (as [on, off, on, off, on, etc]
).
For example Puck.IR(pulseTimes)
- see http://www.espruino.com/Puck.js+Infrared
for a full example.
You can also attach an external LED to Puck.js, in which case
you can just execute Puck.IR(pulseTimes, led_cathode, led_anode)
data
- An array of pulse lengths, in milliseconds
cathode
- (optional) pin to use for IR LED cathode - if not defined, the built-in IR LED is used
anode
- (optional) pin to use for IR LED anode - if not defined, the built-in IR LED is used
This function is used in the following places in Espruino's documentation
Puck.light()
Return a light value based on the light the red LED is seeing.
Note: If called more than 5 times per second, the received light value may not be accurate.
Note: This is only available in NRF52 devices (like Puck.js, Pixl.js and MDBT42Q)
A light value from 0 to 1
Puck.mag()
Turn on the magnetometer, take a single reading, and then turn it off again.
An object of the form {x,y,z}
is returned containing magnetometer readings.
Due to residual magnetism in the Puck and magnetometer itself, with
no magnetic field the Puck will not return {x:0,y:0,z:0}
.
Instead, it's up to you to figure out what the 'zero value' is for your Puck in your location and to then subtract that from the value returned. If you're not trying to measure the Earth's magnetic field then it's a good idea to just take a reading at startup and use that.
With the aerial at the top of the board, the y
reading is vertical, x
is
horizontal, and z
is through the board.
Readings are in increments of 0.1 micro Tesla (uT). The Earth's magnetic field varies from around 25-60 uT, so the reading will vary by 250 to 600 depending on location.
An Object {x,y,z}
of magnetometer readings as integers
This function is used in the following places in Espruino's documentation
Puck.on('mag', function() { ... });
Called after Puck.magOn()
every time magnetometer data
is sampled. There is one argument which is an object
of the form {x,y,z}
containing magnetometer readings
as integers (for more information see Puck.mag()
).
This function is used in the following places in Espruino's documentation
Puck.magOff()
Turn the magnetometer off
Puck.magOn(samplerate)
Turn the magnetometer on and start periodic sampling. Samples will then cause a 'mag' event on 'Puck':
Puck.magOn();
Puck.on('mag', function(xyz) {
console.log(xyz);
});
// Turn events off with Puck.magOff();
This call will be ignored if the sampling is already on.
If given an argument, the sample rate is set (if not, it's at 0.63 Hz). The sample rate must be one of the following (resulting in the given power consumption):
When the battery level drops too low while sampling is turned on, the magnetometer may stop sampling without warning, even while other Puck functions continue uninterrupted.
samplerate
- The sample rate in Hz, or undefined
Puck.magTemp()
Turn on the magnetometer, take a single temperature reading from the MAG3110 chip, and then turn it off again.
(If the magnetometer is already on, this just returns the last reading obtained)
E.getTemperature()
uses the microcontroller's temperature sensor, but this uses the magnetometer's.
The reading obtained is an integer (so no decimal places), but the sensitivity is factory trimmed. to 1°C, however the temperature offset isn't - so absolute readings may still need calibrating.
Temperature in degrees C
Puck.selfTest()
Run a self-test, and return true for a pass. This checks for shorts between pins, so your Puck shouldn't have anything connected to it.
Note: This self-test auto starts if you hold the button on your Puck down while inserting the battery, leave it pressed for 3 seconds (while the green LED is lit) and release it soon after all LEDs turn on. 5 red blinks is a fail, 5 green is a pass.
True if the self-test passed
The base class for reference errors - where a variable which doesn't exist has been accessed.
new ReferenceError(message)
Creates a ReferenceError object
message
- An optional message string
A ReferenceError object
function ReferenceError.toString()
A String
The built-in class for handling Regular Expressions
Note: Espruino's regular expression parser does not contain all the features present in a full ES6 JS engine. However it does contain support for the all the basics.
function RegExp.exec(str)
Test this regex on a string - returns a result array on success, or null
otherwise.
/Wo/.exec("Hello World")
will return:
[
"Wo",
"index": 6,
"input": "Hello World"
]
Or with groups /W(o)rld/.exec("Hello World")
returns:
[
"World",
"o", "index": 6,
"input": "Hello World"
]
Note: This is not available in devices with low flash memory
str
- A string to match on
A result array, or null
new RegExp(regex, regex)
Creates a RegExp object, for handling Regular Expressions
Note: This is not available in devices with low flash memory
regex
- A regular expression as a string
regex
- Flags for the regular expression as a string
A RegExp object
function RegExp.test(str)
Test this regex on a string - returns true
on a successful match, or false
otherwise
Note: This is not available in devices with low flash memory
str
- A string to match on
true for a match, or false
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
Bluetooth
The Bluetooth Serial port - used when data is sent or received over Bluetooth Smart on nRF51/nRF52 chips.LoopbackA
A loopback serial device. Data sent to LoopbackA comes out of LoopbackB and vice versaLoopbackB
A loopback serial device. Data sent to LoopbackA comes out of LoopbackB and vice versaSerial1
The first Serial (USART) portSerial2
The second Serial (USART) portSerial3
The third Serial (USART) portSerial4
The fourth Serial (USART) portSerial5
The fifth Serial (USART) portSerial6
The sixth Serial (USART) portTelnet
A telnet serial device that maps to the built-in telnet console server (devices that have
built-in wifi only).Terminal
A simple VT100 terminal emulator.When data is sent to this, it searches for a Graphics variable called either
g
or LCD
and starts writing characters to it.
* USB
The USB Serial port
function Serial.available()
Return how many bytes are available to read. If there is already a listener for data, this will always return 0.
How many bytes are available
Serial.on('data', function(data) { ... });
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()
data
- A string containing one or more characters of received data
Serial.find(pin)
Try and find a USART (Serial) hardware device that will work on this pin (eg. Serial1
)
May return undefined if no device can be found.
pin
- A pin to search with
An object of type Serial
, or undefined
if one couldn't be found.
Serial.on('framing', function() { ... });
The framing
event is called when there was activity on the input to the UART
but the STOP
bit wasn't in the correct place. This is either because there
was noise on the line, or the line has been pulled to 0 for a long period
of time.
To enable this, you must initialise Serial with SerialX.setup(..., { ..., errors:true });
Note: Even though there was an error, the byte will still be received and
passed to the data
handler.
Note: This only works on STM32 and NRF52 based devices (eg. all official Espruino boards)
function Serial.inject(data, ...)
Add data to this device as if it came directly from the input - it will be
returned via serial.on('data', ...)
;
Serial1.on('data', function(d) { print("Got",d); });
Serial1.inject('Hello World');
// prints "Got Hel","Got lo World" (characters can be split over multiple callbacks)
This is most useful if you wish to send characters to Espruino's REPL (console) while it is on another device.
data, ...
- One or more items to write. May be ints, strings, arrays, or objects of the form {data: ..., count:#}
.
Serial.on('parity', function() { ... });
The parity
event is called when the UART was configured with a parity bit,
and this doesn't match the bits that have actually been received.
To enable this, you must initialise Serial with SerialX.setup(..., { ..., errors:true });
Note: Even though there was an error, the byte will still be received and
passed to the data
handler.
Note: This only works on STM32 and NRF52 based devices (eg. all official Espruino boards)
function Serial.pipe(destination, options)
Pipe this USART to a stream (an object with a 'write' method)
Note: This is not available in devices with low flash memory
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
This function is used in the following places in Espruino's documentation
function Serial.print(string)
Print a string to the serial port - without a line feed
Note: This function replaces any occurances of \n
in the string with \r\n
. To avoid this, use Serial.write
.
string
- A String to print
This function is used in the following places in Espruino's documentation
function Serial.println(string)
Print a line to the serial port with a newline (\r\n
) at the end of it.
Note: This function converts data to a string first, eg Serial.print([1,2,3])
is equivalent to Serial.print("1,2,3"). If you'd like to write raw bytes, use
Serial.write`.
string
- A String to print
This function is used in the following places in Espruino's documentation
function Serial.read(chars)
Return a string containing characters that have been received
chars
- The number of characters to read, or undefined/0 for all available
A string containing the required bytes.
function Serial.setConsole(force)
Set this Serial port as the port for the JavaScript console (REPL).
Unless force
is set to true, changes in the connection state of the board
(for instance plugging in USB) will cause the console to change.
force
- Whether to force the console to this port
This function is used in the following places in Espruino's documentation
function Serial.setup(baudrate, options)
Setup this Serial port with the given baud rate and options.
{
rx:pin, // Receive pin (data in to Espruino)
tx:pin, // Transmit pin (data out of Espruino)
ck:pin, // (default none) Clock Pin
cts:pin, // (default none) Clear to Send Pin
bytesize:8, // (default 8)How many data bits - 7 or 8
parity:null/'none'/'o'/'odd'/'e'/'even',
// (default none) Parity bit
stopbits:1, // (default 1) Number of stop bits to use
flow:null/undefined/'none'/'xon', // (default none) software flow control
path:null/undefined/string // Linux Only - the path to the Serial device to use
errors:false // (default false) whether to forward framing/parity errors
}
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.
If not specified in options, the default pins are used for rx and tx
(usually the lowest numbered pins on the lowest port that supports
this peripheral). ck
and cts
are not used unless specified.
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
or
pinMode
.
Flow control can be xOn/xOff (flow:'xon'
) or hardware flow control
(receive only) if cts
is specified. If cts
is set to a pin, the
pin's value will be 0 when Espruino is ready for data and 1 when it isn't.
By default, framing or parity errors don't create framing
or parity
events
on the Serial
object because storing these errors uses up additional
storage in the queue. If you're intending to receive a lot of malformed
data then the queue mioght overflow E.getErrorFlags()
would return FIFO_FULL
.
However if you need to respond to framing
or parity
errors then
you'll need to use errors:true
when initialising serial.
baudrate
- The baud rate - the default is 9600
options
- An optional structure containing extra information on initialising the serial port - see below.
function Serial.write(data, ...)
Write a character or array of data to the serial port
This method writes unmodified data, eg Serial.write([1,2,3])
is equivalent to Serial.write("\1\2\3")
. If you'd like data converted to a string first, use Serial.print
.
data, ...
- One or more items to write. May be ints, strings, arrays, or objects of the form {data: ..., count:#}
.
This function is used in the following places in Espruino's documentation
The socket server created by require('net').createServer
function Server.close()
Stop listening for new connections
function Server.listen(port)
Start listening for new connections on the given port
port
- The port to listen on
The HTTP server instance that 'listen' was called on
An actual socket connection - allowing transmit/receive of TCP data
function Socket.available()
Return how many bytes are available to read. If there is already a listener for data, this will always return 0.
How many bytes are available
Socket.on('close', function(had_error) { ... });
Called when the connection closes.
had_error
- A boolean indicating whether the connection had an error (use an error event handler to get error details).
Socket.on('data', function(data) { ... });
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()
data
- A string containing one or more characters of received data
Socket.on('drain', function() { ... });
An event that is fired when the buffer is empty and it can accept more data to send.
function Socket.end(data)
Close this socket - optional data to append as an argument.
See Socket.write
for more information about the data argument
data
- A string containing data to send
Socket.on('error', function(details) { ... });
There was an error on this socket and it is closing (or wasn't opened in the first place). If a "connected" event was issued on this socket then the error event is always followed by a close event. The error codes are:
details
- An error object with an error code (a negative integer) and a message.
function Socket.pipe(destination, options)
Pipe this to a stream (an object with a 'write' method)
Note: This is not available in devices with low flash memory
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
function Socket.read(chars)
Return a string containing characters that have been received
chars
- The number of characters to read, or undefined/0 for all available
A string containing the required bytes.
function Socket.write(data)
This function writes the data
argument as a string. Data that is passed in
(including arrays) will be converted to a string with the normal JavaScript
toString
method.
If you wish to send binary data then you need to convert that data directly to a
String. This can be done with String.fromCharCode
, however it's often easier
and faster to use the Espruino-specific E.toString
, which will read its arguments
as an array of bytes and convert that to a String:
socket.write(E.toString([0,1,2,3,4,5]));
If you need to send something other than bytes, you can use 'Typed Arrays', or
even DataView
:
var d = new DataView(new ArrayBuffer(8)); // 8 byte array buffer
d.setFloat32(0, 765.3532564); // write float at bytes 0-3
d.setInt8(4, 42); // write int8 at byte 4
socket.write(E.toString(d.buffer))
data
- A string containing data to send
For node.js compatibility, returns the boolean false. When the send buffer is empty, a drain
event will be sent
This class allows use of the built-in SPI ports. Currently it is SPI master only.
SPI.find(pin)
Try and find an SPI hardware device that will work on this pin (eg. SPI1
)
May return undefined if no device can be found.
pin
- A pin to search with
An object of type SPI
, or undefined
if one couldn't be found.
function SPI.send(data, nss_pin)
Send data down SPI, and return the result. Sending an integer will return an integer, a String will return a String, and anything else will return a Uint8Array.
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. Note that you can even pass arrays of arrays, like [1,[2,3,4],5]
data
- The data to send - either an Integer, Array, String, or Object of the form {data: ..., count:#}
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.
The data that was returned
This function is used in the following places in Espruino's documentation
function SPI.send4bit(data, bit0, bit1, nss_pin)
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.
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.
function SPI.send8bit(data, bit0, bit1, nss_pin)
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 not available in devices with low flash memory
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
function SPI.setup(options)
Set up this SPI port as an SPI Master.
Note: When using Software SPI, the baud rate will be ignored - data is sent as fast as possible.
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.
This function is used in the following places in Espruino's documentation
new SPI()
Create a software SPI port. This has limited functionality (no baud rate), but it can work on any pins.
Use SPI.setup
to configure this port.
function SPI.write(data, ...)
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.
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
This module allows you to read and write part of the nonvolatile flash memory of your device using a filesystem-like API.
Also see the Flash
library, which provides a low level, more dangerous way
to access all parts of your flash memory.
Storage.compact()
The Flash Storage system is journaling. To make the most of the limited
write cycles of Flash memory, Espruino marks deleted/replaced files as
garbage and moves on to a fresh part of flash memory. Espruino only
fully erases those files when it is running low on flash, or when
compactFiles
is called.
compactFiles
may fail if there isn't enough RAM free on the stack to
use as swap space, however in this case it will not lose data.
Note: compactFiles
rearranges the contents of memory. If code is
referencing that memory (eg. functions that have their code stored in flash)
then they may become garbled when compaction happens. To avoid this,
call eraseFiles
before uploading data that you intend to reference to
ensure that uploaded files are right at the start of flash and cannot be
compacted further.
Note: This is not available in devices with low flash memory
Storage.debug()
This writes information about all blocks in flash memory to the console - and is only useful for debugging flash storage.
Note: This is only available in debug builds
Storage.erase(name)
Erase a single file from the flash storage area.
Note: This is not available in devices with low flash memory
name
- The filename - max 8 characters (case sensitive)
Storage.eraseAll()
Erase the flash storage area. This will remove all files
created with require("Storage").write(...)
as well
as any code saved with save()
or E.setBootCode()
.
Note: This is not available in devices with low flash memory
Storage.list()
List all files in the flash storage area. An array of Strings is returned.
Note: This will output system files (eg. saved code) as well as files that you may have written.
Note: This is not available in devices with low flash memory
An array of filenames
Storage.read(name)
Read a file from the flash storage area that has
been written with require("Storage").write(...)
.
This function returns a String that points to the actual memory area in read-only memory, so it won't use up RAM.
If you evaluate this string with eval
, any functions
contained in the String will keep their code stored
in flash memory.
Note: This is not available in devices with low flash memory
name
- The filename - max 8 characters (case sensitive)
A string of data
Storage.readArrayBuffer(name)
Read a file from the flash storage area that has
been written with require("Storage").write(...)
,
and return the raw binary data as an ArrayBuffer.
This can be used:
DataView
with new DataView(require("Storage").readArrayBuffer("x"))
Uint8Array/Float32Array/etc
with new Uint8Array(require("Storage").readArrayBuffer("x"))
Note: This is not available in devices with low flash memory
name
- The filename - max 8 characters (case sensitive)
An ArrayBuffer containing data from the file, or undefined
Storage.readJSON(name)
Read a file from the flash storage area that has
been written with require("Storage").write(...)
,
and parse JSON in it into a JavaScript object.
This is identical to JSON.parse(require("Storage").read(...))
Note: This is not available in devices with low flash memory
name
- The filename - max 8 characters (case sensitive)
An object containing parsed JSON from the file, or undefined
Storage.write(name, data, offset, size)
Write/create a file in the flash storage area. This is nonvolatile and will not disappear when the device resets or power is lost.
Simply write require("Storage").write("MyFile", "Some data")
to write
a new file, and require("Storage").read("MyFile")
to read it.
If you supply:
You may also create a file and then populate data later as long as you don't try and overwrite data that already exists. For instance:
var f = require("Storage");
f.write("a","Hello",0,14);
f.write("a"," ",5);
f.write("a","World!!!",6);
print(f.read("a"));
This can be useful if you've got more data to write than you have RAM available.
Note: This is not available in devices with low flash memory
name
- The filename - max 8 characters (case sensitive)
data
- The data to write
offset
- The offset within the file to write
size
- The size of the file (if a file is to be created that is bigger than the data)
True on success, false on failure
This is the built-in class for Text Strings.
Text Strings in Espruino are not zero-terminated, so you can store zeros in them.
function String.charAt(pos)
Return a single character at the given position in the String.
pos
- The character number in the string. Negative values return characters from end of string (-1 = last char)
The character in the string
function String.charCodeAt(pos)
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
pos
- The character number in the string. Negative values return characters from end of string (-1 = last char)
The integer value of a character in the string
String.fromCharCode(code, ...)
Return the character(s) represented by the given character code(s).
code, ...
- One or more character codes to create a string from (range 0-255).
The character
This function is used in the following places in Espruino's documentation
function String.indexOf(substring, fromIndex)
Return the index of substring in this string, or -1 if not found
substring
- The string to search for
fromIndex
- Index to search from
The index of the string, or -1 if not found
This function is used in the following places in Espruino's documentation
function String.lastIndexOf(substring, fromIndex)
Return the last index of substring in this string, or -1 if not found
substring
- The string to search for
fromIndex
- Index to search from
The index of the string, or -1 if not found
property String.length
Find the length of the string
The value of the string
function String.match(subStr)
Matches subStr
occurrence in the string.
subStr
- Substring or RegExp to match
This match array
function String.replace(subStr, newSubStr)
Search and replace ONE occurrance of subStr
with newSubStr
and return the result. This doesn't alter the original string. Regular expressions not supported.
subStr
- The string to search for
newSubStr
- The string to replace it with
This string with subStr
replaced
function String.slice(start, end)
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
Part of this string from start for len characters
function String.split(separator)
Return an array made by splitting this string up by the separator. eg. '1,2,3'.split(',')==[1,2,3]
separator
- The start character index
Part of this string from start for len characters
new String(str, ...)
Create a new String
str, ...
- A value to turn into a string. If undefined or not supplied, an empty String is created.
A String
function String.substr(start, len)
start
- The start character index
len
- The number of characters
Part of this string from start for len characters
function String.substring(start, end)
start
- The start character index
end
- The end character index
The part of this string between start and end
function String.toLowerCase()
The lowercase version of this string
function String.toUpperCase()
The uppercase version of this string
function String.trim()
Return a new string with any whitespace (tabs, space, form feed, newline, carriage return, etc) removed from the beginning and end.
A String with Whitespace removed from the beginning and end
The base class for syntax errors
new SyntaxError(message)
Creates a SyntaxError object
message
- An optional message string
A SyntaxError object
function SyntaxError.toString()
A String
This library implements a telnet console for the Espruino interpreter. It requires a network connection, e.g. Wifi, and currently only functions on the ESP8266 and on Linux . It uses port 23 on the ESP8266 and port 2323 on Linux.
Note: To enable on Linux, run ./espruino --telnet
TelnetServer.setOptions(options)
options
- Options controlling the telnet console server
This library allows you to create TCPIP servers and clients using TLS encryption
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.
tls.connect(options, callback)
Create a socket connection using TLS
Options can have ca
, key
and cert
fields, which should be the decoded content of the certificate.
var options = url.parse("localhost:1234");
options.key = atob("MIIJKQ ... OZs08C");
options.cert = atob("MIIFi ... Uf93rN+");
options.ca = atob("MIIFgDCC ... GosQML4sc=");
require("tls").connect(options, ... );
If you have the certificates as .pem
files, you need to load these files, take the information between the lines beginning with ----
, remove the newlines from it so you have raw base64, and then feed it into atob
as above.
You can also:
Just specify the filename (<=100 characters) and it will be loaded and parsed if you have an SD card connected. For instance options.key = "key.pem";
Specify a function, which will be called to retrieve the data. For instance `options.key = function() { eeprom.load_my_info(); };
For more information about generating and using certificates, see:
https://engineering.circle.com/https-authorized-certs-with-node-js/
(You'll need to use 2048 bit certificates as opposed to 4096 bit shown above)
Note: This is only available in devices with TLS and SSL support (Espruino Pico and Espruino WiFi only)
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 a new net.Socket object
This library provides TV out capability on the Espruino and Espruino Pico.
See the [[Television]] page for more information.
tv.setup(options, width)
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 : 240,
repeat : 2, // amount of times to repeat each line
});
or
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,
repeat : 1, // amount of times to repeat each line
});
See the [[Television]] page for more information.
options
- Various options for the TV output
width
-
A graphics object
The base class for type errors
function TypeError.toString()
A String
new TypeError(message)
Creates a TypeError object
message
- An optional message string
A TypeError object
This is the built-in JavaScript class for a typed array of 16 bit unsigned integers.
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).
Arrays of this type include all the methods from ArrayBufferView
new Uint16Array(arr, byteOffset, length)
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.
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)
A typed array
This is the built-in JavaScript class for a typed array of 32 bit unsigned integers.
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).
Arrays of this type include all the methods from ArrayBufferView
new Uint32Array(arr, byteOffset, length)
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.
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)
A typed array
This is the built-in JavaScript class for a typed array of 8 bit unsigned integers.
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).
Arrays of this type include all the methods from ArrayBufferView
new Uint8Array(arr, byteOffset, length)
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.
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)
A typed array
This function is used in the following places in Espruino's documentation
This is the built-in JavaScript class for a typed array of 8 bit unsigned integers that are automatically clamped to the range 0 to 255.
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).
Arrays of this type include all the methods from ArrayBufferView
new Uint8ClampedArray(arr, byteOffset, length)
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
.
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)
A typed array
This class helps to convert URLs into Objects of information ready for http.request/get
url.parse(urlStr, parseQuery)
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"}}
urlStr
- A URL to be parsed
parseQuery
- Whether to parse the query string into an object not (default = false)
An object containing options for http.request
or http.get
. Contains method
, host
, path
, pathname
, search
, port
and query
This function is used in the following places in Espruino's documentation
This class handles waveforms. In Espruino, a Waveform is a set of data that you want to input or output.
function Waveform.startInput(output, freq, options)
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 not available in devices with low flash memory
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
function Waveform.startOutput(output, freq, options)
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 not available in devices with low flash memory
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
function Waveform.stop()
Stop a waveform that is currently outputting
Note: This is not available in devices with low flash memory
new Waveform(samples, options)
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 not available in devices with low flash memory
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).
An Waveform object
The Wifi library is designed to control the Wifi interface. It supports functionality such as connecting to wifi networks, getting network information, starting an access point, etc.
It is available on these devices:
Certain features may or may not be implemented on your device however we have documented what is available and what isn't.
If you're not using one of the devices above, a separate WiFi library is provided. For instance:
Other ways of connecting to the net such as GSM, Ethernet and LTE have their own libraries.
You can use the WiFi library as follows:
var wifi = require("Wifi");
wifi.connect("my-ssid", {password:"my-pwd"}, function(ap){ console.log("connected:", ap); });
On ESP32/ESP8266 if you want the connection to happen automatically at boot, add wifi.save();
.
On other platforms, place wifi.connect
in a function called onInit
.
Wifi.on('associated', function(details) { ... });
The 'connected' event is called when an association with an access point has succeeded, i.e., a connection to the AP's network has been established.
On ESP32/ESP8266 there is a details
parameter which includes:
details
- An object with event details
Wifi.on('auth_change', function(details) { ... });
The 'auth_change' event is called when the authentication mode with the associated access point changes. The details include:
Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
details
- An object with event details
Wifi.connect(ssid, options, callback)
Connect to an access point as a station. If there is an existing connection to an AP it is first disconnected if the SSID or password are different from those passed as parameters. Put differently, if the passed SSID and password are identical to the currently connected AP then nothing is changed.
When the connection attempt completes the callback function is invoked with one err
parameter, which is NULL if there is no error and a string message if there is an error. If DHCP is enabled the callback occurs once an IP addres has been obtained, if a static IP is set the callback occurs once the AP's network has been joined. The callback is also invoked if a connection already exists and does not need to be changed.
The options properties may contain:
password
- Password string to be used to access the network.dnsServers
(array of String) - An array of up to two DNS servers in dotted decimal format string.Notes:
getDetails().status
field.connect
call automatically enabled station mode, it can be disabled again by calling disconnect
.ssid
- The access point network id.
options
- Connection options (optional).
callback
- A callback(err)
function to be called back on completion. err
is null on success, or contains an error string on failure.
Wifi.on('connected', function(details) { ... });
The 'connected' event is called when the connection with an access point is ready for traffic. In the case of a dynamic IP address configuration this is when an IP address is obtained, in the case of static IP address allocation this happens when an association is formed (in that case the 'associated' and 'connected' events are fired in rapid succession).
On ESP32/ESP8266 there is a details
parameter which includes:
details
- An object with event details
Wifi.on('dhcp_timeout', function() { ... });
The 'dhcp_timeout' event is called when a DHCP request to the connected access point fails and thus no IP address could be acquired (or renewed).
Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
Wifi.disconnect(callback)
Disconnect the wifi station from an access point and disable the station mode. It is OK to call disconnect
to turn off station mode even if no connection exists (for example, connection attempts may be failing). Station mode can be re-enabled by calling connect
or scan
.
callback
- An optional callback()
function to be called back on disconnection. The callback function receives no argument.
Wifi.on('disconnected', function(details) { ... });
The 'disconnected' event is called when an association with an access point has been lost.
On ESP32/ESP8266 there is a details
parameter which includes:
details
- An object with event details
Wifi.getAPDetails(callback)
Retrieve the current access point configuration and status. The details object has the following properties:
status
- Current access point status: enabled
or disabled
stations
- an array of the stations connected to the access point. This array may be empty. Each entry in the array is an object describing the station which, at a minimum contains ip
being the IP address of the station.ssid
- SSID to broadcast.password
- Password for authentication.authMode
- the authentication required of stations: open
, wpa
, wpa2
, wpa_wpa2
.hidden
- True if the SSID is hidden, false otherwise.maxConn
- Max number of station connections supported.savedSsid
- the SSID to broadcast automatically at boot time, null if the access point is to be disabled at boot.Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
callback
- An optional callback(details)
function to be called back with the current access point details, i.e. the same object as returned directly.
An object representing the current access point details, if available immediately.
Wifi.getAPIP(callback)
Return the access point IP information in an object which contains:
callback
- An optional callback(err, ipinfo)
function to be called back with the the IP information.
An object representing the esp8266's Access Point IP information, if available immediately (ONLY on ESP8266/ESP32).
Wifi.getDetails(callback)
Retrieve the wifi station configuration and status details. The details object has the following properties:
status
- Details about the wifi station connection, one of off
, connecting
, wrong_password
, no_ap_found
, connect_fail
, or connected
. The off, bad_password and connected states are stable, the other states are transient. The connecting state will either result in connected or one of the error states (bad_password, no_ap_found, connect_fail) and the no_ap_found and connect_fail states will result in a reconnection attempt after some interval.rssi
- signal strength of the connected access point in dB, typically in the range -110 to 0, with anything greater than -30 being an excessively strong signal.ssid
- SSID of the access point.password
- the password used to connect to the access point.authMode
- the authentication used: open
, wpa
, wpa2
, wpa_wpa2
(not currently supported).savedSsid
- the SSID to connect to automatically at boot time, null if none.Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
callback
- An optional callback(details)
function to be called back with the wifi details, i.e. the same object as returned directly.
An object representing the wifi station details, if available immediately.
Wifi.getHostByName(hostname, callback)
Lookup the hostname and invoke a callback with the IP address as integer argument. If the lookup fails, the callback is invoked with a null argument. Note: only a single hostname lookup can be made at a time, concurrent lookups are not supported.
Note: This is only available in ESP8266 boards running Espruino
hostname
- The hostname to lookup.
callback
- The callback(ip)
to invoke when the IP is returned. ip==null
on failure.
Wifi.getHostname(callback)
Returns the hostname announced to the DHCP server and broadcast via mDNS when connecting to an access point.
Note: This is only available in ESP8266 boards running Espruino
callback
- An optional callback(hostname)
function to be called back with the hostname.
The currently configured hostname, if available immediately.
Wifi.getIP(callback)
Return the station IP information in an object as follows:
Note that the ip
, netmask
, and gw
fields are omitted if no connection is established:
callback
- An optional callback(err, ipinfo)
function to be called back with the IP information.
An object representing the station IP information, if available immediately (ONLY on ESP8266/ESP32).
Wifi.getStatus(callback)
Retrieve the current overall WiFi configuration. This call provides general information that pertains to both station and access point modes. The getDetails and getAPDetails calls provide more in-depth information about the station and access point configurations, respectively. The status object has the following properties:
station
- Status of the wifi station: off
, connecting
, ...ap
- Status of the wifi access point: disabled
, enabled
.mode
- The current operation mode: off
, sta
, ap
, sta+ap
.phy
- Modulation standard configured: 11b
, 11g
, 11n
(the esp8266 docs are not very clear, but it is assumed that 11n means b/g/n). This setting limits the modulations that the radio will use, it does not indicate the current modulation used with a specific access point.powersave
- Power saving mode: none
(radio is on all the time), ps-poll
(radio is off between beacons as determined by the access point's DTIM setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., no power saving is possible.savedMode
- The saved operation mode which will be applied at boot time: off
, sta
, ap
, sta+ap
.Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
callback
- Optional callback(status)
function to be called back with the current Wifi status, i.e. the same object as returned directly.
An object representing the current WiFi status, if available immediately.
Wifi.ping(hostname, callback)
Issues a ping to the given host, and calls a callback with the time when the ping is received.
Note: This is only available in Espruino WiFi boards and ESP8266 boards running Espruino
hostname
- The host to ping
callback
- A callback(time)
function to invoke when a ping is received
Wifi.on('probe_recv', function(details) { ... });
The 'probe_recv' event is called when a probe request is received from some station by the esp8266's access point. The details include:
Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
details
- An object with event details
Wifi.restore()
Restores the saved Wifi configuration from flash. See Wifi.save()
.
Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
Wifi.save(what)
On boards where this is not available, just issue the connect
commands you need to run at startup from an onInit
function.
Save the current wifi configuration (station and access point) to flash and automatically apply this configuration at boot time, unless what=="clear"
, in which case the saved configuration is cleared such that wifi remains disabled at boot. The saved configuration includes:
Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
what
- An optional parameter to specify what to save, on the esp8266 the two supported values are clear
and sta+ap
. The default is sta+ap
Wifi.scan(callback)
Perform a scan for access points. This will enable the station mode if it is not currently enabled. Once the scan is complete the callback function is called with an array of APs found, each AP is an object with:
ssid
: SSID string.mac
: access point MAC address in 00:00:00:00:00:00 format.authMode
: open
, wep
, wpa
, wpa2
, or wpa_wpa2
.channel
: wifi channel 1..13.hidden
: true if the SSID is hidden (ESP32/ESP8266 only)rssi
: signal strength in dB in the range -110..0.Notes: in order to perform the scan the station mode is turned on and remains on, use Wifi.disconnect() to turn it off again, if desired. only one scan can be in progress at a time.
callback
- A callback(err, ap_list)
function to be called back on completion. err==null
and ap_list
is an array on success, or err
is an error string and ap_list
is undefined on failure.
Wifi.setAPIP(settings, callback)
The settings
object must contain the following properties.
ip
IP address as string (e.g. "192.168.5.100")gw
The network gateway as string (e.g. "192.168.5.1")netmask
The interface netmask as string (e.g. "255.255.255.0")Note: This is only available in Espruino WiFi boards and ESP8266 boards running Espruino
settings
- Configuration settings
callback
- A callback(err)
function to invoke when ip is set. err==null
on success, or a string on failure.
Wifi.setConfig(settings)
Sets a number of global wifi configuration settings. All parameters are optional and which are passed determines which settings are updated. The settings available are:
phy
- Modulation standard to allow: 11b
, 11g
, 11n
(the esp8266 docs are not very clear, but it is assumed that 11n means b/g/n).powersave
- Power saving mode: none
(radio is on all the time), ps-poll
(radio is off between beacons as determined by the access point's DTIM setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., no power saving is possible.Note: esp8266 SDK programmers may be missing an "opmode" option to set the sta/ap/sta+ap operation mode. Please use connect/scan/disconnect/startAP/stopAP, which all set the esp8266 opmode indirectly.
Note: This is only available in ESP8266 boards running Espruino
settings
- An object with the configuration settings to change.
Wifi.setHostname(hostname, callback)
Set the hostname. Depending on implemenation, the hostname is sent with every DHCP request and is broadcast via mDNS. The DHCP hostname may be visible in the access point and may be forwarded into DNS as hostname.local. If a DHCP lease currently exists changing the hostname will cause a disconnect and reconnect in order to transmit the change to the DHCP server. The mDNS announcement also includes an announcement for the "espruino" service.
Note: This is only available in ESP8266 boards running Espruino and Espruino WiFi boards
hostname
- The new hostname.
callback
- An optional callback()
function to be called back when the hostname is set
Wifi.setIP(settings, callback)
The settings
object must contain the following properties.
ip
IP address as string (e.g. "192.168.5.100")gw
The network gateway as string (e.g. "192.168.5.1")netmask
The interface netmask as string (e.g. "255.255.255.0")Note: This is only available in ESP8266 boards running Espruino and Espruino WiFi boards
settings
- Configuration settings
callback
- A callback(err)
function to invoke when ip is set. err==null
on success, or a string on failure.
Wifi.setSNTP(server, tz_offset)
Starts the SNTP (Simple Network Time Protocol) service to keep the clock synchronized with the specified server. Note that the time zone is really just an offset to UTC and doesn't handle daylight savings time. The interval determines how often the time server is queried and Espruino's time is synchronized. The initial synchronization occurs asynchronously after setSNTP returns.
Note: This is only available in ESP8266 boards running Espruino
server
- The NTP server to query, for example, us.pool.ntp.org
tz_offset
- Local time zone offset in the range -11..13.
Wifi.on('sta_joined', function(details) { ... });
The 'sta_joined' event is called when a station establishes an association (i.e. connects) with the esp8266's access point. The details include:
Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
details
- An object with event details
Wifi.on('sta_left', function(details) { ... });
The 'sta_left' event is called when a station disconnects from the esp8266's access point (or its association times out?). The details include:
Note: This is only available in ESP32 boards and ESP8266 boards running Espruino
details
- An object with event details
Wifi.startAP(ssid, options, callback)
Create a WiFi access point allowing stations to connect. If the password is NULL or an empty string the access point is open, otherwise it is encrypted.
The callback function is invoked once the access point is set-up and receives one err
argument, which is NULL on success and contains an error message string otherwise.
The options
object can contain the following properties.
authMode
- The authentication mode to use. Can be one of "open", "wpa2", "wpa", "wpa_wpa2". The default is open (but open access points are not recommended).password
- The password for connecting stations if authMode is not open.channel
- The channel to be used for the access point in the range 1..13. If the device is also connected to an access point as a station then that access point determines the channel.hidden
- The flag if visible or not (0:visible, 1:hidden), default is visiable.Notes:
startAP
call automatically enables AP mode. It can be disabled again by calling stopAP
.ssid
- The network id.
options
- Configuration options (optional).
callback
- Optional callback(err)
function to be called when the AP is successfully started. err==null
on success, or an error string on failure.
Wifi.stopAP(callback)
Stop being an access point and disable the AP operation mode. AP mode can be re-enabled by calling startAP
.
callback
- An optional callback()
function to be called back on successful stop. The callback function receives no argument.
Wifi.turbo(enable, callback)
Switch to using a higher communication speed with the WiFi module.
true
= 921600 baudfalse
= 1152001843200
(or any number) = use a specific baud rate.
*
eg. wifi.turbo(true,callback)
or wifi.turbo(1843200,callback)
Note: This is only available in Espruino WiFi boards
enable
- true (or a baud rate as a number) to enable, false to disable
callback
- A callback()
function to invoke when turbo mode has been set
Class containing utility functions for the Seeed WIO LTE board
WioLTE.A4
See description above
WioLTE.A6
See description above
WioLTE.D20
See description above
WioLTE.D38
See description above
WioLTE.I2C
See description above
WioLTE.LED(red, green, blue)
Set the WIO's LED
red
- 0-255, red LED intensity
green
- 0-255, green LED intensity
blue
- 0-255, blue LED intensity
WioLTE.setGrovePower(onoff)
Set the power of Grove connectors, except for D38
and D39
which are always on.
onoff
- Whether to turn the Grove connectors power on or off (D38/D39 are always powered)
WioLTE.setLEDPower(onoff)
Turn power to the WIO's LED on or off.
Turning the LED on won't immediately display a color - that must be done with WioLTE.LED(r,g,b)
onoff
- true = on, false = off
This function is used in the following places in Espruino's documentation
WioLTE.UART
See description above
Library for communication with the WIZnet Ethernet module
WIZnet.connect(spi, cs)
Initialise the WIZnet module and return an Ethernet object
spi
- Device to use for SPI (or undefined to use the default)
cs
- The pin to use for Chip Select
An Ethernet Object
This function is used in the following places in Espruino's documentation
An instantiation of a WiFi network adaptor
function WLAN.connect(ap, key, callback)
Connect to a wireless network
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'
True if connection succeeded, false if it didn't.
function WLAN.disconnect()
Completely uninitialise and power down the CC3000. After this you'll have to use require("CC3000").connect()
again.
function WLAN.getIP()
Get the current IP address
See description above
function WLAN.reconnect()
Completely uninitialise and power down the CC3000, then reconnect to the old access point.
function WLAN.setIP(options)
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()
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.
True on success