Espruino Hardware Reference
The Espruino Software will run on a variety of boards. However the official boards below have been specially designed to complement our software, and are the only boards that we actively support. Please click on the thumbnails below to see diagrams of each board with their pins and capabilities.
Official Boards
Original Espruino
Espruino Pico
Espruino WiFi
Puck.js
Unofficial boards ▼
Espruino Software Reference
Version 1v91.38
Contents
Globals
- function acceleration()
- function analogRead(pin)
- function analogWrite(pin, value, options)
- variable arguments
- function atob(binaryData)
- Bluetooth
- function btoa(binaryData)
- function changeInterval(id, time)
- function clearInterval(id)
- function clearTimeout(id)
- function clearWatch(id)
- function compass()
- function decodeURIComponent(str)
- function digitalPulse(pin, value, time)
- function digitalRead(pin)
- function digitalWrite(pin, value)
- function dump()
- function echo(echoOn)
- function edit(funcName)
- function encodeURIComponent(str)
- function eval(code)
- function getPinMode(pin)
- function getSerial()
- function getTime()
- variable global
- variable HIGH
- I2C1
- I2C2
- I2C3
- variable Infinity
- function isNaN(x)
- function load()
- LoopbackA
- LoopbackB
- variable LOW
- variable NaN
- function parseFloat(string)
- function parseInt(string, radix)
- function peek16(addr, count)
- function peek32(addr, count)
- function peek8(addr, count)
- function pinMode(pin, mode, automatic)
- function poke16(addr, value)
- function poke32(addr, value)
- function poke8(addr, value)
- function print(text, ...)
- function require(moduleName)
- function reset()
- function save()
- Serial1
- Serial2
- Serial3
- Serial4
- Serial5
- Serial6
- function setBusyIndicator(pin)
- function setDeepSleep(sleep)
- function setInterval(function, timeout, args, ...)
- function setSleepIndicator(pin)
- function setTime(time)
- function setTimeout(function, timeout, args, ...)
- function setWatch(function, pin, options)
- function shiftOut(pins, options, data)
- function show(image)
- SPI1
- SPI2
- SPI3
- Telnet
- function trace(root)
- USB
AES
Array
- constructor Array(args, ...)
- function Array.concat(args, ...)
- function Array.every(function, thisArg)
- function Array.fill(value, start, end)
- function Array.filter(function, thisArg)
- function Array.forEach(function, thisArg)
- function Array.indexOf(value)
- Array.isArray(var)
- function Array.join(separator)
- property Array.length
- function Array.map(function, thisArg)
- function Array.pop()
- function Array.push(arguments, ...)
- function Array.reduce(callback, initialValue)
- function Array.reverse()
- function Array.shift()
- function Array.slice(start, end)
- function Array.some(function, thisArg)
- function Array.sort(var)
- function Array.splice(index, howMany, elements, ...)
- function Array.toString(radix)
- function Array.unshift(elements, ...)
ArrayBuffer
ArrayBufferView
- property ArrayBufferView.buffer
- property ArrayBufferView.byteLength
- property ArrayBufferView.byteOffset
- function ArrayBufferView.fill(value, start, end)
- function ArrayBufferView.forEach(function, thisArg)
- function ArrayBufferView.indexOf(value)
- function ArrayBufferView.join(separator)
- function ArrayBufferView.map(function, thisArg)
- function ArrayBufferView.reduce(callback, initialValue)
- function ArrayBufferView.reverse()
- function ArrayBufferView.set(arr, offset)
- function ArrayBufferView.slice(start, end)
- function ArrayBufferView.sort(var)
BluetoothDevice
BluetoothRemoteGATTCharacteristic
- function BluetoothRemoteGATTCharacteristic.readValue()
- function BluetoothRemoteGATTCharacteristic.startNotifications()
- function BluetoothRemoteGATTCharacteristic.stopNotifications()
- function BluetoothRemoteGATTCharacteristic.writeValue(data)
BluetoothRemoteGATTServer
- function BluetoothRemoteGATTServer.connect()
- function BluetoothRemoteGATTServer.disconnect()
- function BluetoothRemoteGATTServer.getPrimaryService(service)
- function BluetoothRemoteGATTServer.getPrimaryServices()
BluetoothRemoteGATTService
- function BluetoothRemoteGATTService.getCharacteristic(characteristic)
- function BluetoothRemoteGATTService.getCharacteristics()
Boolean
CC3000
console
crypto
- crypto.AES
- crypto.PBKDF2(passphrase, salt, options)
- crypto.SHA1(message)
- crypto.SHA224(message)
- crypto.SHA256(message)
- crypto.SHA384(message)
- crypto.SHA512(message)
Date
- constructor Date(args, ...)
- function Date.getDate()
- function Date.getDay()
- function Date.getFullYear()
- function Date.getHours()
- function Date.getMilliseconds()
- function Date.getMinutes()
- function Date.getMonth()
- function Date.getSeconds()
- function Date.getTime()
- function Date.getTimezoneOffset()
- Date.now()
- Date.parse(str)
- function Date.toISOString()
- function Date.toString()
- function Date.toUTCString()
- function Date.valueOf()
E
- E.clip(x, min, max)
- E.connectSDCard(spi, csPin)
- E.convolve(arr1, arr2, offset)
- E.dumpLockedVars()
- E.dumpStr()
- E.dumpTimers()
- E.enableWatchdog(timeout, isAuto)
- E.FFT(arrReal, arrImage, inverse)
- E.getAnalogVRef()
- E.getErrorFlags()
- E.getSizeOf(v, depth)
- E.getTemperature()
- E.HSBtoRGB(hue, sat, bri)
- E.hwRand()
- event E.init()
- E.interpolate(array, index)
- E.interpolate2d(array, width, x, y)
- E.kickWatchdog()
- E.lockConsole()
- E.mapInPlace(from, to, map, bits)
- E.memoryArea(addr, len)
- E.nativeCall(addr, sig, data)
- E.openFile(path, mode)
- E.reverseByte(x)
- E.sendUSBHID(data)
- E.setBootCode(code, alwaysExec)
- E.setClock(options)
- E.setPassword(password)
- E.setUSBHID(opts)
- E.srand(v)
- E.sum(arr)
- E.toArrayBuffer(str)
- E.toString(args, ...)
- E.toUint8Array(args, ...)
- E.unmountSD()
- E.variance(arr, mean)
Error
ESP8266
- ESP8266.crc32(arrayOfData)
- ESP8266.deepSleep(micros)
- ESP8266.dumpSocketInfo()
- ESP8266.getFreeFlash()
- ESP8266.getResetInfo()
- ESP8266.getState()
- ESP8266.logDebug(enable)
- ESP8266.neopixelWrite(pin, arrayOfData)
- ESP8266.ping(ipAddr, pingCallback)
- ESP8266.printLog()
- ESP8266.readLog()
- ESP8266.reboot()
- ESP8266.setCPUFreq(freq)
- ESP8266.setLog(mode)
Ethernet
File
- function File.close()
- function File.pipe(destination, options)
- function File.read(length)
- function File.seek(nBytes)
- function File.skip(nBytes)
- function File.write(buffer)
Flash
- Flash.erasePage(addr)
- Flash.getFree()
- Flash.getPage(addr)
- Flash.read(length, addr)
- Flash.write(data, addr)
Float32Array
Float64Array
fs
- fs.appendFile(path, data)
- fs.appendFileSync(path, data)
- fs.pipe(source, destination, options)
- fs.readdir(path)
- fs.readdirSync(path)
- fs.readFile(path)
- fs.readFileSync(path)
- fs.statSync(path)
- fs.unlink(path)
- fs.unlinkSync(path)
- fs.writeFile(path, data)
- fs.writeFileSync(path, data)
Function
- function Function.apply(this, args)
- function Function.bind(this, params, ...)
- function Function.call(this, params, ...)
- constructor Function(args, ...)
- function Function.replaceWith(newFunc)
Graphics
- function Graphics.clear()
- Graphics.createArrayBuffer(width, height, bpp, options)
- Graphics.createCallback(width, height, bpp, callback)
- Graphics.createSDL(width, height)
- function Graphics.drawCircle(x, y, rad)
- function Graphics.drawImage(image, x, y)
- function Graphics.drawLine(x1, y1, x2, y2)
- function Graphics.drawRect(x1, y1, x2, y2)
- function Graphics.drawString(str, x, y)
- function Graphics.fillCircle(x, y, rad)
- function Graphics.fillPoly(poly)
- function Graphics.fillRect(x1, y1, x2, y2)
- function Graphics.getBgColor()
- function Graphics.getColor()
- function Graphics.getHeight()
- function Graphics.getModified(reset)
- function Graphics.getPixel(x, y)
- function Graphics.getWidth()
- function Graphics.lineTo(x, y)
- function Graphics.moveTo(x, y)
- function Graphics.setBgColor(r, g, b)
- function Graphics.setColor(r, g, b)
- function Graphics.setFontBitmap()
- function Graphics.setFontCustom(bitmap, firstChar, width, height)
- function Graphics.setFontVector(size)
- function Graphics.setPixel(x, y, col)
- function Graphics.setRotation(rotation, reflect)
- function Graphics.stringWidth(str)
HASH
hashlib
http
httpCRq
httpCRs
- function httpCRs.available()
- event httpCRs.close()
- event httpCRs.data(data)
- event httpCRs.error()
- function httpCRs.pipe(destination, options)
- function httpCRs.read(chars)
httpSRq
- function httpSRq.available()
- event httpSRq.close()
- event httpSRq.data(data)
- function httpSRq.pipe(destination, options)
- function httpSRq.read(chars)
httpSRs
- event httpSRs.close()
- event httpSRs.drain()
- function httpSRs.end(data)
- function httpSRs.write(data)
- function httpSRs.writeHead(statusCode, headers)
httpSrv
I2C
- I2C.find(pin)
- constructor I2C()
- function I2C.readFrom(address, quantity)
- function I2C.setup(options)
- function I2C.writeTo(address, data, ...)
Int16Array
Int32Array
Int8Array
InternalError
JSON
Math
- Math.abs(x)
- Math.acos(x)
- Math.asin(x)
- Math.atan(x)
- Math.atan2(y, x)
- Math.ceil(x)
- Math.clip(x, min, max)
- Math.cos(theta)
- Math.E
- Math.exp(x)
- Math.floor(x)
- Math.LN10
- Math.LN2
- Math.log(x)
- Math.LOG10E
- Math.LOG2E
- Math.max(args, ...)
- Math.min(args, ...)
- Math.PI
- Math.pow(x, y)
- Math.random()
- Math.round(x)
- Math.sin(theta)
- Math.sqrt(x)
- Math.SQRT1_2
- Math.SQRT2
- Math.tan(theta)
- Math.wrap(x, max)
Modules
- Modules.addCached(id, sourcecode)
- Modules.getCached()
- Modules.removeAllCached()
- Modules.removeCached(id)
net
NetworkJS
NodeMCU
- NodeMCU.A0
- NodeMCU.D0
- NodeMCU.D1
- NodeMCU.D10
- NodeMCU.D2
- NodeMCU.D3
- NodeMCU.D4
- NodeMCU.D5
- NodeMCU.D6
- NodeMCU.D7
- NodeMCU.D8
- NodeMCU.D9
NRF
- event NRF.characteristicsDiscover()
- event NRF.connect(addr)
- NRF.connect(mac)
- event NRF.disconnect()
- NRF.disconnect()
- NRF.findDevices(callback, time)
- NRF.getAddress()
- NRF.getBattery()
- event NRF.NFCoff()
- event NRF.NFCon()
- NRF.nfcRaw(payload)
- NRF.nfcURL(url)
- NRF.requestDevice(options)
- NRF.restart()
- NRF.sendHIDReport(data, callback)
- event NRF.servicesDiscover()
- NRF.setAdvertising(data, options)
- NRF.setLowPowerConnection(lowPower)
- NRF.setRSSIHandler(callback)
- NRF.setScan(callback)
- NRF.setServices(data, options)
- NRF.setTxPower(power)
- NRF.sleep()
- NRF.updateServices(data)
- NRF.wake()
Nucleo
- Nucleo.A0
- Nucleo.A1
- Nucleo.A2
- Nucleo.A3
- Nucleo.A4
- Nucleo.A5
- Nucleo.D0
- Nucleo.D1
- Nucleo.D10
- Nucleo.D11
- Nucleo.D12
- Nucleo.D13
- Nucleo.D14
- Nucleo.D15
- Nucleo.D2
- Nucleo.D3
- Nucleo.D4
- Nucleo.D5
- Nucleo.D6
- Nucleo.D7
- Nucleo.D8
- Nucleo.D9
Number
- Number.MAX_VALUE
- Number.MIN_VALUE
- Number.NaN
- Number.NEGATIVE_INFINITY
- constructor Number(value, ...)
- Number.POSITIVE_INFINITY
- function Number.toFixed(decimalPlaces)
Object
- function Object.clone()
- Object.create(proto, propertiesObject)
- Object.defineProperties(obj, props)
- Object.defineProperty(obj, name, desc)
- function Object.emit(event, args, ...)
- Object.getOwnPropertyDescriptor(obj, name)
- Object.getOwnPropertyNames(object)
- Object.getPrototypeOf(object)
- function Object.hasOwnProperty(name)
- Object.keys(object)
- property Object.length
- constructor Object(value)
- function Object.on(event, listener)
- function Object.removeAllListeners(event)
- function Object.removeListener(event, listener)
- Object.setPrototypeOf(object, prototype)
- function Object.toString(radix)
- function Object.valueOf()
OneWire
- constructor OneWire(pin)
- function OneWire.read(count)
- function OneWire.reset()
- function OneWire.search()
- function OneWire.search(command)
- function OneWire.select(rom)
- function OneWire.skip()
- function OneWire.write(data, power)
Pin
- function Pin.getInfo()
- function Pin.getMode()
- function Pin.mode(mode)
- constructor Pin(value)
- function Pin.read()
- function Pin.reset()
- function Pin.set()
- function Pin.toggle()
- function Pin.write(value)
- function Pin.writeAtTime(value, time)
process
Promise
- Promise.all(promises)
- function Promise.catch(onRejected)
- constructor Promise(executor)
- Promise.reject(promises)
- Promise.resolve(promises)
- function Promise.then(onFulfilled, onRejected)
Puck
- Puck.capSense(tx, rx)
- Puck.getBatteryPercentage()
- Puck.IR(data, cathode, anode)
- Puck.light()
- Puck.mag()
- event Puck.mag()
- Puck.magOff()
- Puck.magOn(samplerate)
- Puck.selfTest()
ReferenceError
Serial
- function Serial.available()
- event Serial.data(data)
- Serial.find(pin)
- event Serial.framing()
- function Serial.onData(function)
- event Serial.parity()
- function Serial.pipe(destination, options)
- function Serial.print(string)
- function Serial.println(string)
- function Serial.read(chars)
- function Serial.setConsole(force)
- function Serial.setup(baudrate, options)
- function Serial.write(data, ...)
Server
Socket
- function Socket.available()
- event Socket.close(had_error)
- event Socket.data(data)
- event Socket.drain()
- function Socket.end(data)
- event Socket.error(details)
- function Socket.pipe(destination, options)
- function Socket.read(chars)
- function Socket.write(data)
SPI
- SPI.find(pin)
- function SPI.send(data, nss_pin)
- function SPI.send4bit(data, bit0, bit1, nss_pin)
- function SPI.send8bit(data, bit0, bit1, nss_pin)
- function SPI.setup(options)
- constructor SPI()
- function SPI.write(data, ...)
String
- function String.charAt(pos)
- function String.charCodeAt(pos)
- String.fromCharCode(code, ...)
- function String.indexOf(substring, fromIndex)
- function String.lastIndexOf(substring, fromIndex)
- property String.length
- function String.replace(subStr, newSubStr)
- function String.slice(start, end)
- function String.split(separator)
- constructor String(str, ...)
- function String.substr(start, len)
- function String.substring(start, end)
- function String.toLowerCase()
- function String.toUpperCase()
- function String.trim()
SyntaxError
TelnetServer
tls
tv
TypeError
Uint16Array
Uint32Array
Uint8Array
Uint8ClampedArray
url
Waveform
- function Waveform.startInput(output, freq, options)
- function Waveform.startOutput(output, freq, options)
- function Waveform.stop()
- constructor Waveform(samples, options)
Wifi
- event Wifi.associated(details)
- event Wifi.auth_change(details)
- Wifi.connect(ssid, options, callback)
- event Wifi.connected(details)
- event Wifi.dhcp_timeout()
- Wifi.disconnect(callback)
- event Wifi.disconnected(details)
- Wifi.getAPDetails(callback)
- Wifi.getAPIP(callback)
- Wifi.getDetails(callback)
- Wifi.getDHCPHostname(callback)
- Wifi.getHostByName(hostname, callback)
- Wifi.getHostname(callback)
- Wifi.getIP(callback)
- Wifi.getStatus(callback)
- event Wifi.probe_recv(details)
- Wifi.restore()
- Wifi.save(what)
- Wifi.scan(callback)
- Wifi.setAPIP(settings, callback)
- Wifi.setConfig(settings)
- Wifi.setDHCPHostname(hostname)
- Wifi.setHostname(hostname)
- Wifi.setIP(settings, callback)
- Wifi.setSNTP(server, tz_offset)
- event Wifi.sta_joined(details)
- event Wifi.sta_left(details)
- Wifi.startAP(ssid, options, callback)
- Wifi.stopAP(callback)
WIZnet
WLAN
- function WLAN.connect(ap, key, callback)
- function WLAN.disconnect()
- function WLAN.getIP()
- function WLAN.reconnect()
- function WLAN.setIP(options)
Detail
Global Functions
Methods and Fields
- function acceleration()
- function analogRead(pin)
- function analogWrite(pin, value, options)
- variable arguments
- function atob(binaryData)
- function btoa(binaryData)
- function changeInterval(id, time)
- function clearInterval(id)
- function clearTimeout(id)
- function clearWatch(id)
- function compass()
- function decodeURIComponent(str)
- function digitalPulse(pin, value, time)
- function digitalRead(pin)
- function digitalWrite(pin, value)
- function dump()
- function echo(echoOn)
- function edit(funcName)
- function encodeURIComponent(str)
- function eval(code)
- function getPinMode(pin)
- function getSerial()
- function getTime()
- variable global
- variable HIGH
- variable Infinity
- function isNaN(x)
- function load()
- variable LOW
- variable NaN
- function parseFloat(string)
- function parseInt(string, radix)
- function peek16(addr, count)
- function peek32(addr, count)
- function peek8(addr, count)
- function pinMode(pin, mode, automatic)
- function poke16(addr, value)
- function poke32(addr, value)
- function poke8(addr, value)
- function print(text, ...)
- function require(moduleName)
- function reset()
- function save()
- function setBusyIndicator(pin)
- function setDeepSleep(sleep)
- function setInterval(function, timeout, args, ...)
- function setSleepIndicator(pin)
- function setTime(time)
- function setTimeout(function, timeout, args, ...)
- function setWatch(function, pin, options)
- function shiftOut(pins, options, data)
- function show(image)
- function trace(root)
function acceleration ⇒
Call type:
function acceleration()Description
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
Returns
An object with x, y, and z fields in it
function analogRead ⇒
Call type:
function analogRead(pin)Description
Get the analog value of the given pin
This is different to Arduino which only returns an integer between 0 and 1023
However only pins connected to an ADC will work (see the datasheet)
Note: if you didn't call pinMode beforehand then this function will also reset pin's state to "analog"
Parameters
pin - The pin to use
You can find out which pins to use by looking at your board's reference page and searching for pins with the ADC markers.
Returns
The analog Value of the Pin between 0 and 1
Examples
This function is used in the following places in Espruino's documentation
- Arduino Pico adaptor board
- HD44780 Character LCD
- Light Dependent Resistor
- LM339/393 Comparator (set watch on analog voltage)
- NRF24L01+ Wireless Module
- Analog to Digital Converter
- File IO and SD cards
- AA/AAA Battery Charger
- Pico Light Sensor
- Thermistors
function analogWrite ⇒
Call type:
function analogWrite(pin, value, options)Description
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 even
Note: if you didn't call pinMode beforehand then this function will also reset pin's state to "output"
Parameters
pin - The pin to use
You can find out which pins to use by looking at your board's reference page and searching for pins with the PWM or DAC markers.
value - A value between 0 and 1
options - An object containing options for analog output - see below
Examples
This function is used in the following places in Espruino's documentation
- Espruino Pico
- DMX
- L293D Motor Driver IC
- LM339/393 Comparator (set watch on analog voltage)
- Servo Motors
- Stepper Motors
- ULN2003 Transistor Array
- Digital to Analog Converter
- Pulse Width Modulation
- Waveforms
- File IO and SD cards
- Dial Tones
- Measuring and Controlling Fan Speed
- Making Sounds and Music
- Morse Code Texting
- Pico FET Output
- Pico Infrared Transmit and Receive
- Pico Piano
- 5 Minute Wire Loop Game
- Low-level STM32 Peripheral access
- Simple LED wiring
- The Useless Box - a box that turns itself off
- Remote Control Helicopter with Wii Nunchuck
variable arguments ⇒
Call type:
variable argumentsDescription
A variable containing the arguments given to the function
Returns
An array containing all the arguments given to the function
function atob ⇒
Call type:
function atob(binaryData)Description
Decode the supplied base64 string into a normal string
Note: This is only available in not devices with low flash memory
Parameters
binaryData - A string of base64 data to decode
Returns
A string containing the decoded data
Examples
This function is used in the following places in Espruino's documentation
Bluetooth ⇒
Instance of Serial
Description
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 ⇒
Call type:
function btoa(binaryData)Description
Encode the supplied string (or array) into a base64 string
Note: This is only available in not devices with low flash memory
Parameters
binaryData - A string of data to encode
Returns
A base64 encoded string
function changeInterval ⇒
Call type:
function changeInterval(id, time)Description
Change the Interval on a callback created with setInterval, for example:
var id = setInterval(function () { print('foo'); }, 1000); // every second
changeInterval(id, 1500); // now runs every 1.5 seconds
This takes effect immediately and resets the timeout, so in the example above,
regardless of when you call changeInterval, the next interval will occur 1500ms
after it.
Parameters
id - The id returned by a previous call to setInterval
time - The new time period in ms
Examples
This function is used in the following places in Espruino's documentation
function clearInterval ⇒
Call type:
function clearInterval(id)Description
Clear the Interval that was created with setInterval, for example:
var id = setInterval(function () { print('foo'); }, 1000);
clearInterval(id);
If no argument is supplied, all timers and intervals are stopped
Parameters
id - The id returned by a previous call to setInterval
Examples
This function is used in the following places in Espruino's documentation
- Servo Motors
- Wifi Remote Console
- USB and USB HID
- File IO and SD cards
- Digital Dice
- Flashing Lights
- KeyPad Combination Lock
- KeyPad Timer
- Logging to Google Sheets
- Motion Sensing Lights
- Pico Buttons
- Pico Clock
- Pico Weather Station
- 5 Minute Wire Loop Game
- Single Button Combination Lock
- Snake Game
- Understanding PWM and Implementing it Yourself
- HTTP Image Loader
- Reaction Timer using RGB123
- Temperature on a PCD8544 display, with DS18B20 temperature sensor
- Temperature Graph on a PCD8544 display, with DS18B20 temperature sensor
- The Useless Box - a box that turns itself off
- WiFi Xively Humidity/Temperature Sensor with Display
function clearTimeout ⇒
Call type:
function clearTimeout(id)Description
Clear the Timeout that was created with setTimeout, for example:
var id = setTimeout(function () { print('foo'); }, 1000);
clearTimeout(id);
If no argument is supplied, all timers and intervals are stopped
Parameters
id - The id returned by a previous call to setTimeout
Examples
This function is used in the following places in Espruino's documentation
- CC3000 WiFi Module
- Using BTN1 to turn on an LED
- Dial Tones
- Infrared Remote Control
- Morse Code Texting
- Motion Sensing Lights
- Single Button Combination Lock
function clearWatch ⇒
Call type:
function clearWatch(id)Description
Clear the Watch that was created with setWatch. If no parameter is supplied, all watches will be removed.
Parameters
id - The id returned by a previous call to setWatch
Examples
This function is used in the following places in Espruino's documentation
- LM339/393 Comparator (set watch on analog voltage)
- Digital Dice
- Measuring and Controlling Fan Speed
- Pico Buttons
- Pico Infrared Transmit and Receive
- 5 Minute Wire Loop Game
- Snake Game
function compass ⇒
Call type:
function compass()Description
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
Returns
An object with x, y, and z fields in it
Examples
This function is used in the following places in Espruino's documentation
function decodeURIComponent ⇒
Call type:
function decodeURIComponent(str)Description
Convert any groups of characters of the form '%ZZ', into characters with hex code '0xZZ'
Note: This is only available in not devices with low flash memory
Parameters
str - A string to decode from a URI
Returns
A string containing the decoded data
function digitalPulse ⇒
Call type:
function digitalPulse(pin, value, time)Description
Pulse the pin with the value for the given time in milliseconds. It uses a hardware timer to produce accurate pulses, and returns immediately (before the pulse has finished). Use digitalPulse(A0,1,0) to wait until a previous pulse has finished.
eg. digitalPulse(A0,1,5); pulses A0 high for 5ms. digitalPulse(A0,1,[5,2,4]); pulses A0 high for 5ms, low for 2ms, and high for 4ms
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.
Parameters
pin - The pin to use
value - Whether to pulse high (true) or low (false)
time - A time in milliseconds, or an array of times (in which case a square wave will be output starting with a pulse of 'value')
Examples
This function is used in the following places in Espruino's documentation
- Espruino Pico Robot PCB
- Servo Motors
- Controlling Other Pucks
- Door Controlled Light with Puck.js
- Puck.js Security and Access Control
- File IO and SD cards
- Infrared Remote Control
- Interactive Web-based UI
- KeyPad Combination Lock
- KeyPad Timer
- Pico Buttons
- Pico Infrared Transmit and Receive
- Single Button Combination Lock
- Understanding PWM and Implementing it Yourself
- Time Lapse Camera
- Water Physics with Servo Motors
- The Useless Box - a box that turns itself off
- Remote Control Helicopter with Wii Nunchuck
function digitalRead ⇒
Call type:
function digitalRead(pin)Description
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
Parameters
pin - The pin to use
Returns
The digital Value of the Pin
Examples
This function is used in the following places in Espruino's documentation
- Espruino Pico
- Buttons
- AA/AAA Battery Charger
- Using BTN1 to turn on an LED
- Dial Tones
- Morse Code Texting
- Pico Buttons
- 5 Minute Wire Loop Game
- Time Lapse Camera
- Water Physics with Servo Motors
- Remote Control Helicopter with Wii Nunchuck
function digitalWrite ⇒
Call type:
function digitalWrite(pin, value)Description
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.
Parameters
pin - The pin to use
value - Whether to pulse high (true) or low (false)
Examples
This function is used in the following places in Espruino's documentation
- Espruino Pico
- Arduino Pico adaptor board
- Buttons
- CC3000 WiFi Module
- ESP8266 WiFi Module
- EasyVR Voice Recognition Board
- L293D Motor Driver IC
- LIS302DL Accelerometer
- MFRC522 NFC/RFID module
- PN532 NFC/RFID module
- HopeRF RFM69 Wireless Module
- SSD1606 e-Paper display driver
- Stepper Motors
- TCS3200 driver
- ULN2003 Transistor Array
- Inline Assembler
- Espruino Performance Notes
- Power Consumption
- Controlling Other Pucks
- Infrared Record and Playback with Puck.js
- File IO and SD cards
- Internet (HTTP)
- AA/AAA Battery Charger
- Bluetooth Voice Controlled Robot
- Measuring and Controlling Fan Speed
- Flashing Lights
- Heater Controller
- KeyPad Combination Lock
- Logging to Google Sheets
- Making Sounds and Music
- Motion Sensing Lights
- Pico Buttons
- Pico Electronic Dice
- Pico Infrared Transmit and Receive
- Pico Light Sensor
- Pico Piano
- Pico Vibration
- 5 Minute Wire Loop Game
- Quick Start
- Low-level STM32 Peripheral access
- Single Button Combination Lock
- Small Solar Powered Espruino
- Thermistors
- Time Lapse Camera
- Distance Sensing Robot
- Reaction Timer using RGB123
- The Useless Box - a box that turns itself off
function dump ⇒
Call type:
function dump()Description
Output current interpreter state in a text form such that it can be copied to a new device
Note: 'Internal' functions are currently not handled correctly. You will need to recreate these in the onInit function.
Note: This is only available in not devices with low flash memory
function echo ⇒
Call type:
function echo(echoOn)Description
Should TinyJS echo what you type back to you? true = yes (Default), false = no. When echo is off, the result of executing a command is not returned. Instead, you must use 'print' to send output.
Parameters
echoOn -
function edit ⇒
Call type:
function edit(funcName)Description
Fill the console with the contents of the given function, so you can edit it.
NOTE: This is a convenience function - it will not edit 'inner functions'. For that, you must edit the 'outer function' and re-execute it.
Parameters
funcName - The name of the function to edit (either a string or just the unquoted name)
Examples
This function is used in the following places in Espruino's documentation
function encodeURIComponent ⇒
Call type:
function encodeURIComponent(str)Description
Convert a string with any character not alphanumeric or - _ . ! ~ * ' ( ) converted to the form %XY where XY is its hexadecimal representation
Note: This is only available in not devices with low flash memory
Parameters
str - A string to encode as a URI
Returns
A string containing the encoded data
Examples
This function is used in the following places in Espruino's documentation
function eval ⇒
Call type:
function eval(code)Description
Evaluate a string containing JavaScript code
Parameters
code -
Returns
The result of evaluating the string
Examples
This function is used in the following places in Espruino's documentation
function getPinMode ⇒
Call type:
function getPinMode(pin)Description
Return the current mode of the given pin. See pinMode for more information on returned values.
Note: This is only available in not devices with low flash memory
Parameters
pin - The pin to check
Returns
The pin mode, as a string
function getSerial ⇒
Call type:
function getSerial()Description
Get the serial number of this board
Returns
The board's serial number
function getTime ⇒
Call type:
function getTime()Description
Return the current system time in Seconds (as a floating point number)
Returns
See description above
Examples
This function is used in the following places in Espruino's documentation
- LM339/393 Comparator (set watch on analog voltage)
- LPD-6416 LED Matrix Display
- MAG3110 3-axis magnetometer
- Sharp Memory LCD
- Servo Motors
- Waveforms
- File IO and SD cards
- AA/AAA Battery Charger
- Reaction Timer using RGB123
- LED Clock (using WS8111)
variable global ⇒
Call type:
variable globalDescription
A reference to the global scope, where everything is defined.
Returns
The global scope
variable HIGH ⇒
Call type:
variable HIGHReturns
Logic 1 for Arduino compatibility - this is the same as just typing 1
I2C1 ⇒
Instance of I2C
Description
The first I2C port
I2C2 ⇒
Instance of I2C
Description
The second I2C port
I2C3 ⇒
Instance of I2C
Description
The third I2C port
variable Infinity ⇒
Call type:
variable InfinityReturns
Positive Infinity (1/0)
function isNaN ⇒
Call type:
function isNaN(x)Description
Whether the x is NaN (Not a Number) or not
Parameters
x -
Returns
True is the value is NaN, false if not.
function load ⇒
Call type:
function load()Description
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.
LoopbackA ⇒
Instance of Serial
Description
A loopback serial device. Data sent to LoopbackA comes out of LoopbackB and vice versa
LoopbackB ⇒
Instance of Serial
Description
A loopback serial device. Data sent to LoopbackA comes out of LoopbackB and vice versa
variable LOW ⇒
Call type:
variable LOWReturns
Logic 0 for Arduino compatibility - this is the same as just typing 0
variable NaN ⇒
Call type:
variable NaNReturns
Not a Number
function parseFloat ⇒
Call type:
function parseFloat(string)Description
Convert a string representing a number into an float
Parameters
string -
Returns
The value of the string
Examples
This function is used in the following places in Espruino's documentation
function parseInt ⇒
Call type:
function parseInt(string, radix)Description
Convert a string representing a number into an integer
Parameters
string -
radix - The Radix of the string (optional)
Returns
The integer value of the string (or NaN)
Examples
This function is used in the following places in Espruino's documentation
function peek16 ⇒
Call type:
function peek16(addr, count)Description
Read 16 bits of memory at the given location - DANGEROUS!
Parameters
addr - The address in memory to read
count - (optional) the number of items to read. If >1 a Uint16Array will be returned.
Returns
The value of memory at the given location
Examples
This function is used in the following places in Espruino's documentation
function peek32 ⇒
Call type:
function peek32(addr, count)Description
Read 32 bits of memory at the given location - DANGEROUS!
Parameters
addr - The address in memory to read
count - (optional) the number of items to read. If >1 a Uint32Array will be returned.
Returns
The value of memory at the given location
Examples
This function is used in the following places in Espruino's documentation
function peek8 ⇒
Call type:
function peek8(addr, count)Description
Read 8 bits of memory at the given location - DANGEROUS!
Parameters
addr - The address in memory to read
count - (optional) the number of items to read. If >1 a Uint8Array will be returned.
Returns
The value of memory at the given location
function pinMode ⇒
Call type:
function pinMode(pin, mode, automatic)Description
Set the mode of the given pin.
auto/undefined- Don't change state, but allowdigitalWrite/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 logical1leaves the pin open circuitopendrain_pullup- Digital output that pulls down to 0v. Sending a logical1enables 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 logical1leaves the pin open circuit
Note: 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)).
Parameters
pin - The pin to set pin mode for
mode - The mode - a string that is either 'analog', 'input', 'input_pullup', 'input_pulldown', 'output', 'opendrain', 'af_output' or 'af_opendrain'. Do not include this argument 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)
Examples
This function is used in the following places in Espruino's documentation
- Espruino Pico
- Buttons
- LM339/393 Comparator (set watch on analog voltage)
- JavaScript Compilation
- Infrared Record and Playback with Puck.js
- AA/AAA Battery Charger
- Digital Dice
- Infrared Remote Control
- Pico Buttons
- Pico Electronic Dice
- Pico FET Output
- Pico Infrared Transmit and Receive
- Pico Piano
- Pico Vibration
- 5 Minute Wire Loop Game
- Reaction Timer using RGB123
function poke16 ⇒
Call type:
function poke16(addr, value)Description
Write 16 bits of memory at the given location - VERY DANGEROUS!
Parameters
addr - The address in memory to write
value - The value to write, or an array of values
Examples
This function is used in the following places in Espruino's documentation
function poke32 ⇒
Call type:
function poke32(addr, value)Description
Write 32 bits of memory at the given location - VERY DANGEROUS!
Parameters
addr - The address in memory to write
value - The value to write, or an array of values
Examples
This function is used in the following places in Espruino's documentation
function poke8 ⇒
Call type:
function poke8(addr, value)Description
Write 8 bits of memory at the given location - VERY DANGEROUS!
Parameters
addr - The address in memory to write
value - The value to write, or an array of values
function print ⇒
Call type:
function print(text, ...)Description
Print the supplied string(s) to the console
Note: If you're connected to a computer (not a wall adaptor) via USB but you are not running a terminal app then when you print data Espruino may pause execution and wait until the computer requests the data it is trying to print.
Parameters
text, ... -
Examples
This function is used in the following places in Espruino's documentation
- Rotary Encoder
- KeyPad Matrix
- MFRC522 NFC/RFID module
- MMC212xMG Dual-axis Magnetic Sensor from MEMSIC used in HDMM01 breakout from Pollin
- NRF24L01+ Wireless Module
- PN532 NFC/RFID module
- TSL2561 Luminosity sensor
- JavaScript Compilation
- Espruino Performance Notes
- Clock Module
- WebSockets
- OneWire
- USART / UART / Serial Port
- Puck.js and BLE UARTs
- Door Controlled Light with Puck.js
- Puck.js and HTTP Proxies
- Puck.js and BLE Printers
- Fractals
- Graphics Library
- Bluetooth Voice Controlled Robot
- Digital Dice
- Infrared Remote Control
- The Useless Box - a box that turns itself off
- Remote Control Helicopter with Wii Nunchuck
function require ⇒
Call type:
function require(moduleName)Description
Load the given module, and return the exported functions
Parameters
moduleName - A String containing the name of the given module
Returns
The result of evaluating the string
Examples
This function is used in the following places in Espruino's documentation
- Modules
- Espruino on ESP8266 WiFi
- Espruino WiFi
- 433.92Mhz Transmitter and Receiver
- ADNS5050 Optical Mouse Sensor
- ADS1x15 programmable gain ADC
- ADS7843 Touchscreen
- ADXL335 Accelerometer
- ADXL345 Accelerometer
- Arduino Pico adaptor board
- Espruino module for BME280
- BMP085/BMP180 digital pressure sensor
- Espruino module for BMP280
- CAP1188 capacitive touch breakout
- CC3000 WiFi Module
- Espruino Parallel to Serial Shifting-In with a CD4021BE
- Charlieplexed LED Module
- DCF77
- DHT11 Temperature and RH Sensor
- DHT22/AM230x/RHT0x Temperature and RH Sensor
- DMX
- DS18B20 Temperature Sensor
- Digole LCD driver (monochrome)
- ESP8266 WiFi Module
- EasyVR Voice Recognition Board
- Rotary Encoder
- GPS Module
- SeeedStudio Grove System
- HC-SR04 Ultrasonic Distance Sensor
- HD44780 Character LCD
- HP03S pressure sensor module
- HTS221 pressure sensor
- HTU21D Temperature and RH Sensor
- ILI9163 LCD controller
- ILI9341 LCD controller
- Infrared Remote Control Receiver Module
- KeyPad Matrix
- LPD-6416 LED Matrix Display
- LPS25HB pressure sensor
- MAG3110 3-axis magnetometer
- MAX7219 7 segment display driver
- MCP23xxx I2C and SPI port expanders
- MCP4xxx I2C and SPI digital potentiometers
- MCP9808 precision I2C temperature sensor
- MFRC522 NFC/RFID module
- MLX90614 Infra Red thermometer
- MMC212xMG Dual-axis Magnetic Sensor from MEMSIC used in HDMM01 breakout from Pollin
- MPL115A2, I2C digital barometer and temperature sensor
- MPL3115A2 Digital Altitude / Pressure / Temperature Sensor
- MPU6050 accelerometer and gyro
- MQ135 Air Quality Sensor
- Sharp Memory LCD
- Midi
- NRF24L01+ Wireless Module
- nRF905 Wireless Transceiver
- PCD8544 LCD driver (Nokia 5110)
- PN532 NFC/RFID module
- CMUcam5 Pixy
- HopeRF RFM69 Wireless Module
- Analog RGB LED Control
- RN2483 LoRa Modules
- Espruino Pico Robot PCB
- SH1106 OLED driver
- Sensirion SHT10 SHT11 & SHT15 Temperature and Relative Humidity Sensor Module
- Sensirion SHT20, SHT21 & SHT25 Temperature and Relative Humidity Sensor
- SIMCom SIM800/SIM900 GSM/GPRS Module
- SSD1306 OLED driver
- SSD1351 OLED display driver
- SSD1606 e-Paper display driver
- ST7565/ST7567 128x64 Monochrome LCD driver
- STM32F1 Flash Memory Module
- SX1276/77/78/79 LoRa Modules
- Servo Motors
- SmartNixie Nixie Tube driver
- Stepper Motor Module
- TCS3200 driver
- TCS3472x I2C Color Sensor
- TSL2561 Luminosity sensor
- Thermistor Temperature Sensor
- Touchscreen
- WIZnet WIZ550io/W5500 Ethernet module
- Wii Nunchuck
- xBee radio module
- LPRS easyRadio (eRIC) Radio Modules
- Wifi Remote Console
- Running code from an EEPROM
- IoT Services
- Espruino Pico 'Shims'
- BMP Loader Module
- EEPROM on Flash
- InitialState
- Losant
- OneWireTempManager
- USB and USB HID
- VT100 Terminal Emulator
- Clock Module
- HMAC Module
- WebSockets
- TV Out
- Waveforms
- Puck.js and BLE UARTs
- Controlling Other Pucks
- Door Controlled Light with Puck.js
- Puck.js and Eddystone Beacons
- Puck.js and HTTP Proxies
- Puck.js and HID Keyboards
- Puck.js and BLE Printers
- Puck.js and Eddystone Beacons
- File IO and SD cards
- Fonts
- Graphics Library
- Internet (HTTP)
- AA/AAA Battery Charger
- Dial Tones
- Flashing and using the ESP8266 with Espruino
- Using the ESP8266 with Wifi
- Ethernet Webcam Display
- Graphical Web Interface
- Heater Controller
- Interactive Web-based UI
- KeyPad Combination Lock
- KeyPad Timer
- Logging to Google Sheets
- Morse Code Texting
- Soldering an LCD directly to Espruino
- Pico Clock
- Pico Electronic Dice
- Pico Infrared Transmit and Receive
- Pico LCD Display Hello World
- Pico Weather Station
- 5 Minute Wire Loop Game
- Pocket 'walking' GPS
- Snake Game
- WiFi Enabled Thermometer
- Wireless Temperature Sensor
- Writing and Submitting Modules (or changes)
- HTTP File Server
- HTTP Image Loader
- Reaction Timer using RGB123
- Image Slideshow with ILI9341 display
- Temperature on a PCD8544 display, with DS18B20 temperature sensor
- Temperature Graph on a PCD8544 display, with DS18B20 temperature sensor
- WiFi Xively Humidity/Temperature Sensor with Display
- Remote Control Helicopter with Wii Nunchuck
function reset ⇒
Call type:
function reset()Description
Reset the interpreter - clear program memory, and do not load a saved program from flash. This does NOT reset the underlying hardware (which allows you to reset the device without it disconnecting from USB).
This command only executes when the Interpreter returns to the Idle state - for instance a=1;reset();a=2; will still leave 'a' as undefined.
The safest way to do a full reset is to hit the reset button.
Examples
This function is used in the following places in Espruino's documentation
function save ⇒
Call type:
function save()Description
Save program memory into flash. It will then be loaded automatically every time Espruino powers on or is hard-reset.
This command only executes when the Interpreter returns to the Idle state - for
instance a=1;save();a=2; will save 'a' as 2.
When Espruino powers on, it will resume from where it was when you typed save().
If you want code to be executed right after loading (for instance to initialise
devices connected to Espruino), 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.
Serial1 ⇒
Instance of Serial
Description
The first Serial (USART) port
Serial2 ⇒
Instance of Serial
Description
The second Serial (USART) port
Serial3 ⇒
Instance of Serial
Description
The third Serial (USART) port
Serial4 ⇒
Instance of Serial
Description
The fourth Serial (USART) port
Serial5 ⇒
Instance of Serial
Description
The fifth Serial (USART) port
Serial6 ⇒
Instance of Serial
Description
The sixth Serial (USART) port
function setBusyIndicator ⇒
Call type:
function setBusyIndicator(pin)Description
When Espruino is busy, set the pin specified here high. Set this to undefined to disable the feature.
Parameters
pin -
function setDeepSleep ⇒
Call type:
function setDeepSleep(sleep)Description
Set whether we can enter deep sleep mode, which reduces power consumption to around 100uA. This only works on the Espruino Board.
Please see http://www.espruino.com/Power+Consumption for more details on this.
Parameters
sleep -
Examples
This function is used in the following places in Espruino's documentation
- Power Consumption
- File IO and SD cards
- Small Solar Powered Espruino
- Time Lapse Camera
- Simple Data Logger
function setInterval ⇒
Call type:
function setInterval(function, timeout, args, ...)Description
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.
Parameters
function - A Function or String to be executed
timeout - The time between calls to the function
args, ... - Optional arguments to pass to the function when executed
Returns
An ID that can be passed to clearInterval
function setSleepIndicator ⇒
Call type:
function setSleepIndicator(pin)Description
When Espruino is asleep, set the pin specified here low (when it's awake, set it high). Set this to undefined to disable the feature.
Please see http://www.espruino.com/Power+Consumption for more details on this.
Parameters
pin -
Examples
This function is used in the following places in Espruino's documentation
function setTime ⇒
Call type:
function setTime(time)Description
Set the current system time in seconds (to the nearest second)
Parameters
time -
function setTimeout ⇒
Call type:
function setTimeout(function, timeout, args, ...)Description
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.
Parameters
function - A Function or String to be executed
timeout - The time until the function will be executed
args, ... - Optional arguments to pass to the function when executed
Returns
An ID that can be passed to clearTimeout
function setWatch ⇒
Call type:
function setWatch(function, pin, options)Description
Call the function specified when the pin changes. Watches set with setWatch can be removed using clearWatch.
The function may also take an argument, which is an object of type {state:bool, time:float, lastTime:float}.
stateis whether the pin is currently a1or a0timeis the time in seconds at which the pin changed statelastTimeis the time in seconds at which the pin last changed state. When usingedge:'rising'oredge:'falling', this is not the same as when the function was last called.
For instance, if you want to measure the length of a positive pulse you could use setWatch(function(e) { console.log(e.time-e.lastTime); }, BTN, { repeat:true, edge:'falling' });.
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, 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: The STM32 chip (used in the Espruino Board and Pico) cannot
watch two pins with the same number - eg A0 and B0.
Parameters
function - A Function or String to be executed
pin - The pin to watch
options - If this is a boolean or integer, it determines whether to call this once (false = default) or every time a change occurs (true)
If this is an object, it can contain the following information: { repeat: true/false(default), edge:'rising'/'falling'/'both'(default), debounce:10}. debounce is the time in ms to wait for bounces to subside, or 0.
Returns
An ID that can be passed to clearWatch
Examples
This function is used in the following places in Espruino's documentation
- BBC micro:bit
- Puck.js
- Buttons
- LM339/393 Comparator (set watch on analog voltage)
- MAG3110 3-axis magnetometer
- Pyroelectric Motion Sensor
- HopeRF RFM69 Wireless Module
- Stepper Motor Module
- Vibration Sensor
- Inline Assembler
- Espruino Performance Notes
- Power Consumption
- USB and USB HID
- Clock Module
- Controlling Other Pucks
- Infrared Record and Playback with Puck.js
- Puck.js Security and Access Control
- Controlling Bluetooth Lights with Puck.js
- File IO and SD cards
- AA/AAA Battery Charger
- Using BTN1 to turn on an LED
- Dial Tones
- Digital Dice
- Measuring and Controlling Fan Speed
- Individually Addressable LEDs
- Infrared Remote Control
- Making Sounds and Music
- Motion Sensing Lights
- Pico Buttons
- Pico Electronic Dice
- Pico Infrared Transmit and Receive
- Pico Piano
- Pico Vibration
- 5 Minute Wire Loop Game
- Remote Control Sockets
- Single Button Combination Lock
- Slot Machine
- Snake Game
- Distance Sensing Robot
- Reaction Timer using RGB123
- The Useless Box - a box that turns itself off
function shiftOut ⇒
Call type:
function shiftOut(pins, options, data)Description
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.
Parameters
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 ⇒
Call type:
function show(image)Description
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:
- A number where each bit represents a pixel (so 25 bits). eg.
5or0x1FFFFFF - A string, eg:
show("10001"). Newlines are ignored, and anything that is not a space or0is treated as a 1. - An array of 4 bytes (more will be ignored), eg
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)
Parameters
image - The image to show
SPI1 ⇒
Instance of SPI
Description
The first SPI port
SPI2 ⇒
Instance of SPI
Description
The second SPI port
SPI3 ⇒
Instance of SPI
Description
The third SPI port
Telnet ⇒
Instance of Serial
Description
A telnet serial device that maps to the built-in telnet console server (devices that have built-in wifi only).
function trace ⇒
Call type:
function trace(root)Description
Output debugging information
Note: This is only available in not devices with low flash memory
Parameters
root - The symbol to output (optional). If nothing is specified, everything will be output
USB ⇒
Instance of Serial
Description
The USB Serial port
Note: This is only available in devices with USB
AES Class
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.
Methods and Fields
AES.decrypt ⇒
Call type:
AES.decrypt(passphrase, key, options)Parameters
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
Returns an ArrayBuffer
AES.encrypt ⇒
Call type:
AES.encrypt(passphrase, key, options)Parameters
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
Returns an ArrayBuffer
Array Class
This is the built-in JavaScript class for arrays.
Arrays can be defined with [], new Array(), or new Array(length)
Methods and Fields
- constructor Array(args, ...)
- function Array.concat(args, ...)
- function Array.every(function, thisArg)
- function Array.fill(value, start, end)
- function Array.filter(function, thisArg)
- function Array.forEach(function, thisArg)
- function Array.indexOf(value)
- Array.isArray(var)
- function Array.join(separator)
- property Array.length
- function Array.map(function, thisArg)
- function Array.pop()
- function Array.push(arguments, ...)
- function Array.reduce(callback, initialValue)
- function Array.reverse()
- function Array.shift()
- function Array.slice(start, end)
- function Array.some(function, thisArg)
- function Array.sort(var)
- function Array.splice(index, howMany, elements, ...)
- function Array.toString(radix)
- function Array.unshift(elements, ...)
constructor Array ⇒
Call type:
new Array(args, ...)Description
Create an Array. Either give it one integer argument (>=0) which is the length of the array, or any number of arguments
Parameters
args, ... - The length of the array OR any number of items to add to the array
Returns
An Array
function Array.concat ⇒
Call type:
function Array.concat(args, ...)Description
Create a new array, containing the elements from this one and any arguments, if any argument is an array then those elements will be added.
Note: This is only available in not devices with low flash memory
Parameters
args, ... - Any items to add to the array
Returns
An Array
function Array.every ⇒
Call type:
function Array.every(function, thisArg)Description
Return 'true' if the callback returns 'true' for every element in the array
Parameters
function - Function to be executed
thisArg - if specified, the function is called with 'this' set to thisArg (optional)
Returns
A boolean containing the result
function Array.fill ⇒
Call type:
function Array.fill(value, start, end)Description
Fill this array with the given value, for every index >= start and < end
Note: This is only available in not devices with low flash memory
Parameters
value - The value to fill the array with
start - Optional. The index to start from (or 0). If start is negative, it is treated as length+start where length is the length of the array
end - Optional. The index to end at (or the array length). If end is negative, it is treated as length+end.
Returns
This array
function Array.filter ⇒
Call type:
function Array.filter(function, thisArg)Description
Return an array which contains only those elements for which the callback function returns 'true'
Parameters
function - Function to be executed
thisArg - if specified, the function is called with 'this' set to thisArg (optional)
Returns
An array containing the results
function Array.forEach ⇒
Call type:
function Array.forEach(function, thisArg)Description
Executes a provided function once per array element.
Parameters
function - Function to be executed
thisArg - if specified, the function is called with 'this' set to thisArg (optional)
function Array.indexOf ⇒
Call type:
function Array.indexOf(value)Description
Return the index of the value in the array, or -1
Parameters
value - The value to check for
Returns
the index of the value in the array, or -1
Array.isArray ⇒
Call type:
Array.isArray(var)Description
Returns true if the provided object is an array
Parameters
var - The variable to be tested
Returns
True if var is an array, false if not.
function Array.join ⇒
Call type:
function Array.join(separator)Description
Join all elements of this array together into one string, using 'separator' between them. eg. [1,2,3].join(' ')=='1 2 3'
Parameters
separator - The separator
Returns
A String representing the Joined array
property Array.length ⇒
Call type:
property Array.lengthDescription
Find the length of the array
Returns
The value of the array
function Array.map ⇒
Call type:
function Array.map(function, thisArg)Description
Return an array which is made from the following: A.map(function) = [function(A[0]), function(A[1]), ...]
Parameters
function - Function used to map one item to another
thisArg - if specified, the function is called with 'this' set to thisArg (optional)
Returns
An array containing the results
function Array.pop ⇒
Call type:
function Array.pop()Description
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.
Returns
The value that is popped off
function Array.push ⇒
Call type:
function Array.push(arguments, ...)Description
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.
Parameters
arguments, ... - One or more arguments to add
Returns
The new size of the array
Examples
This function is used in the following places in Espruino's documentation
- Infrared Record and Playback with Puck.js
- Individually Addressable LEDs
- Pico Infrared Transmit and Receive
- Snake Game
function Array.reduce ⇒
Call type:
function Array.reduce(callback, initialValue)Description
Execute previousValue=initialValue and then previousValue = callback(previousValue, currentValue, index, array) for each element in the array, and finally return previousValue.
Note: This is only available in not devices with low flash memory
Parameters
callback - Function used to reduce the array
initialValue - if specified, the initial value to pass to the function
Returns
The value returned by the last function called
function Array.reverse ⇒
Call type:
function Array.reverse()Description
Reverse all elements in this array (in place)
Note: This is only available in not devices with low flash memory
Returns
The array, but reversed.
function Array.shift ⇒
Call type:
function Array.shift()Description
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 only available in not devices with low flash memory
Parameters
Returns
The element that was removed
function Array.slice ⇒
Call type:
function Array.slice(start, end)Description
Return a copy of a portion of this array (in a new array)
Parameters
start - Start index
end - End index (optional)
Returns
A new array
function Array.some ⇒
Call type:
function Array.some(function, thisArg)Description
Return 'true' if the callback returns 'true' for any of the elements in the array
Parameters
function - Function to be executed
thisArg - if specified, the function is called with 'this' set to thisArg (optional)
Returns
A boolean containing the result
function Array.sort ⇒
Call type:
function Array.sort(var)Description
Do an in-place quicksort of the array
Note: This is only available in not devices with low flash memory
Parameters
var - A function to use to compare array elements (or undefined)
Returns
This array object
function Array.splice ⇒
Call type:
function Array.splice(index, howMany, elements, ...)Description
Both remove and add items to an array
Parameters
index - Index at which to start changing the array. If negative, will begin that many elements from the end
howMany - An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
elements, ... - One or more items to add to the array
Returns
An array containing the removed elements. If only one element is removed, an array of one element is returned.
function Array.toString ⇒
Call type:
function Array.toString(radix)Description
Convert the Array to a string
Parameters
radix - unused
Returns
A String representing the array
function Array.unshift ⇒
Call type:
function Array.unshift(elements, ...)Description
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 only available in not devices with low flash memory
Parameters
elements, ... - One or more items to add to the beginning of the array
Returns
The new array length
ArrayBuffer Class
This is the built-in JavaScript class for array buffers.
Methods and Fields
constructor ArrayBuffer ⇒
Call type:
new ArrayBuffer(byteLength)Description
Create an Array Buffer object
Parameters
byteLength - The length in Bytes
Returns
An ArrayBuffer object
ArrayBufferView Class
This is the built-in JavaScript class that is the prototype for Uint8Array / Float32Array / etc
Methods and Fields
- property ArrayBufferView.buffer
- property ArrayBufferView.byteLength
- property ArrayBufferView.byteOffset
- function ArrayBufferView.fill(value, start, end)
- function ArrayBufferView.forEach(function, thisArg)
- function ArrayBufferView.indexOf(value)
- function ArrayBufferView.join(separator)
- function ArrayBufferView.map(function, thisArg)
- function ArrayBufferView.reduce(callback, initialValue)
- function ArrayBufferView.reverse()
- function ArrayBufferView.set(arr, offset)
- function ArrayBufferView.slice(start, end)
- function ArrayBufferView.sort(var)
property ArrayBufferView.buffer ⇒
Call type:
property ArrayBufferView.bufferDescription
The buffer this view references
Returns
An ArrayBuffer object
property ArrayBufferView.byteLength ⇒
Call type:
property ArrayBufferView.byteLengthDescription
The length, in bytes, of the view
Returns
The Length
property ArrayBufferView.byteOffset ⇒
Call type:
property ArrayBufferView.byteOffsetDescription
The offset, in bytes, to the first byte of the view within the ArrayBuffer
Returns
The byte Offset
function ArrayBufferView.fill ⇒
Call type:
function ArrayBufferView.fill(value, start, end)Description
Fill this array with the given value, for every index >= start and < end
Note: This is only available in not devices with low flash memory
Parameters
value - The value to fill the array with
start - Optional. The index to start from (or 0). If start is negative, it is treated as length+start where length is the length of the array
end - Optional. The index to end at (or the array length). If end is negative, it is treated as length+end.
Returns
This array
Examples
This function is used in the following places in Espruino's documentation
function ArrayBufferView.forEach ⇒
Call type:
function ArrayBufferView.forEach(function, thisArg)Description
Executes a provided function once per array element.
Parameters
function - Function to be executed
thisArg - if specified, the function is called with 'this' set to thisArg (optional)
function ArrayBufferView.indexOf ⇒
Call type:
function ArrayBufferView.indexOf(value)Description
Return the index of the value in the array, or -1
Parameters
value - The value to check for
Returns
the index of the value in the array, or -1
function ArrayBufferView.join ⇒
Call type:
function ArrayBufferView.join(separator)Description
Join all elements of this array together into one string, using 'separator' between them. eg. [1,2,3].join(' ')=='1 2 3'
Parameters
separator - The separator
Returns
A String representing the Joined array
function ArrayBufferView.map ⇒
Call type:
function ArrayBufferView.map(function, thisArg)Description
Return an array which is made from the following: A.map(function) = [function(A[0]), function(A[1]), ...]
Note: This returns an ArrayBuffer of the same type it was called on. To get an Array, use Array.prototype.map
Parameters
function - Function used to map one item to another
thisArg - if specified, the function is called with 'this' set to thisArg (optional)
Returns
An array containing the results
function ArrayBufferView.reduce ⇒
Call type:
function ArrayBufferView.reduce(callback, initialValue)Description
Execute previousValue=initialValue and then previousValue = callback(previousValue, currentValue, index, array) for each element in the array, and finally return previousValue.
Note: This is only available in not devices with low flash memory
Parameters
callback - Function used to reduce the array
initialValue - if specified, the initial value to pass to the function
Returns
The value returned by the last function called
function ArrayBufferView.reverse ⇒
Call type:
function ArrayBufferView.reverse()Description
Reverse the contents of this arraybuffer in-place
Note: This is only available in not devices with low flash memory
Returns
This array
function ArrayBufferView.set ⇒
Call type:
function ArrayBufferView.set(arr, offset)Description
Copy the contents of array into this one, mapping this[x+offset]=array[x];
Parameters
arr - Floating point index to access
offset - The offset in this array at which to write the values (optional)
Examples
This function is used in the following places in Espruino's documentation
function ArrayBufferView.slice ⇒
Call type:
function ArrayBufferView.slice(start, end)Description
Return a copy of a portion of this array (in a new array).
Note: This currently returns a normal Array, not an ArrayBuffer
Note: This is only available in not devices with low flash memory
Parameters
start - Start index
end - End index (optional)
Returns
A new array
function ArrayBufferView.sort ⇒
Call type:
function ArrayBufferView.sort(var)Description
Do an in-place quicksort of the array
Note: This is only available in not devices with low flash memory
Parameters
var - A function to use to compare array elements (or undefined)
Returns
This array object
BluetoothDevice Class
Web Bluetooth-style device - get this using NRF.requestDevice(address)
Methods and Fields
property BluetoothDevice.gatt ⇒
Call type:
property BluetoothDevice.gattDescription
Note: This is only available on some devices
Note: This is only available in NRF52 devices (like Puck.js)
Returns
A BluetoothRemoteGATTServer for this device
BluetoothRemoteGATTCharacteristic Class
Web Bluetooth-style GATT characteristic - get this using BluetoothRemoteGATTService.getCharacteristic(s)
https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattcharacteristic
Methods and Fields
- function BluetoothRemoteGATTCharacteristic.readValue()
- function BluetoothRemoteGATTCharacteristic.startNotifications()
- function BluetoothRemoteGATTCharacteristic.stopNotifications()
- function BluetoothRemoteGATTCharacteristic.writeValue(data)
function BluetoothRemoteGATTCharacteristic.readValue ⇒
Call type:
function BluetoothRemoteGATTCharacteristic.readValue()Description
Read 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.readValue();
}).then(function(d) {
console.log("Got:", JSON.stringify(d));
device.disconnect();
}).catch(function() {
console.log("Something's broken.");
});
Note: This is only available on some devices
Returns
A Promise that is resolved (or rejected) with data when the characteristic is read
function BluetoothRemoteGATTCharacteristic.startNotifications ⇒
Call type:
function BluetoothRemoteGATTCharacteristic.startNotifications()Description
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.");
});
Note: This is only available on some devices
Returns
A Promise that is resolved (or rejected) with data when notifications have been added
function BluetoothRemoteGATTCharacteristic.stopNotifications ⇒
Call type:
function BluetoothRemoteGATTCharacteristic.stopNotifications()Description
Note: This is only available on some devices
Returns
A Promise that is resolved (or rejected) with data when notifications have been added
function BluetoothRemoteGATTCharacteristic.writeValue ⇒
Call type:
function BluetoothRemoteGATTCharacteristic.writeValue(data)Description
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.");
});
Note: This is only available on some devices
Parameters
data - The data to write
Returns
A Promise that is resolved (or rejected) when the characteristic is written
BluetoothRemoteGATTServer Class
Web Bluetooth-style GATT server - get this using NRF.connect(address)
or NRF.requestDevice(options) then response.gatt.connect
https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver
Methods and Fields
- function BluetoothRemoteGATTServer.connect()
- function BluetoothRemoteGATTServer.disconnect()
- function BluetoothRemoteGATTServer.getPrimaryService(service)
- function BluetoothRemoteGATTServer.getPrimaryServices()
function BluetoothRemoteGATTServer.connect ⇒
Call type:
function BluetoothRemoteGATTServer.connect()Description
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 on some devices
Note: This is only available in NRF52 devices (like Puck.js)
Returns
A Promise that is resolved (or rejected) when the connection is complete
function BluetoothRemoteGATTServer.disconnect ⇒
Call type:
function BluetoothRemoteGATTServer.disconnect()Description
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 on some devices
Note: This is only available in NRF52 devices (like Puck.js)
function BluetoothRemoteGATTServer.getPrimaryService ⇒
Call type:
function BluetoothRemoteGATTServer.getPrimaryService(service)Description
Note: This is only available on some devices
Note: This is only available in NRF52 devices (like Puck.js)
Parameters
service - The service UUID
Returns
A Promise that is resolved (or rejected) when the primary service is found
function BluetoothRemoteGATTServer.getPrimaryServices ⇒
Call type:
function BluetoothRemoteGATTServer.getPrimaryServices()Description
Note: This is only available on some devices
Note: This is only available in NRF52 devices (like Puck.js)
Returns
A Promise that is resolved (or rejected) when the primary services are found
BluetoothRemoteGATTService Class
Web Bluetooth-style GATT service - get this using BluetoothRemoteGATTServer.getPrimaryService(s)
https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice
Methods and Fields
- function BluetoothRemoteGATTService.getCharacteristic(characteristic)
- function BluetoothRemoteGATTService.getCharacteristics()
function BluetoothRemoteGATTService.getCharacteristic ⇒
Call type:
function BluetoothRemoteGATTService.getCharacteristic(characteristic)Description
Note: This is only available on some devices
Note: This is only available in NRF52 devices (like Puck.js)
Parameters
characteristic - The characteristic UUID
Returns
A Promise that is resolved (or rejected) when the characteristic is found
function BluetoothRemoteGATTService.getCharacteristics ⇒
Call type:
function BluetoothRemoteGATTService.getCharacteristics()Description
Note: This is only available on some devices
Note: This is only available in NRF52 devices (like Puck.js)
Returns
A Promise that is resolved (or rejected) when the characteristic is found
Boolean Class
Methods and Fields
constructor Boolean ⇒
Call type:
new Boolean(value)Description
Creates a boolean
Parameters
value - A single value to be converted to a number
Returns
A Boolean object
CC3000 Library
Methods and Fields
CC3000.connect ⇒
Call type:
CC3000.connect(spi, cs, en, irq)Description
Initialise the CC3000 and return a WLAN object
Parameters
spi - Device to use for SPI (or undefined to use the default). SPI should be 1,000,000 baud, and set to 'mode 1'
cs - The pin to use for Chip Select
en - The pin to use for Enable
irq - The pin to use for Interrupts
Returns
A WLAN Object
Examples
This function is used in the following places in Espruino's documentation
- CC3000 WiFi Module
- Wifi Remote Console
- Graphical Web Interface
- WiFi Enabled Thermometer
- HTTP File Server
- HTTP Image Loader
- WiFi Xively Humidity/Temperature Sensor with Display
console Class
An Object that contains functions for writing to the interactive console
Methods and Fields
console.log ⇒
Call type:
console.log(text, ...)Description
Print the supplied string(s) to the console
Note: If you're connected to a computer (not a wall adaptor) via USB but you are not running a terminal app then when you print data Espruino may pause execution and wait until the computer requests the data it is trying to print.
Parameters
text, ... - One or more arguments to print
Examples
This function is used in the following places in Espruino's documentation
- Espruino on ESP8266 WiFi
- BBC micro:bit
- Puck.js
- Espruino WiFi
- 433.92Mhz Transmitter and Receiver
- ADS1x15 programmable gain ADC
- ADXL335 Accelerometer
- Arduino Pico adaptor board
- Espruino module for BME280
- BMP085/BMP180 digital pressure sensor
- Espruino module for BMP280
- Bluetooth BLE 4.0 (HM-10)
- Bluetooth
- Buttons
- CC3000 WiFi Module
- Espruino Parallel to Serial Shifting-In with a CD4021BE
- DCF77
- DHT11 Temperature and RH Sensor
- DHT22/AM230x/RHT0x Temperature and RH Sensor
- DS18B20 Temperature Sensor
- ESP8266 WiFi Module
- EasyVR Voice Recognition Board
- GPS Module
- SeeedStudio Grove System
- HC-SR04 Ultrasonic Distance Sensor
- HP03S pressure sensor module
- HTU21D Temperature and RH Sensor
- Infrared Remote Control Receiver Module
- Light Dependent Resistor
- LM339/393 Comparator (set watch on analog voltage)
- MAG3110 3-axis magnetometer
- MCP23xxx I2C and SPI port expanders
- MCP9808 precision I2C temperature sensor
- MLX90614 Infra Red thermometer
- MMC212xMG Dual-axis Magnetic Sensor from MEMSIC used in HDMM01 breakout from Pollin
- MPL115A2, I2C digital barometer and temperature sensor
- MPL3115A2 Digital Altitude / Pressure / Temperature Sensor
- MQ135 Air Quality Sensor
- Midi
- NRF24L01+ Wireless Module
- nRF905 Wireless Transceiver
- CMUcam5 Pixy
- Pyroelectric Motion Sensor
- HopeRF RFM69 Wireless Module
- RN2483 LoRa Modules
- Espruino Pico Robot PCB
- Sensirion SHT20, SHT21 & SHT25 Temperature and Relative Humidity Sensor
- SIMCom SIM800/SIM900 GSM/GPRS Module
- STM32F1 Flash Memory Module
- SX1276/77/78/79 LoRa Modules
- Stepper Motor Module
- WIZnet WIZ550io/W5500 Ethernet module
- Wii Nunchuck
- xBee radio module
- LPRS easyRadio (eRIC) Radio Modules
- Wifi Remote Console
- Inline Assembler
- Espruino Debugger
- IoT Services
- Espruino Performance Notes
- Espruino Pico 'Shims'
- Troubleshooting
- MQTT Client
- OneWireTempManager
- USART / UART / Serial Port
- Waveforms
- About Bluetooth LE
- Infrared Record and Playback with Puck.js
- Using Puck.js from a Web Bluetooth Website
- Controlling Bluetooth Lights with Puck.js
- File IO and SD cards
- Graphics Library
- Internet (HTTP)
- Using the ESP8266 with Wifi
- Ethernet Webcam Display
- Graphical Web Interface
- Interactive Web-based UI
- KeyPad Combination Lock
- KeyPad Timer
- Logging to Google Sheets
- Morse Code Texting
- Pico Buttons
- Pico Clock
- Pico Infrared Transmit and Receive
- Pico Vibration
- Pico Weather Station
- Remote Control Sockets
- Single Button Combination Lock
- WiFi Enabled Thermometer
- Word Clock
- HTTP File Server
- HTTP Image Loader
- Reaction Timer using RGB123
- Simple Data Logger
- WiFi Xively Humidity/Temperature Sensor with Display
crypto Library
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.
Methods and Fields
- crypto.AES
- crypto.PBKDF2(passphrase, salt, options)
- crypto.SHA1(message)
- crypto.SHA224(message)
- crypto.SHA256(message)
- crypto.SHA384(message)
- crypto.SHA512(message)
crypto.AES ⇒
Call type:
crypto.AESDescription
Class containing AES encryption/decryption
Note: This is only available in devices that support AES (Espruino Pico, Espruino WiFi or Linux)
Returns
See description above
crypto.PBKDF2 ⇒
Call type:
crypto.PBKDF2(passphrase, salt, options)Description
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)
Parameters
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
Returns an ArrayBuffer
crypto.SHA1 ⇒
Call type:
crypto.SHA1(message)Description
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, Espruino WiFi, Linux or ESP8266)
Parameters
message - The message to apply the hash to
Returns
Returns a 20 byte ArrayBuffer
crypto.SHA224 ⇒
Call type:
crypto.SHA224(message)Description
Performs a SHA224 hash and returns the result as a 28 byte ArrayBuffer
Note: This is only available in devices that support Crypto Functionality (Espruino Pico, Espruino WiFi, Linux or ESP8266)
Parameters
message - The message to apply the hash to
Returns
Returns a 20 byte ArrayBuffer
crypto.SHA256 ⇒
Call type:
crypto.SHA256(message)Description
Performs a SHA256 hash and returns the result as a 32 byte ArrayBuffer
Note: This is only available in devices that support Crypto Functionality (Espruino Pico, Espruino WiFi, Linux or ESP8266)
Parameters
message - The message to apply the hash to
Returns
Returns a 20 byte ArrayBuffer
crypto.SHA384 ⇒
Call type:
crypto.SHA384(message)Description
Performs a SHA384 hash and returns the result as a 48 byte ArrayBuffer
Note: This is only available in devices that support Crypto Functionality (Espruino Pico, Espruino WiFi, Linux or ESP8266)
Parameters
message - The message to apply the hash to
Returns
Returns a 20 byte ArrayBuffer
crypto.SHA512 ⇒
Call type:
crypto.SHA512(message)Description
Performs a SHA512 hash and returns the result as a 64 byte ArrayBuffer
Note: This is only available in devices that support Crypto Functionality (Espruino Pico, Espruino WiFi, Linux or ESP8266)
Parameters
message - The message to apply the hash to
Returns
Returns a 32 byte ArrayBuffer
Date Class
The built-in class for handling Dates
Methods and Fields
- constructor Date(args, ...)
- function Date.getDate()
- function Date.getDay()
- function Date.getFullYear()
- function Date.getHours()
- function Date.getMilliseconds()
- function Date.getMinutes()
- function Date.getMonth()
- function Date.getSeconds()
- function Date.getTime()
- function Date.getTimezoneOffset()
- Date.now()
- Date.parse(str)
- function Date.toISOString()
- function Date.toString()
- function Date.toUTCString()
- function Date.valueOf()
constructor Date ⇒
Call type:
new Date(args, ...)Description
Creates a date object
Parameters
args, ... - Either nothing (current time), one numeric argument (milliseconds since 1970), a date string (see Date.parse), or [year, month, day, hour, minute, second, millisecond]
Returns
A Date object
Examples
This function is used in the following places in Espruino's documentation
function Date.getDate ⇒
Call type:
function Date.getDate()Description
Day of the month 1..31
Returns
See description above
function Date.getDay ⇒
Call type:
function Date.getDay()Description
Day of the week (0=sunday, 1=monday, etc)
Returns
See description above
function Date.getFullYear ⇒
Call type:
function Date.getFullYear()Description
The year, eg. 2014
Returns
See description above
function Date.getHours ⇒
Call type:
function Date.getHours()Description
0..23
Returns
See description above
function Date.getMilliseconds ⇒
Call type:
function Date.getMilliseconds()Description
0..999
Returns
See description above
function Date.getMinutes ⇒
Call type:
function Date.getMinutes()Description
0..59
Returns
See description above
function Date.getMonth ⇒
Call type:
function Date.getMonth()Description
Month of the year 0..11
Returns
See description above
function Date.getSeconds ⇒
Call type:
function Date.getSeconds()Description
0..59
Returns
See description above
function Date.getTime ⇒
Call type:
function Date.getTime()Description
Return the number of milliseconds since 1970
Returns
See description above
function Date.getTimezoneOffset ⇒
Call type:
function Date.getTimezoneOffset()Description
The getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.
Returns
The difference, in minutes, between UTC and local time
Date.now ⇒
Call type:
Date.now()Description
Get the number of milliseconds elapsed since 1970 (or on embedded platforms, since startup)
Returns
See description above
Date.parse ⇒
Call type:
Date.parse(str)Description
Parse a date string and return milliseconds since 1970. Data can be either '2011-10-20T14:48:00', '2011-10-20' or 'Mon, 25 Dec 1995 13:30:00 +0430'
Parameters
str - A String
Returns
The number of milliseconds since 1970
Examples
This function is used in the following places in Espruino's documentation
function Date.toISOString ⇒
Call type:
function Date.toISOString()Description
Converts to a ISO 8601 String, eg: 2014-06-20T14:52:20.123Z
Note: This always assumes a timezone of GMT
Returns
A String
function Date.toString ⇒
Call type:
function Date.toString()Description
Converts to a String, eg: Fri Jun 20 2014 14:52:20 GMT+0000
Note: This always assumes a timezone of GMT+0000
Returns
A String
function Date.toUTCString ⇒
Call type:
function Date.toUTCString()Description
Converts to a String, eg: Fri, 20 Jun 2014 14:52:20 GMT
Note: This always assumes a timezone of GMT
Returns
A String
function Date.valueOf ⇒
Call type:
function Date.valueOf()Description
Return the number of milliseconds since 1970
Returns
See description above
E Class
This is the built-in JavaScript class for Espruino utility functions.
Methods and Fields
- E.clip(x, min, max)
- E.connectSDCard(spi, csPin)
- E.convolve(arr1, arr2, offset)
- E.dumpLockedVars()
- E.dumpStr()
- E.dumpTimers()
- E.enableWatchdog(timeout, isAuto)
- E.FFT(arrReal, arrImage, inverse)
- E.getAnalogVRef()
- E.getErrorFlags()
- E.getSizeOf(v, depth)
- E.getTemperature()
- E.HSBtoRGB(hue, sat, bri)
- E.hwRand()
- event E.init()
- E.interpolate(array, index)
- E.interpolate2d(array, width, x, y)
- E.kickWatchdog()
- E.lockConsole()
- E.mapInPlace(from, to, map, bits)
- E.memoryArea(addr, len)
- E.nativeCall(addr, sig, data)
- E.openFile(path, mode)
- E.reverseByte(x)
- E.sendUSBHID(data)
- E.setBootCode(code, alwaysExec)
- E.setClock(options)
- E.setPassword(password)
- E.setUSBHID(opts)
- E.srand(v)
- E.sum(arr)
- E.toArrayBuffer(str)
- E.toString(args, ...)
- E.toUint8Array(args, ...)
- E.unmountSD()
- E.variance(arr, mean)
E.clip ⇒
Call type:
E.clip(x, min, max)Description
Clip a number to be between min and max (inclusive)
Note: This is only available in not devices with low flash memory
Parameters
x - A floating point value to clip
min - The smallest the value should be
max - The largest the value should be
Returns
The value of x, clipped so as not to be below min or above max.
Examples
This function is used in the following places in Espruino's documentation
- Servo Motors
- Water Physics with Servo Motors
- The Useless Box - a box that turns itself off
- Remote Control Helicopter with Wii Nunchuck
E.connectSDCard ⇒
Call type:
E.connectSDCard(spi, csPin)Description
Setup the filesystem so that subsequent calls to E.openFile and require('fs').* will use an SD card on the supplied SPI device and pin.
It can even work using software SPI - for instance:
var spi = new SPI();
spi.setup({mosi:C7,miso:C8,sck:C9});
E.connectSDCard(spi,C6);
console.log(require("fs").readdirSync());
Note: This is only available in not devices with low flash memory
Parameters
spi - The SPI object to use for communication
csPin - The pin to use for Chip Select
E.convolve ⇒
Call type:
E.convolve(arr1, arr2, offset)Description
Convolve arr1 with arr2. This is equivalent to v=0;for (i in arr1) v+=arr1[i] * arr2[(i+offset) % arr2.length]
Note: This is only available in not devices with low flash memory
Parameters
arr1 - An array to convolve
arr2 - An array to convolve
offset - The mean value of the array
Returns
The variance of the given buffer
E.dumpLockedVars ⇒
Call type:
E.dumpLockedVars()Description
Dump any locked variables that aren't referenced from global - for debugging memory leaks only.
Note: This is only available in not release builds
E.dumpStr ⇒
Call type:
E.dumpStr()Description
Get the current interpreter state in a text form such that it can be copied to a new device
Note: This is only available in not devices with low flash memory
Returns
A String
E.dumpTimers ⇒
Call type:
E.dumpTimers()Description
Output the current list of Utility Timer Tasks - for debugging only
Note: This is only available in not release builds
E.enableWatchdog ⇒
Call type:
E.enableWatchdog(timeout, isAuto)Description
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.
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 devices.
Note: This is only available in not devices with low flash memory
Parameters
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.FFT ⇒
Call type:
E.FFT(arrReal, arrImage, inverse)Description
Performs a Fast Fourier Transform (fft) on the supplied data and writes it back into the original arrays. Note that if only one array is supplied, the data written back is the modulus of the complex result sqrt(r*r+i*i).
Note: This is only available in not devices with low flash memory
Parameters
arrReal - An array of real values
arrImage - An array of imaginary values (or if undefined, all values will be taken to be 0)
inverse - Set this to true if you want an inverse FFT - otherwise leave as 0
E.getAnalogVRef ⇒
Call type:
E.getAnalogVRef()Description
Check the internal voltage reference. To work out an actual voltage of an input pin, you can use analogRead(pin)*E.getAnalogVRef()
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 only available in not devices with low flash memory
Returns
The voltage (in Volts) that a reading of 1 from analogRead actually represents - usually around 3.3v
Examples
This function is used in the following places in Espruino's documentation
E.getErrorFlags ⇒
Call type:
E.getErrorFlags()Description
Get and reset the error flags. Returns an array that can contain:
'FIFO_FULL': The receive FIFO filled up and data was lost. This could be state transitions for setWatch, or received characters.
'BUFFER_FULL': A buffer for a stream filled up and characters were lost. This can happen to any stream - Serial,HTTP,etc.
'CALLBACK': A callback (setWatch, setInterval, on('data',...)) caused an error and so was removed.
'LOW_MEMORY': Memory is running low - Espruino had to run a garbage collection pass or remove some of the command history
'MEMORY': Espruino ran out of memory and was unable to allocate some data that it needed.
Note: This is only available in not devices with low flash memory
Returns
An array of error flags
E.getSizeOf ⇒
Call type:
E.getSizeOf(v, depth)Description
Return the number of variable blocks used by the supplied variable. This is useful if you're running out of memory and you want to be able to see what is taking up most of the available space.
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 only available in not devices with low flash memory
Parameters
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
Returns
Information about the variable size - see below
E.getTemperature ⇒
Call type:
E.getTemperature()Description
Use the STM32's internal thermistor to work out the temperature.
While this is implemented on Espruino boards, it may not be implemented on other devices. If so it'll return NaN.
Note: This is not entirely accurate and varies by a few degrees from chip to chip. It measures the die temperature, so when connected to USB it could be reading 10 over degrees C above ambient temperature. When running from battery with setDeepSleep(true) it is much more accurate though.
Returns
The temperature in degrees C
Examples
This function is used in the following places in Espruino's documentation
E.HSBtoRGB ⇒
Call type:
E.HSBtoRGB(hue, sat, bri)Description
Convert hue, saturation and brightness to red, green and blue (packed into an integer)
This replaces Graphics.setColorHSB and Graphics.setBgColorHSB. On devices with 24 bit colour it can
be used as: Graphics.setColorHSB(E.HSBtoRGB(h, s, b))
Note: This is only available in not devices with low flash memory
Parameters
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
Returns
A 24 bit number containing bytes representing red, green, and blue: 0xBBGGRR
E.hwRand ⇒
Call type:
E.hwRand()Description
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 only available in not devices with low flash memory
Returns
A random number
event E.init ⇒
Call type:
E.on('init', function() { ... });Description
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 ⇒
Call type:
E.interpolate(array, index)Description
Interpolate between two adjacent values in the Typed Array
Note: This is only available in not devices with low flash memory
Parameters
array - A Typed Array to interpolate between
index - Floating point index to access
Returns
The result of interpolating between (int)index and (int)(index+1)
E.interpolate2d ⇒
Call type:
E.interpolate2d(array, width, x, y)Description
Interpolate between four adjacent values in the Typed Array, in 2D.
Note: This is only available in not devices with low flash memory
Parameters
array - A Typed Array to interpolate between
width - Integer 'width' of 2d array
x - Floating point X index to access
y - Floating point Y index to access
Returns
The result of interpolating in 2d between the 4 surrounding cells
E.kickWatchdog ⇒
Call type:
E.kickWatchdog()Description
Kicks a Watchdog timer set up with E.enableWatchdog(..., false). See
E.enableWatchdog for more information.
NOTE: This is only implemented on STM32 devices.
Note: This is only available in not devices with low flash memory
E.lockConsole ⇒
Call type:
E.lockConsole()Description
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 ⇒
Call type:
E.mapInPlace(from, to, map, bits)Description
Take each element of the from array, look it up in map (or call the
function with it as a first argument), and write it into the corresponding
element in the to array.
Note: This is only available in not devices with low flash memory
Parameters
from - An ArrayBuffer to read elements from
to - An ArrayBuffer to write elements too
map - An array or function to use to map one element to another
bits - If specified, the number of bits per element
E.memoryArea ⇒
Call type:
E.memoryArea(addr, len)Description
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.
Parameters
addr - The address of the memory area
len - The length (in bytes) of the memory area
Returns
A Uint8Array
Examples
This function is used in the following places in Espruino's documentation
E.nativeCall ⇒
Call type:
E.nativeCall(addr, sig, data)Description
ADVANCED: This is a great way to crash Espruino if you're not sure what you are doing
Create a native function that executes the code at the given address. Eg. E.nativeCall(0x08012345,'double (double,double)')(1.1, 2.2)
If you're executing a thumb function, you'll almost certainly need to set the bottom bit of the address to 1.
Note it's not guaranteed that the call signature you provide can be used - there are limits on the number of arguments allowed.
When supplying data, if it is a 'flat string' then it will be used directly, otherwise it'll be converted to a flat string and used.
Note: This is only available in not devices with low flash memory
Parameters
addr - The address in memory of the function (or offset in data if it was supplied
sig - The signature of the call, returnType (arg1,arg2,...). Allowed types are void,bool,int,double,Pin,JsVar
data - (Optional) A string containing the function itself. If not supplied then 'addr' is used as an absolute address.
Returns
The native function
Examples
This function is used in the following places in Espruino's documentation
E.openFile ⇒
Call type:
E.openFile(path, mode)Description
Open a file
Parameters
path - the path to the file to open.
mode - The mode to use when opening the file. Valid values for mode are 'r' for read, 'w' for write new, 'w+' for write existing, and 'a' for append. If not specified, the default is 'r'.
Returns
A File object
Examples
This function is used in the following places in Espruino's documentation
E.reverseByte ⇒
Call type:
E.reverseByte(x)Description
Reverse the 8 bits in a byte, swapping MSB and LSB.
For example, E.reverseByte(0b10010000) == 0b00001001.
Note that you can reverse all the bytes in an array with: arr = arr.map(E.reverseByte)
Note: This is only available in not devices with low flash memory
Parameters
x - A byte value to reverse the bits of
Returns
The byte with reversed bits
E.sendUSBHID ⇒
Call type:
E.sendUSBHID(data)Parameters
data - An array of bytes to send as a USB HID packet
Returns
1 on success, 0 on failure
E.setBootCode ⇒
Call type:
E.setBootCode(code, alwaysExec)Description
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()
Parameters
code - The code to execute (as a string)
alwaysExec - Whether to always execute the code (even after a reset)
E.setClock ⇒
Call type:
E.setClock(options)Description
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.
STM32F4
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.
- System clock = 8Mhz * N / ( M * P )
- USB clock (should be 48Mhz) = 8Mhz * N / ( M * Q )
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.
ESP8266
Just specify an integer value, either 80 or 160 (for 80 or 160Mhz)
Note: This is only available in not devices with low flash memory
Parameters
options - Platform-specific options for setting clock speed
Returns
The actual frequency the clock has been set to
E.setPassword ⇒
Call type:
E.setPassword(password)Description
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.
Parameters
password - The password - max 20 chars
E.setUSBHID ⇒
Call type:
E.setUSBHID(opts)Description
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)
Parameters
opts - An object containing at least reportDescriptor, an array representing the report descriptor. Pass undefined to disable HID.
E.srand ⇒
Call type:
E.srand(v)Description
Set the seed for the random number generator used by Math.random().
Note: This is only available in not devices with low flash memory
Parameters
v - The 32 bit integer seed to use for the random number generator
E.sum ⇒
Call type:
E.sum(arr)Description
Sum the contents of the given Array, String or ArrayBuffer and return the result
Note: This is only available in not devices with low flash memory
Parameters
arr - The array to sum
Returns
The sum of the given buffer
Examples
This function is used in the following places in Espruino's documentation
E.toArrayBuffer ⇒
Call type:
E.toArrayBuffer(str)Description
Create an ArrayBuffer from the given string. This is done via a reference, not a copy - so it is very fast and memory efficient.
Note that this is an ArrayBuffer, not a Uint8Array. To get one of those, do: new Uint8Array(E.toArrayBuffer('....')).
Parameters
str - The string to convert to an ArrayBuffer
Returns
An ArrayBuffer that uses the given string
Examples
This function is used in the following places in Espruino's documentation
E.toString ⇒
Call type:
E.toString(args, ...)Description
Returns a 'flat' string representing the data in the arguments.
This creates a string from the given arguments. If an argument is a String or an Array, each element is traversed and added as an 8 bit character. If it is anything else, it is converted to a character directly.
Parameters
args, ... - The arguments to convert to a String
Returns
A String
Examples
This function is used in the following places in Espruino's documentation
E.toUint8Array ⇒
Call type:
E.toUint8Array(args, ...)Description
This creates a Uint8Array from the given arguments. If an argument is a String or an Array, each element is traversed and added as if it were an 8 bit value. If it is anything else, it is converted to an 8 bit value directly.
Parameters
args, ... - The arguments to convert to a Uint8Array
Returns
A Uint8Array
E.unmountSD ⇒
Call type:
E.unmountSD()Description
Unmount the SD card, so it can be removed. If you remove the SD card without calling this you may cause corruption, and you will be unable to access another SD card until you reset Espruino or call E.unmountSD().
E.variance ⇒
Call type:
E.variance(arr, mean)Description
Work out the variance of the contents of the given Array, String or ArrayBuffer and return the result. This is equivalent to v=0;for (i in arr) v+=Math.pow(mean-arr[i],2)
Note: This is only available in not devices with low flash memory
Parameters
arr - The array to work out the variance for
mean - The mean value of the array
Returns
The variance of the given buffer
Error Class
The base class for runtime errors
Methods and Fields
constructor Error ⇒
Call type:
new Error(message)Description
Creates an Error object
Parameters
message - An optional message string
Returns
An Error object
function Error.toString ⇒
Call type:
function Error.toString()Returns
A String
ESP8266 Library
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.
Methods and Fields
- ESP8266.crc32(arrayOfData)
- ESP8266.deepSleep(micros)
- ESP8266.dumpSocketInfo()
- ESP8266.getFreeFlash()
- ESP8266.getResetInfo()
- ESP8266.getState()
- ESP8266.logDebug(enable)
- ESP8266.neopixelWrite(pin, arrayOfData)
- ESP8266.ping(ipAddr, pingCallback)
- ESP8266.printLog()
- ESP8266.readLog()
- ESP8266.reboot()
- ESP8266.setCPUFreq(freq)
- ESP8266.setLog(mode)
ESP8266.crc32 ⇒
Call type:
ESP8266.crc32(arrayOfData)Parameters
arrayOfData - Array of data to CRC
Returns
32-bit CRC
ESP8266.deepSleep ⇒
Call type:
ESP8266.deepSleep(micros)Description
Put the ESP8266 into 'deep sleep' for the given number of microseconds, reducing power consumption drastically.
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.
Parameters
micros - Number of microseconds to sleep.
ESP8266.dumpSocketInfo ⇒
Call type:
ESP8266.dumpSocketInfo()Description
Dumps info about all sockets to the log. This is for troubleshooting the socket implementation.
ESP8266.getFreeFlash ⇒
Call type:
ESP8266.getFreeFlash()Description
Note: This is deprecated. Use require("flash").getFree()
Returns
Array of objects with addr and length properties describing the free flash areas available
ESP8266.getResetInfo ⇒
Call type:
ESP8266.getResetInfo()Description
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: (?)
Returns
An object with the reset cause information
ESP8266.getState ⇒
Call type:
ESP8266.getState()Description
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`
Returns
The state of the ESP8266
ESP8266.logDebug ⇒
Call type:
ESP8266.logDebug(enable)Description
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).
Parameters
enable - Enable or disable the debug logging.
ESP8266.neopixelWrite ⇒
Call type:
ESP8266.neopixelWrite(pin, arrayOfData)Parameters
pin - Pin for output signal.
arrayOfData - Array of LED data.
ESP8266.ping ⇒
Call type:
ESP8266.ping(ipAddr, pingCallback)Description
Perform a network ping request. The parameter can be either a String or a numeric IP address. Note: This function should probably be removed, or should it be part of the wifi library?
Parameters
ipAddr - A string representation of an IP address.
pingCallback - Optional callback function.
ESP8266.printLog ⇒
Call type:
ESP8266.printLog()Description
Prints the contents of the debug log to the console.
ESP8266.readLog ⇒
Call type:
ESP8266.readLog()Description
Returns one line from the log or up to 128 characters.
ESP8266.reboot ⇒
Call type:
ESP8266.reboot()Description
Perform a hardware reset/reboot of the esp8266.
ESP8266.setCPUFreq ⇒
Call type:
ESP8266.setCPUFreq(freq)Description
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.
Parameters
freq - Desired frequency - either 80 or 160.
ESP8266.setLog ⇒
Call type:
ESP8266.setLog(mode)Description
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.
Parameters
mode - Debug log mode: 0=off, 1=in-memory only, 2=in-mem and uart0, 3=in-mem and uart1.
Ethernet Class
An instantiation of an Ethernet network adaptor
Methods and Fields
function Ethernet.getIP ⇒
Call type:
function Ethernet.getIP()Description
Get the current IP address, subnet, gateway and mac address.
Returns
See description above
function Ethernet.setIP ⇒
Call type:
function Ethernet.setIP(options)Description
Set the current IP address or get an IP from DHCP (if no options object is specified)
If 'mac' is specified as an option, it must be a string of the form "00:01:02:03:04:05"
Parameters
options - Object containing IP address options { ip : '1,2,3,4', subnet, gateway, dns, mac }, or do not supply an object in order to force DHCP.
Returns
True on success
File Class
This is the File object - it allows you to stream data to and from files (As opposed to the require('fs').readFile(..) style functions that read an entire file).
To create a File object, you must type var fd = E.openFile('filepath','mode') - see E.openFile for more information.
Note: If you want to remove an SD card after you have started using it, you must call E.unmountSD() or you may cause damage to the card.
Methods and Fields
- function File.close()
- function File.pipe(destination, options)
- function File.read(length)
- function File.seek(nBytes)
- function File.skip(nBytes)
- function File.write(buffer)
function File.close ⇒
Call type:
function File.close()Description
Close an open file.
function File.pipe ⇒
Call type:
function File.pipe(destination, options)Description
Pipe this file to a stream (an object with a 'write' method)
Note: This is only available in not devices with low flash memory
Parameters
destination - The destination file/stream that will receive content from the source.
options - An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished
function File.read ⇒
Call type:
function File.read(length)Description
Read data in a file in byte size chunks
Parameters
length - is an integer specifying the number of bytes to read.
Returns
A string containing the characters that were read
Examples
This function is used in the following places in Espruino's documentation
function File.seek ⇒
Call type:
function File.seek(nBytes)Description
Seek to a certain position in the file
Parameters
nBytes - is an integer specifying the number of bytes to skip forwards.
function File.skip ⇒
Call type:
function File.skip(nBytes)Description
Skip the specified number of bytes forward in the file
Parameters
nBytes - is a positive integer specifying the number of bytes to skip forwards.
function File.write ⇒
Call type:
function File.write(buffer)Description
write data to a file
Parameters
buffer - A string containing the bytes to write
Returns
the number of bytes written
Examples
This function is used in the following places in Espruino's documentation
Flash Library
This module allows access to read and write the STM32's flash memory.
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().
Methods and Fields
- Flash.erasePage(addr)
- Flash.getFree()
- Flash.getPage(addr)
- Flash.read(length, addr)
- Flash.write(data, addr)
Flash.erasePage ⇒
Call type:
Flash.erasePage(addr)Description
Erase a page of flash memory
Note: This is only available in not devices with low flash memory
Parameters
addr - An address in the page that is to be erased
Flash.getFree ⇒
Call type:
Flash.getFree()Description
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 only available in not devices with low flash memory
Returns
Array of objects with addr and length properties
Flash.getPage ⇒
Call type:
Flash.getPage(addr)Description
Returns the start and length of the flash page containing the given address.
Note: This is only available in not devices with low flash memory
Parameters
addr - An address in memory
Returns
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 ⇒
Call type:
Flash.read(length, addr)Description
Read flash memory from the given address
Note: This is only available in not devices with low flash memory
Parameters
length - The amount of data to read (in bytes)
addr - The address to start reading from
Returns
A Uint8Array of data
Flash.write ⇒
Call type:
Flash.write(data, addr)Description
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 only available in not devices with low flash memory
Parameters
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)
Float32Array Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Float32Array ⇒
Call type:
new Float32Array(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
Float64Array Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Float64Array ⇒
Call type:
new Float64Array(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
fs Library
This library handles interfacing with a FAT32 filesystem on an SD card. The API is designed to be similar to node.js's - However Espruino does not currently support asynchronous file IO, so the functions behave like node.js's xxxxSync functions. Versions of the functions with 'Sync' after them are also provided for compatibility.
Currently this provides minimal file IO - it's great for logging and loading/saving settings, but not good for loading large amounts of data as you will soon fill your memory up.
It is currently only available on boards that contain an SD card slot, such as the Olimexino and the HY. It can not currently be added to boards that did not ship with a card slot.
To use this, you must type var fs = require('fs') to get access to the library
Methods and Fields
- fs.appendFile(path, data)
- fs.appendFileSync(path, data)
- fs.pipe(source, destination, options)
- fs.readdir(path)
- fs.readdirSync(path)
- fs.readFile(path)
- fs.readFileSync(path)
- fs.statSync(path)
- fs.unlink(path)
- fs.unlinkSync(path)
- fs.writeFile(path, data)
- fs.writeFileSync(path, data)
fs.appendFile ⇒
Call type:
fs.appendFile(path, data)Description
Append the data to the given file, created a new file if it doesn't exist
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
Parameters
path - The path of the file to write
data - The data to write to the file
Returns
True on success, false on failure
fs.appendFileSync ⇒
Call type:
fs.appendFileSync(path, data)Description
Append the data to the given file, created a new file if it doesn't exist
Note: This is only available in not devices with low flash memory
Parameters
path - The path of the file to write
data - The data to write to the file
Returns
True on success, false on failure
Examples
This function is used in the following places in Espruino's documentation
fs.pipe ⇒
Call type:
fs.pipe(source, destination, options)Parameters
source - The source file/stream that will send content.
destination - The destination file/stream that will receive content from the source.
options - An optional object { chunkSize : int=64, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished
fs.readdir ⇒
Call type:
fs.readdir(path)Description
List all files in the supplied directory, returning them as an array of strings.
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
Parameters
path - The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory
Returns
An array of filename strings (or undefined if the directory couldn't be listed)
Examples
This function is used in the following places in Espruino's documentation
fs.readdirSync ⇒
Call type:
fs.readdirSync(path)Description
List all files in the supplied directory, returning them as an array of strings.
Note: This is only available in not devices with low flash memory
Parameters
path - The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory
Returns
An array of filename strings (or undefined if the directory couldn't be listed)
Examples
This function is used in the following places in Espruino's documentation
fs.readFile ⇒
Call type:
fs.readFile(path)Description
Read all data from a file and return as a string
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
Parameters
path - The path of the file to read
Returns
A string containing the contents of the file (or undefined if the file doesn't exist)
Examples
This function is used in the following places in Espruino's documentation
fs.readFileSync ⇒
Call type:
fs.readFileSync(path)Description
Read all data from a file and return as a string.
Note: The size of files you can load using this method is limited by the amount of available RAM. To read files a bit at a time, see the File class.
Note: This is only available in not devices with low flash memory
Parameters
path - The path of the file to read
Returns
A string containing the contents of the file (or undefined if the file doesn't exist)
Examples
This function is used in the following places in Espruino's documentation
fs.statSync ⇒
Call type:
fs.statSync(path)Description
Return information on the given file. This returns an object with the following fields:
size: size in bytes dir: a boolean specifying if the file is a directory or not mtime: A Date structure specifying the time the file was last modified
Note: This is only available in not devices with low flash memory
Parameters
path - The path of the file to get information on
Returns
An object describing the file, or undefined on failure
fs.unlink ⇒
Call type:
fs.unlink(path)Description
Delete the given file
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
Note: This is only available in not devices with low flash memory
Parameters
path - The path of the file to delete
Returns
True on success, or false on failure
fs.unlinkSync ⇒
Call type:
fs.unlinkSync(path)Description
Delete the given file
Note: This is only available in not devices with low flash memory
Parameters
path - The path of the file to delete
Returns
True on success, or false on failure
fs.writeFile ⇒
Call type:
fs.writeFile(path, data)Description
Write the data to the given file
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
Parameters
path - The path of the file to write
data - The data to write to the file
Returns
True on success, false on failure
fs.writeFileSync ⇒
Call type:
fs.writeFileSync(path, data)Description
Write the data to the given file
Note: This is only available in not devices with low flash memory
Parameters
path - The path of the file to write
data - The data to write to the file
Returns
True on success, false on failure
Examples
This function is used in the following places in Espruino's documentation
Function Class
This is the built-in class for Functions
Methods and Fields
- function Function.apply(this, args)
- function Function.bind(this, params, ...)
- function Function.call(this, params, ...)
- constructor Function(args, ...)
- function Function.replaceWith(newFunc)
function Function.apply ⇒
Call type:
function Function.apply(this, args)Description
This executes the function with the supplied 'this' argument and parameters
Parameters
this - The value to use as the 'this' argument when executing the function
args - Optional Array of Arguments
Returns
The return value of executing this function
function Function.bind ⇒
Call type:
function Function.bind(this, params, ...)Description
This executes the function with the supplied 'this' argument and parameters
Parameters
this - The value to use as the 'this' argument when executing the function
params, ... - Optional Default parameters that are prepended to the call
Returns
The 'bound' function
Examples
This function is used in the following places in Espruino's documentation
function Function.call ⇒
Call type:
function Function.call(this, params, ...)Description
This executes the function with the supplied 'this' argument and parameters
Parameters
this - The value to use as the 'this' argument when executing the function
params, ... - Optional Parameters
Returns
The return value of executing this function
constructor Function ⇒
Call type:
new Function(args, ...)Description
Creates a function
Parameters
args, ... - Zero or more arguments (as strings), followed by a string representing the code to run
Returns
A Number object
function Function.replaceWith ⇒
Call type:
function Function.replaceWith(newFunc)Description
This replaces the function with the one in the argument - while keeping the old function's scope. This allows inner functions to be edited, and is used when edit() is called on an inner function.
Parameters
newFunc - The new function to replace this function with
Graphics Class
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)
Methods and Fields
- function Graphics.clear()
- Graphics.createArrayBuffer(width, height, bpp, options)
- Graphics.createCallback(width, height, bpp, callback)
- Graphics.createSDL(width, height)
- function Graphics.drawCircle(x, y, rad)
- function Graphics.drawImage(image, x, y)
- function Graphics.drawLine(x1, y1, x2, y2)
- function Graphics.drawRect(x1, y1, x2, y2)
- function Graphics.drawString(str, x, y)
- function Graphics.fillCircle(x, y, rad)
- function Graphics.fillPoly(poly)
- function Graphics.fillRect(x1, y1, x2, y2)
- function Graphics.getBgColor()
- function Graphics.getColor()
- function Graphics.getHeight()
- function Graphics.getModified(reset)
- function Graphics.getPixel(x, y)
- function Graphics.getWidth()
- function Graphics.lineTo(x, y)
- function Graphics.moveTo(x, y)
- function Graphics.setBgColor(r, g, b)
- function Graphics.setColor(r, g, b)
- function Graphics.setFontBitmap()
- function Graphics.setFontCustom(bitmap, firstChar, width, height)
- function Graphics.setFontVector(size)
- function Graphics.setPixel(x, y, col)
- function Graphics.setRotation(rotation, reflect)
- function Graphics.stringWidth(str)
function Graphics.clear ⇒
Call type:
function Graphics.clear()Description
Clear the LCD with the Background Color
Examples
This function is used in the following places in Espruino's documentation
Graphics.createArrayBuffer ⇒
Call type:
Graphics.createArrayBuffer(width, height, bpp, options)Description
Create a Graphics object that renders to an Array Buffer. This will have a field called 'buffer' that can get used to get at the buffer itself
Parameters
width - Pixels wide
height - Pixels high
bpp - Number of bits per pixel
options - An object of other options. { zigzag : true/false(default), vertical_byte : true/false(default), msb : true/false(default), color_order: 'rgb'(default),'bgr',etc }
zigzag = whether to alternate the direction of scanlines for rows
vertical_byte = whether to align bits in a byte vertically or not
msb = when bits<8, store pixels msb first
color_order = re-orders the colour values that are supplied via setColor
Returns
The new Graphics object
Examples
This function is used in the following places in Espruino's documentation
- BBC micro:bit
- MAX7219 7 segment display driver
- RGB123 LED Matrices/Strips
- SSD1606 e-Paper display driver
- Puck.js and BLE Printers
- Ethernet Webcam Display
- Reaction Timer using RGB123
Graphics.createCallback ⇒
Call type:
Graphics.createCallback(width, height, bpp, callback)Description
Create a Graphics object that renders by calling a JavaScript callback function to draw pixels
Parameters
width - Pixels wide
height - Pixels high
bpp - Number of bits per pixel
callback - A function of the form function(x,y,col) that is called whenever a pixel needs to be drawn, or an object with: {setPixel:function(x,y,col),fillRect:function(x1,y1,x2,y2,col)}. All arguments are already bounds checked.
Returns
The new Graphics object
Examples
This function is used in the following places in Espruino's documentation
Graphics.createSDL ⇒
Call type:
Graphics.createSDL(width, height)Description
Create a Graphics object that renders to SDL window (Linux-based devices only)
Note: This is only available in Linux with SDL support compiled in
Parameters
width - Pixels wide
height - Pixels high
Returns
The new Graphics object
function Graphics.drawCircle ⇒
Call type:
function Graphics.drawCircle(x, y, rad)Description
Draw an unfilled circle 1px wide in the Foreground Color
Parameters
x - The X axis
y - The Y axis
rad - The circle radius
function Graphics.drawImage ⇒
Call type:
function Graphics.drawImage(image, x, y)Description
Draw an image at the specified position. If the image is 1 bit, the graphics foreground/background colours will be used. Otherwise color data will be copied as-is. Bitmaps are rendered MSB-first
Parameters
image - An object with the following fields { width : int, height : int, bpp : int, buffer : ArrayBuffer, transparent: optional int }. bpp = bits per pixel, transparent (if defined) is the colour that will be treated as transparent
x - The X offset to draw the image
y - The Y offset to draw the image
Examples
This function is used in the following places in Espruino's documentation
function Graphics.drawLine ⇒
Call type:
function Graphics.drawLine(x1, y1, x2, y2)Description
Draw a line between x1,y1 and x2,y2 in the current foreground color
Parameters
x1 - The left
y1 - The top
x2 - The right
y2 - The bottom
Examples
This function is used in the following places in Espruino's documentation
function Graphics.drawRect ⇒
Call type:
function Graphics.drawRect(x1, y1, x2, y2)Description
Draw an unfilled rectangle 1px wide in the Foreground Color
Parameters
x1 - The left
y1 - The top
x2 - The right
y2 - The bottom
function Graphics.drawString ⇒
Call type:
function Graphics.drawString(str, x, y)Description
Draw a string of text in the current font
Parameters
str - The string
x - The X position of the leftmost pixel
y - The Y position of the topmost pixel
function Graphics.fillCircle ⇒
Call type:
function Graphics.fillCircle(x, y, rad)Description
Draw a filled circle in the Foreground Color
Parameters
x - The X axis
y - The Y axis
rad - The circle radius
function Graphics.fillPoly ⇒
Call type:
function Graphics.fillPoly(poly)Description
Draw a filled polygon in the current foreground color
Parameters
poly - An array of vertices, of the form [x1,y1,x2,y2,x3,y3,etc]
function Graphics.fillRect ⇒
Call type:
function Graphics.fillRect(x1, y1, x2, y2)Description
Fill a rectangular area in the Foreground Color
Parameters
x1 - The left
y1 - The top
x2 - The right
y2 - The bottom
function Graphics.getBgColor ⇒
Call type:
function Graphics.getBgColor()Description
Get the background color to use for subsequent drawing operations
Returns
The integer value of the colour
function Graphics.getColor ⇒
Call type:
function Graphics.getColor()Description
Get the color to use for subsequent drawing operations
Returns
The integer value of the colour
function Graphics.getHeight ⇒
Call type:
function Graphics.getHeight()Description
The height of the LCD
Returns
The height of the LCD
function Graphics.getModified ⇒
Call type:
function Graphics.getModified(reset)Description
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}
Parameters
reset - Whether to reset the modified area or not
Returns
An object {x1,y1,x2,y2} containing the modified area, or undefined if not modified
function Graphics.getPixel ⇒
Call type:
function Graphics.getPixel(x, y)Description
Get a pixel's color
Parameters
x - The left
y - The top
Returns
The color
function Graphics.getWidth ⇒
Call type:
function Graphics.getWidth()Description
The width of the LCD
Returns
The width of the LCD
function Graphics.lineTo ⇒
Call type:
function Graphics.lineTo(x, y)Description
Draw a line from the last position of lineTo or moveTo to this position
Parameters
x - X value
y - Y value
function Graphics.moveTo ⇒
Call type:
function Graphics.moveTo(x, y)Description
Move the cursor to a position - see lineTo
Parameters
x - X value
y - Y value
function Graphics.setBgColor ⇒
Call type:
function Graphics.setBgColor(r, g, b)Description
Set the background color to use for subsequent drawing operations
Parameters
r - Red (between 0 and 1) OR an integer representing the color in the current bit depth and color order
g - Green (between 0 and 1)
b - Blue (between 0 and 1)
function Graphics.setColor ⇒
Call type:
function Graphics.setColor(r, g, b)Description
Set the color to use for subsequent drawing operations
Parameters
r - Red (between 0 and 1) OR an integer representing the color in the current bit depth and color order
g - Green (between 0 and 1)
b - Blue (between 0 and 1)
Examples
This function is used in the following places in Espruino's documentation
function Graphics.setFontBitmap ⇒
Call type:
function Graphics.setFontBitmap()Description
Make subsequent calls to drawString use the built-in 4x6 pixel bitmapped Font
function Graphics.setFontCustom ⇒
Call type:
function Graphics.setFontCustom(bitmap, firstChar, width, height)Description
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.
Parameters
bitmap - A column-first, MSB-first, 1bpp bitmap containing the font bitmap
firstChar - The first character in the font - usually 32 (space)
width - The width of each character in the font. Either an integer, or a string where each character represents the width
height - The height as an integer
function Graphics.setFontVector ⇒
Call type:
function Graphics.setFontVector(size)Description
Make subsequent calls to drawString use a Vector Font of the given height
Note: This is only available in not devices with low flash memory
Parameters
size - The height of the font, as an integer
Examples
This function is used in the following places in Espruino's documentation
function Graphics.setPixel ⇒
Call type:
function Graphics.setPixel(x, y, col)Description
Set a pixel's color
Parameters
x - The left
y - The top
col - The color
function Graphics.setRotation ⇒
Call type:
function Graphics.setRotation(rotation, reflect)Description
Set the current rotation of the graphics device.
Parameters
rotation - The clockwise rotation. 0 for no rotation, 1 for 90 degrees, 2 for 180, 3 for 270
reflect - Whether to reflect the image
function Graphics.stringWidth ⇒
Call type:
function Graphics.stringWidth(str)Description
Return the size in pixels of a string of text in the current font
Parameters
str - The string
Returns
The length of the string in pixels
HASH Class
Note: This class is currently only included in builds for the original Espruino boards. For other boards you will have to make build your own firmware.
Methods and Fields
function HASH.digest ⇒
Call type:
function HASH.digest(message)Parameters
message - part of message
Returns
Hash digest
function HASH.hexdigest ⇒
Call type:
function HASH.hexdigest(message)Parameters
message - part of message
Returns
Hash hexdigest
function HASH.update ⇒
Call type:
function HASH.update(message)Parameters
message - part of message
hashlib Library
Note: This library is currently only included in builds for the original Espruino boards. For other boards you will have to make build your own firmware.
Methods and Fields
hashlib.sha224 ⇒
Call type:
hashlib.sha224(message)Parameters
message - message to hash
Returns
Returns a new HASH SHA224 Object
hashlib.sha256 ⇒
Call type:
hashlib.sha256(message)Parameters
message - message to hash
Returns
Returns a new HASH SHA256 Object
http Library
This library allows you to create http servers and make http requests
In order to use this, you will need an extra module to get network connectivity such as the TI CC3000 or WIZnet W5500.
This is designed to be a cut-down version of the node.js library. Please see the Internet page for more information on how to use it.
Methods and Fields
http.createServer ⇒
Call type:
http.createServer(callback)Description
Create an HTTP Server
When a request to the server is made, the callback is called. In the callback you can use the methods on the response (httpSRs) to send data. You can also add request.on('data',function() { ... }) to listen for POSTed data
Parameters
callback - A function(request,response) that will be called when a connection is made
Returns
Returns a new httpSrv object
Examples
This function is used in the following places in Espruino's documentation
- CC3000 WiFi Module
- WIZnet WIZ550io/W5500 Ethernet module
- Wifi Remote Console
- File IO and SD cards
- Internet (HTTP)
- Ethernet Webcam Display
- Graphical Web Interface
- Interactive Web-based UI
- WiFi Enabled Thermometer
- HTTP File Server
http.get ⇒
Call type:
http.get(options, callback)Description
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.
Parameters
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
Returns a new httpCRq object
http.request ⇒
Call type:
http.request(options, callback)Description
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)
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.
Parameters
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
Returns a new httpCRq object
httpCRq Class
The HTTP client request, returned by http.request() and http.get().
Methods and Fields
event httpCRq.drain ⇒
Call type:
httpCRq.on('drain', function() { ... });Description
An event that is fired when the buffer is empty and it can accept more data to send.
function httpCRq.end ⇒
Call type:
function httpCRq.end(data)Description
Finish this HTTP request - optional data to append as an argument
Parameters
data - A string containing data to send
event httpCRq.error ⇒
Call type:
httpCRq.on('error', function() { ... });Description
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 ⇒
Call type:
function httpCRq.write(data)Parameters
data - A string containing data to send
Returns
For note compatibility, the boolean false. When the send buffer is empty, a drain event will be sent
httpCRs Class
The HTTP client response, passed to the callback of http.request() an http.get().
Methods and Fields
- function httpCRs.available()
- event httpCRs.close()
- event httpCRs.data(data)
- event httpCRs.error()
- function httpCRs.pipe(destination, options)
- function httpCRs.read(chars)
function httpCRs.available ⇒
Call type:
function httpCRs.available()Description
Return how many bytes are available to read. If there is a 'data' event handler, this will always return 0.
Returns
How many bytes are available
event httpCRs.close ⇒
Call type:
httpCRs.on('close', function() { ... });Description
Called when the connection closes with one hadError boolean parameter, which indicates whether an error occurred.
event httpCRs.data ⇒
Call type:
httpCRs.on('data', function(data) { ... });Description
The 'data' event is called when data is received. If a handler is defined with X.on('data', function(data) { ... }) then it will be called, otherwise data will be stored in an internal buffer, where it can be retrieved with X.read()
Parameters
data - A string containing one or more characters of received data
event httpCRs.error ⇒
Call type:
httpCRs.on('error', function() { ... });Description
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 ⇒
Call type:
function httpCRs.pipe(destination, options)Description
Pipe this to a stream (an object with a 'write' method)
Note: This is only available in not devices with low flash memory
Parameters
destination - The destination file/stream that will receive content from the source.
options - An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished
function httpCRs.read ⇒
Call type:
function httpCRs.read(chars)Description
Return a string containing characters that have been received
Parameters
chars - The number of characters to read, or undefined/0 for all available
Returns
A string containing the required bytes.
httpSRq Class
The HTTP server request
Methods and Fields
- function httpSRq.available()
- event httpSRq.close()
- event httpSRq.data(data)
- function httpSRq.pipe(destination, options)
- function httpSRq.read(chars)
function httpSRq.available ⇒
Call type:
function httpSRq.available()Description
Return how many bytes are available to read. If there is already a listener for data, this will always return 0.
Returns
How many bytes are available
event httpSRq.close ⇒
Call type:
httpSRq.on('close', function() { ... });Description
Called when the connection closes.
event httpSRq.data ⇒
Call type:
httpSRq.on('data', function(data) { ... });Description
The 'data' event is called when data is received. If a handler is defined with X.on('data', function(data) { ... }) then it will be called, otherwise data will be stored in an internal buffer, where it can be retrieved with X.read()
Parameters
data - A string containing one or more characters of received data
function httpSRq.pipe ⇒
Call type:
function httpSRq.pipe(destination, options)Description
Pipe this to a stream (an object with a 'write' method)
Note: This is only available in not devices with low flash memory
Parameters
destination - The destination file/stream that will receive content from the source.
options - An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished
function httpSRq.read ⇒
Call type:
function httpSRq.read(chars)Description
Return a string containing characters that have been received
Parameters
chars - The number of characters to read, or undefined/0 for all available
Returns
A string containing the required bytes.
httpSRs Class
The HTTP server response
Methods and Fields
- event httpSRs.close()
- event httpSRs.drain()
- function httpSRs.end(data)
- function httpSRs.write(data)
- function httpSRs.writeHead(statusCode, headers)
event httpSRs.close ⇒
Call type:
httpSRs.on('close', function() { ... });Description
Called when the connection closes.
event httpSRs.drain ⇒
Call type:
httpSRs.on('drain', function() { ... });Description
An event that is fired when the buffer is empty and it can accept more data to send.
function httpSRs.end ⇒
Call type:
function httpSRs.end(data)Parameters
data - A string containing data to send
function httpSRs.write ⇒
Call type:
function httpSRs.write(data)Parameters
data - A string containing data to send
Returns
For note compatibility, the boolean false. When the send buffer is empty, a drain event will be sent
function httpSRs.writeHead ⇒
Call type:
function httpSRs.writeHead(statusCode, headers)Parameters
statusCode - The HTTP status code
headers - An object containing the headers
httpSrv Class
The HTTP server created by require('http').createServer
Methods and Fields
function httpSrv.close ⇒
Call type:
function httpSrv.close()Description
Stop listening for new HTTP connections
function httpSrv.listen ⇒
Call type:
function httpSrv.listen(port)Description
Start listening for new HTTP connections on the given port
Parameters
port - The port to listen on
I2C Class
This class allows use of the built-in I2C ports. Currently it allows I2C Master mode only.
All addresses are in 7 bit format. If you have an 8 bit address then you need to shift it one bit to the right.
Instances
Methods and Fields
- I2C.find(pin)
- constructor I2C()
- function I2C.readFrom(address, quantity)
- function I2C.setup(options)
- function I2C.writeTo(address, data, ...)
I2C.find ⇒
Call type:
I2C.find(pin)Description
Try and find an I2C hardware device that will work on this pin (eg. I2C1)
May return undefined if no device can be found.
Parameters
pin - A pin to search with
Returns
An object of type I2C, or undefined if one couldn't be found.
constructor I2C ⇒
Call type:
new I2C()Description
Create a software I2C port. This has limited functionality (no baud rate), but it can work on any pins.
Use SPI.setup to configure this port.
function I2C.readFrom ⇒
Call type:
function I2C.readFrom(address, quantity)Description
Request bytes from the given slave device, and return them as a Uint8Array (packed array of bytes). This is like using Arduino Wire's requestFrom, available and read functions. Sends a STOP
Parameters
address - The 7 bit address of the device to request bytes from, or an object of the form {address:12, stop:false} to send this data without a STOP signal.
quantity - The number of bytes to request
Returns
The data that was returned - as a Uint8Array
function I2C.setup ⇒
Call type:
function I2C.setup(options)Description
Set up this I2C port
If not specified in options, the default pins are used (usually the lowest numbered pins on the lowest port that supports this peripheral)
Parameters
options - An optional structure containing extra information on initialising the I2C port{scl:pin, sda:pin, bitrate:100000}
You can find out which pins to use by looking at your board's reference page and searching for pins with the I2C marker. Note that 400000kHz is the maximum bitrate for most parts.
Examples
This function is used in the following places in Espruino's documentation
- ADS1x15 programmable gain ADC
- Espruino module for BME280
- BMP085/BMP180 digital pressure sensor
- Espruino module for BMP280
- CAP1188 capacitive touch breakout
- Digole LCD driver (monochrome)
- HD44780 Character LCD
- HP03S pressure sensor module
- HTS221 pressure sensor
- HTU21D Temperature and RH Sensor
- LPS25HB pressure sensor
- LSM303DLHC Accelerometer
- MAG3110 3-axis magnetometer
- MCP23xxx I2C and SPI port expanders
- MCP9808 precision I2C temperature sensor
- MLX90614 Infra Red thermometer
- MMC212xMG Dual-axis Magnetic Sensor from MEMSIC used in HDMM01 breakout from Pollin
- MPL115A2, I2C digital barometer and temperature sensor
- MPL3115A2 Digital Altitude / Pressure / Temperature Sensor
- MPU6050 accelerometer and gyro
- PN532 NFC/RFID module
- SH1106 OLED driver
- Sensirion SHT20, SHT21 & SHT25 Temperature and Relative Humidity Sensor
- SSD1306 OLED driver
- TCS3472x I2C Color Sensor
- TSL2561 Luminosity sensor
- Wii Nunchuck
- Running code from an EEPROM
- Remote Control Helicopter with Wii Nunchuck
function I2C.writeTo ⇒
Call type:
function I2C.writeTo(address, data, ...)Description
Transmit to the slave device with the given address. This is like Arduino's beginTransmission, write, and endTransmission rolled up into one.
Parameters
address - The 7 bit address of the device to transmit to, or an object of the form {address:12, stop:false} to send this data without a STOP signal.
data, ... - One or more items to write. May be ints, strings, arrays, or objects of the form {data: ..., count:#}.
Int16Array Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Int16Array ⇒
Call type:
new Int16Array(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
Int32Array Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Int32Array ⇒
Call type:
new Int32Array(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
Int8Array Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Int8Array ⇒
Call type:
new Int8Array(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
InternalError Class
The base class for internal errors
Methods and Fields
constructor InternalError ⇒
Call type:
new InternalError(message)Description
Creates an InternalError object
Parameters
message - An optional message string
Returns
An InternalError object
function InternalError.toString ⇒
Call type:
function InternalError.toString()Returns
A String
JSON Class
An Object that handles conversion to and from the JSON data interchange format
Methods and Fields
JSON.parse ⇒
Call type:
JSON.parse(string)Description
Parse the given JSON string into a JavaScript object
NOTE: This implementation uses eval() internally, and as such it is unsafe as it can allow arbitrary JS commands to be executed.
Parameters
string - A JSON string
Returns
The JavaScript object created by parsing the data string
Examples
This function is used in the following places in Espruino's documentation
JSON.stringify ⇒
Call type:
JSON.stringify(data, replacer, space)Description
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:
- The
replacerargument is ignored - Typed arrays like
new Uint8Array(5)will be dumped as if they were arrays, not as if they were objects (since it is more compact)
Parameters
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
Returns
A JSON string
Examples
This function is used in the following places in Espruino's documentation
- ESP8266 WiFi Module
- MFRC522 NFC/RFID module
- nRF905 Wireless Transceiver
- PN532 NFC/RFID module
- HopeRF RFM69 Wireless Module
- RN2483 LoRa Modules
- Espruino Pico Robot PCB
- Wii Nunchuck
- LPRS easyRadio (eRIC) Radio Modules
- IoT Services
- WebSockets
- Puck.js and HTTP Proxies
- Internet (HTTP)
- WiFi Enabled Thermometer
- WiFi Xively Humidity/Temperature Sensor with Display
Math Class
This is a standard JavaScript class that contains useful Maths routines
Methods and Fields
- Math.abs(x)
- Math.acos(x)
- Math.asin(x)
- Math.atan(x)
- Math.atan2(y, x)
- Math.ceil(x)
- Math.clip(x, min, max)
- Math.cos(theta)
- Math.E
- Math.exp(x)
- Math.floor(x)
- Math.LN10
- Math.LN2
- Math.log(x)
- Math.LOG10E
- Math.LOG2E
- Math.max(args, ...)
- Math.min(args, ...)
- Math.PI
- Math.pow(x, y)
- Math.random()
- Math.round(x)
- Math.sin(theta)
- Math.sqrt(x)
- Math.SQRT1_2
- Math.SQRT2
- Math.tan(theta)
- Math.wrap(x, max)
Math.abs ⇒
Call type:
Math.abs(x)Parameters
x - A floating point value
Returns
The absolute value of x (eg, Math.abs(2)==2, but also Math.abs(-2)==2)
Examples
This function is used in the following places in Espruino's documentation
Math.acos ⇒
Call type:
Math.acos(x)Parameters
x - The value to get the arc cosine of
Returns
The arc cosine of x, between 0 and PI
Math.asin ⇒
Call type:
Math.asin(x)Parameters
x - The value to get the arc sine of
Returns
The arc sine of x, between -PI/2 and PI/2
Math.atan ⇒
Call type:
Math.atan(x)Parameters
x - The value to get the arc tangent of
Returns
The arc tangent of x, between -PI/2 and PI/2
Math.atan2 ⇒
Call type:
Math.atan2(y, x)Parameters
y - The Y-part of the angle to get the arc tangent of
x - The X-part of the angle to get the arc tangent of
Returns
The arctangent of Y/X, between -PI and PI
Math.ceil ⇒
Call type:
Math.ceil(x)Parameters
x - The value to round up
Returns
x, rounded upwards to the nearest integer
Math.clip ⇒
Call type:
Math.clip(x, min, max)Description
DEPRECATED - Please use E.clip() instead. Clip a number to be between min and max (inclusive)
Note: This is only available in not devices with low flash memory
Parameters
x - A floating point value to clip
min - The smallest the value should be
max - The largest the value should be
Returns
The value of x, clipped so as not to be below min or above max.
Math.cos ⇒
Call type:
Math.cos(theta)Parameters
theta - The angle to get the cosine of
Returns
The cosine of theta
Examples
This function is used in the following places in Espruino's documentation
Math.E ⇒
Call type:
Math.EReturns
The value of E - 2.718281828459045
Math.exp ⇒
Call type:
Math.exp(x)Parameters
x - The value raise E to the power of
Returns
E^x
Math.floor ⇒
Call type:
Math.floor(x)Parameters
x - The value to round down
Returns
x, rounded downwards to the nearest integer
Examples
This function is used in the following places in Espruino's documentation
Math.LN10 ⇒
Call type:
Math.LN10Returns
The natural logarithm of 10 - 2.302585092994046
Math.LN2 ⇒
Call type:
Math.LN2Returns
The natural logarithm of 2 - 0.6931471805599453
Math.log ⇒
Call type:
Math.log(x)Parameters
x - The value to take the logarithm (base E) root of
Returns
The log (base E) of x
Examples
This function is used in the following places in Espruino's documentation
Math.LOG10E ⇒
Call type:
Math.LOG10EReturns
The base 10 logarithm of e - 0.4342944819032518
Math.LOG2E ⇒
Call type:
Math.LOG2EReturns
The base 2 logarithm of e - 1.4426950408889634
Math.max ⇒
Call type:
Math.max(args, ...)Description
Find the maximum of a series of numbers
Parameters
args, ... - A floating point value to clip
Returns
The maximum of the supplied values
Examples
This function is used in the following places in Espruino's documentation
Math.min ⇒
Call type:
Math.min(args, ...)Description
Find the minimum of a series of numbers
Parameters
args, ... - A floating point value to clip
Returns
The minimum of the supplied values
Examples
This function is used in the following places in Espruino's documentation
- MMC212xMG Dual-axis Magnetic Sensor from MEMSIC used in HDMM01 breakout from Pollin
- TCS3472x I2C Color Sensor
Math.PI ⇒
Call type:
Math.PIReturns
The value of PI - 3.141592653589793
Math.pow ⇒
Call type:
Math.pow(x, y)Parameters
x - The value to raise to the power
y - The power x should be raised to
Returns
x raised to the power y (x^y)
Math.random ⇒
Call type:
Math.random()Returns
A random number between 0 and 1
Examples
This function is used in the following places in Espruino's documentation
- WS2811/WS2812 LED String/Strip
- Digital Dice
- Flashing Lights
- Graphical Web Interface
- Pico Electronic Dice
- Slot Machine
- Snake Game
- Reaction Timer using RGB123
Math.round ⇒
Call type:
Math.round(x)Parameters
x - The value to round
Returns
x, rounded to the nearest integer
Examples
This function is used in the following places in Espruino's documentation
Math.sin ⇒
Call type:
Math.sin(theta)Parameters
theta - The angle to get the sine of
Returns
The sine of theta
Examples
This function is used in the following places in Espruino's documentation
- LPD-6416 LED Matrix Display
- MAX7219 7 segment display driver
- Servo Motors
- Stepper Motors
- WS2811/WS2812 LED String/Strip
- USB and USB HID
- Individually Addressable LEDs
- Pico LCD Display Hello World
Math.sqrt ⇒
Call type:
Math.sqrt(x)Parameters
x - The value to take the square root of
Returns
The square root of x
Examples
This function is used in the following places in Espruino's documentation
Math.SQRT1_2 ⇒
Call type:
Math.SQRT1_2Returns
The square root of 1/2 - 0.7071067811865476
Math.SQRT2 ⇒
Call type:
Math.SQRT2Returns
The square root of 2 - 1.4142135623730951
Math.tan ⇒
Call type:
Math.tan(theta)Parameters
theta - The angle to get the tangent of
Returns
The tangent of theta
Math.wrap ⇒
Call type:
Math.wrap(x, max)Description
Wrap a number around if it is less than 0 or greater than or equal to max. For instance you might do: Math.wrap(angleInDegrees, 360)
Note: This is only available in not devices with low flash memory
Parameters
x - A floating point value to wrap
max - The largest the value should be
Returns
The value of x, wrapped so as not to be below min or above max.
Examples
This function is used in the following places in Espruino's documentation
Modules Class
Built-in class that caches the modules used by the require command
Methods and Fields
- Modules.addCached(id, sourcecode)
- Modules.getCached()
- Modules.removeAllCached()
- Modules.removeCached(id)
Modules.addCached ⇒
Call type:
Modules.addCached(id, sourcecode)Description
Add the given module to the cache
Parameters
id - The module name to add
sourcecode - The module's sourcecode
Modules.getCached ⇒
Call type:
Modules.getCached()Description
Return an array of module names that have been cached
Returns
An array of module names
Modules.removeAllCached ⇒
Call type:
Modules.removeAllCached()Description
Remove all cached modules
Modules.removeCached ⇒
Call type:
Modules.removeCached(id)Description
Remove the given module from the list of cached modules
Parameters
id - The module name to remove
net Library
This library allows you to create TCPIP servers and clients
In order to use this, you will need an extra module to get network connectivity.
This is designed to be a cut-down version of the node.js library. Please see the Internet page for more information on how to use it.
Methods and Fields
net.connect ⇒
Call type:
net.connect(options, callback)Description
Create a socket connection
Parameters
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
Returns a new net.Socket object
Examples
This function is used in the following places in Espruino's documentation
net.createServer ⇒
Call type:
net.createServer(callback)Description
Create a Server
When a request to the server is made, the callback is called. In the callback you can use the methods on the connection to send data. You can also add connection.on('data',function() { ... }) to listen for received data
Parameters
callback - A function(connection) that will be called when a connection is made
Returns
Returns a new Server Object
Examples
This function is used in the following places in Espruino's documentation
NetworkJS Library
Library that initialises a network device that calls into JavaScript
Methods and Fields
NetworkJS.create ⇒
Call type:
NetworkJS.create(obj)Description
Initialise the network using the callbacks given and return the first argument. For instance:
require("NetworkJS").create({
create : function(host,port) {
// Create a socket and return its index, host is a string, port is an integer.
// If host isn't defined, create a server socket
console.log("Create",host,port);
return 1;
},
close : function(sckt) {
// Close the socket. returns nothing
},
accept : function(sckt) {
// Accept the connection on the server socket. Returns socket number or -1 if no connection
return -1;
},
recv : function(sckt, maxLen) {
// Receive data. Returns a string (even if empty).
// If non-string returned, socket is then closed
return null;//or "";
},
send : function(sckt, data) {
// Send data (as string). Returns the number of bytes sent - 0 is ok.
// Less than 0
return data.length;
}
});
Parameters
obj - An object containing functions to access the network device
Returns
The object passed in
NodeMCU Class
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.
Methods and Fields
- NodeMCU.A0
- NodeMCU.D0
- NodeMCU.D1
- NodeMCU.D10
- NodeMCU.D2
- NodeMCU.D3
- NodeMCU.D4
- NodeMCU.D5
- NodeMCU.D6
- NodeMCU.D7
- NodeMCU.D8
- NodeMCU.D9
NodeMCU.A0 ⇒
Call type:
NodeMCU.A0Returns
A Pin
NodeMCU.D0 ⇒
Call type:
NodeMCU.D0Returns
A Pin
NodeMCU.D1 ⇒
Call type:
NodeMCU.D1Returns
A Pin
NodeMCU.D10 ⇒
Call type:
NodeMCU.D10Returns
A Pin
NodeMCU.D2 ⇒
Call type:
NodeMCU.D2Returns
A Pin
NodeMCU.D3 ⇒
Call type:
NodeMCU.D3Returns
A Pin
NodeMCU.D4 ⇒
Call type:
NodeMCU.D4Returns
A Pin
NodeMCU.D5 ⇒
Call type:
NodeMCU.D5Returns
A Pin
NodeMCU.D6 ⇒
Call type:
NodeMCU.D6Returns
A Pin
NodeMCU.D7 ⇒
Call type:
NodeMCU.D7Returns
A Pin
NodeMCU.D8 ⇒
Call type:
NodeMCU.D8Returns
A Pin
NodeMCU.D9 ⇒
Call type:
NodeMCU.D9Returns
A Pin
NRF Class
The NRF class is for controlling functionality of the Nordic nRF51/nRF52 chips. Currently these only used in Puck.js and the BBC micro:bit.
The main part of this is control of Bluetooth Low Energy - both searching for devices, and changing advertising data.
Methods and Fields
- event NRF.characteristicsDiscover()
- event NRF.connect(addr)
- NRF.connect(mac)
- event NRF.disconnect()
- NRF.disconnect()
- NRF.findDevices(callback, time)
- NRF.getAddress()
- NRF.getBattery()
- event NRF.NFCoff()
- event NRF.NFCon()
- NRF.nfcRaw(payload)
- NRF.nfcURL(url)
- NRF.requestDevice(options)
- NRF.restart()
- NRF.sendHIDReport(data, callback)
- event NRF.servicesDiscover()
- NRF.setAdvertising(data, options)
- NRF.setLowPowerConnection(lowPower)
- NRF.setRSSIHandler(callback)
- NRF.setScan(callback)
- NRF.setServices(data, options)
- NRF.setTxPower(power)
- NRF.sleep()
- NRF.updateServices(data)
- NRF.wake()
event NRF.characteristicsDiscover ⇒
Call type:
NRF.on('characteristicsDiscover', function() { ... });Description
Called with discovered characteristics when discovery is finished
Note: This is only available in NRF52 devices (like Puck.js)
event NRF.connect ⇒
Call type:
NRF.on('connect', function(addr) { ... });Description
Called when a host device connects to Espruino. The first argument contains the address.
Parameters
addr - The address of the device that has connected
NRF.connect ⇒
Call type:
NRF.connect(mac)Description
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").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) {
characteristic.writeValue("LED1.set()\n");
}).then(function() {
gatt.disconnect();
console.log("Done!");
});
Note: This is only available on some devices
Note: This is only available in NRF52 devices (like Puck.js)
Parameters
mac - The MAC address to connect to
Returns
A Promise that is resolved (or rejected) when the connection is complete
event NRF.disconnect ⇒
Call type:
NRF.on('disconnect', function() { ... });Description
Called when a host device disconnects from Espruino.
Examples
This function is used in the following places in Espruino's documentation
NRF.disconnect ⇒
Call type:
NRF.disconnect()Description
If a device is connected to Espruino, disconnect from it.
Examples
This function is used in the following places in Espruino's documentation
NRF.findDevices ⇒
Call type:
NRF.findDevices(callback, time)Description
Utility function to return a list of BLE devices detected in range.
NRF.findDevices(function(devices) {
console.log(devices);
}, 1000);
prints something like:
[
BluetoothDevice {
"id": "e7:e0:57:ad:36:a2 random",
"rssi": -45,
"services": [ ],
"data": new ArrayBuffer([ ... ]),
"name": "Puck.js 36a2"
},
BluetoothDevice {
"id": "c0:52:3f:50:42:c9 random",
"rssi": -65,
"services": [ ],
"data": new ArrayBuffer([ ... ]),
"name": "Puck.js 8f57"
}
]
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.
Parameters
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 ⇒
Call type:
NRF.getAddress()Description
Get this device's Bluetooth MAC address
Returns
MAC address - a string of the form 'aa:bb:cc:dd:ee:ff'
NRF.getBattery ⇒
Call type:
NRF.getBattery()Description
Get the battery level in volts
Returns
Battery level in volts
event NRF.NFCoff ⇒
Call type:
NRF.on('NFCoff', function() { ... });Description
Called when an NFC field is no longer detected
Note: This is only available in NRF52 devices (like Puck.js)
event NRF.NFCon ⇒
Call type:
NRF.on('NFCon', function() { ... });Description
Called when an NFC field is detected
Note: This is only available in NRF52 devices (like Puck.js)
NRF.nfcRaw ⇒
Call type:
NRF.nfcRaw(payload)Description
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 on nRF52-based devices
Note: This is only available in NRF52 devices (like Puck.js)
Parameters
payload - The NFC NDEF message to deliver to the reader
NRF.nfcURL ⇒
Call type:
NRF.nfcURL(url)Description
Enables NFC and starts advertising the given URL. For example:
NRF.nfcURL("http://espruino.com");
Note: This is only available on nRF52-based devices
Note: This is only available in NRF52 devices (like Puck.js)
Parameters
url - The URL string to expose on NFC, or undefined to disable NFC
NRF.requestDevice ⇒
Call type:
NRF.requestDevice(options)Description
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 name
NRF.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) {
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 on some devices
Note: This is only available in NRF52 devices (like Puck.js)
Parameters
options - Options used to filter the device to use
Returns
A Promise that is resolved (or rejected) when the connection is complete
NRF.restart ⇒
Call type:
NRF.restart()Description
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 ⇒
Call type:
NRF.sendHIDReport(data, callback)Description
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)
Parameters
data - Input report data as an array
callback - A callback function to be called when the data is sent
Examples
This function is used in the following places in Espruino's documentation
event NRF.servicesDiscover ⇒
Call type:
NRF.on('servicesDiscover', function() { ... });Description
Called with discovered services when discovery is finished
Note: This is only available in NRF52 devices (like Puck.js)
NRF.setAdvertising ⇒
Call type:
NRF.setAdvertising(data, options)Description
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);
Note: Currently only standardised bluetooth UUIDs are allowed (see the list above).
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});
You can even specify an array of arrays, in which case each advertising packet will be iterated over in turn - for instance to make your device advertise both Eddystone and iBeacon:
NRF.setAdvertising([
[0x03,0x03,0xAA,0xFE,0x13,0x16,0xAA,0xFE,0x10,0xF8,0x03,'g','o','o','.','g','l','/','C','H','o','J','H','0'],
[....],
[....],
],{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
interval: 600 // Advertising interval in msec, between 20 and 10000
}
Parameters
data - The data to advertise as an object - see below for more info
options - An optional object of options
NRF.setLowPowerConnection ⇒
Call type:
NRF.setLowPowerConnection(lowPower)Description
This sets the connection parameters - these affect the transfer speed and power usage when the device is connected.
- When not low power, the connection interval is between 7.5 and 20ms
- When low power, the connection interval is between 500 and 1000ms
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.
Parameters
lowPower - Whether the connection is low power or not
NRF.setRSSIHandler ⇒
Call type:
NRF.setRSSIHandler(callback)Description
Start/stop listening for RSSI values on the currently active connection
RSSI is the 'Received Signal Strength Indication' in dBm
``` // Start scanning NRF.setRSSIHandler(function(rssi) { console.log(rssi); }); // prints -85 (or similar)
// Stop Scanning NRF.setRSSIHandler(); ```
Parameters
callback - The callback to call with the RSSI value, or undefined to stop
NRF.setScan ⇒
Call type:
NRF.setScan(callback)Description
Start/stop listening for BLE advertising packets within range. Returns a
BluetoothDevice for each advertsing packet
// Start scanning
packets=10;
NRF.setScan(function(d) {
packets--;
console.log(d); // print packet info
if (packets<=0)
NRF.setScan(); // stop scanning
});
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.
Parameters
callback - The callback to call with received advertising packets, or undefined to stop
NRF.setServices ⇒
Call type:
NRF.setServices(data, options)Description
Change the services and characteristics Espruino advertises.
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
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"
Note: Currently, services/characteristics can't be removed once added. As a result, calling setServices multiple times will cause characteristics to either be updated (value only) or ignored.
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
});
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.
Parameters
data - The service (and characteristics) to advertise
options - Optional object containing options
NRF.setTxPower ⇒
Call type:
NRF.setTxPower(power)Description
Set the BLE radio transmit power. The default TX power is 0 dBm.
Parameters
power - Transmit power. Accepted values are -40, -30, -20, -16, -12, -8, -4, 0, and 4 dBm. Others will give an error code.
NRF.sleep ⇒
Call type:
NRF.sleep()Description
Disable Bluetooth communications
Examples
This function is used in the following places in Espruino's documentation
NRF.updateServices ⇒
Call type:
NRF.updateServices(data)Description
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"
}
}
});
To notify connected clients of a change to the '0xABCD' characteristic in the '0xBCDE' service:
NRF.updateServices({
0xBCDE : {
0xABCD : {
value : "World",
notify: true
}
}
});
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.
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 setServices for more information
Parameters
data - The service (and characteristics) to update
NRF.wake ⇒
Call type:
NRF.wake()Description
Enable Bluetooth communications (they are enabled by default)
Nucleo Class
This is the built-in class for the Arduino-style pin namings on ST Nucleo boards
Methods and Fields
- Nucleo.A0
- Nucleo.A1
- Nucleo.A2
- Nucleo.A3
- Nucleo.A4
- Nucleo.A5
- Nucleo.D0
- Nucleo.D1
- Nucleo.D10
- Nucleo.D11
- Nucleo.D12
- Nucleo.D13
- Nucleo.D14
- Nucleo.D15
- Nucleo.D2
- Nucleo.D3
- Nucleo.D4
- Nucleo.D5
- Nucleo.D6
- Nucleo.D7
- Nucleo.D8
- Nucleo.D9
Nucleo.A0 ⇒
Call type:
Nucleo.A0Returns
A Pin
Nucleo.A1 ⇒
Call type:
Nucleo.A1Returns
A Pin
Nucleo.A2 ⇒
Call type:
Nucleo.A2Returns
A Pin
Nucleo.A3 ⇒
Call type:
Nucleo.A3Returns
A Pin
Nucleo.A4 ⇒
Call type:
Nucleo.A4Returns
A Pin
Nucleo.A5 ⇒
Call type:
Nucleo.A5Returns
A Pin
Nucleo.D0 ⇒
Call type:
Nucleo.D0Returns
A Pin
Nucleo.D1 ⇒
Call type:
Nucleo.D1Returns
A Pin
Nucleo.D10 ⇒
Call type:
Nucleo.D10Returns
A Pin
Nucleo.D11 ⇒
Call type:
Nucleo.D11Returns
A Pin
Nucleo.D12 ⇒
Call type:
Nucleo.D12Returns
A Pin
Nucleo.D13 ⇒
Call type:
Nucleo.D13Returns
A Pin
Nucleo.D14 ⇒
Call type:
Nucleo.D14Returns
A Pin
Nucleo.D15 ⇒
Call type:
Nucleo.D15Returns
A Pin
Nucleo.D2 ⇒
Call type:
Nucleo.D2Returns
A Pin
Nucleo.D3 ⇒
Call type:
Nucleo.D3Returns
A Pin
Nucleo.D4 ⇒
Call type:
Nucleo.D4Returns
A Pin
Nucleo.D5 ⇒
Call type:
Nucleo.D5Returns
A Pin
Nucleo.D6 ⇒
Call type:
Nucleo.D6Returns
A Pin
Nucleo.D7 ⇒
Call type:
Nucleo.D7Returns
A Pin
Nucleo.D8 ⇒
Call type:
Nucleo.D8Returns
A Pin
Nucleo.D9 ⇒
Call type:
Nucleo.D9Returns
A Pin
Number Class
This is the built-in JavaScript class for numbers.
Methods and Fields
- Number.MAX_VALUE
- Number.MIN_VALUE
- Number.NaN
- Number.NEGATIVE_INFINITY
- constructor Number(value, ...)
- Number.POSITIVE_INFINITY
- function Number.toFixed(decimalPlaces)
Number.MAX_VALUE ⇒
Call type:
Number.MAX_VALUEReturns
Maximum representable value
Number.MIN_VALUE ⇒
Call type:
Number.MIN_VALUEReturns
Smallest representable value
Number.NaN ⇒
Call type:
Number.NaNReturns
Not a Number
Number.NEGATIVE_INFINITY ⇒
Call type:
Number.NEGATIVE_INFINITYReturns
Negative Infinity (-1/0)
constructor Number ⇒
Call type:
new Number(value, ...)Description
Creates a number
Parameters
value, ... - A single value to be converted to a number
Returns
A Number object
Number.POSITIVE_INFINITY ⇒
Call type:
Number.POSITIVE_INFINITYReturns
Positive Infinity (1/0)
function Number.toFixed ⇒
Call type:
function Number.toFixed(decimalPlaces)Description
Format the number as a fixed point number
Parameters
decimalPlaces - A number between 0 and 20 specifying the number of decimal digits after the decimal point
Returns
A string
Object Class
This is the built-in class for Objects
Methods and Fields
- function Object.clone()
- Object.create(proto, propertiesObject)
- Object.defineProperties(obj, props)
- Object.defineProperty(obj, name, desc)
- function Object.emit(event, args, ...)
- Object.getOwnPropertyDescriptor(obj, name)
- Object.getOwnPropertyNames(object)
- Object.getPrototypeOf(object)
- function Object.hasOwnProperty(name)
- Object.keys(object)
- property Object.length
- constructor Object(value)
- function Object.on(event, listener)
- function Object.removeAllListeners(event)
- function Object.removeListener(event, listener)
- Object.setPrototypeOf(object, prototype)
- function Object.toString(radix)
- function Object.valueOf()
function Object.clone ⇒
Call type:
function Object.clone()Description
Copy this object completely
Returns
A copy of this Object
Object.create ⇒
Call type:
Object.create(proto, propertiesObject)Description
Creates a new object with the specified prototype object and properties. properties are currently unsupported.
Parameters
proto - A prototype object
propertiesObject - An object containing properties. NOT IMPLEMENTED
Returns
A new object
Object.defineProperties ⇒
Call type:
Object.defineProperties(obj, props)Description
Adds new properties to the Object. See Object.defineProperty for more information
Parameters
obj - An object
props - An object whose fields represent property names, and whose values are property descriptors.
Returns
The object, obj.
Object.defineProperty ⇒
Call type:
Object.defineProperty(obj, name, desc)Description
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, andsetare not implemented and will be ignored.
Parameters
obj - An object
name - The name of the property
desc - The property descriptor
Returns
The object, obj.
function Object.emit ⇒
Call type:
function Object.emit(event, args, ...)Description
Call the event listeners for this object, for instance http.emit('data', 'Foo'). See Node.js's EventEmitter.
Parameters
event - The name of the event, for instance 'data'
args, ... - Optional arguments
Object.getOwnPropertyDescriptor ⇒
Call type:
Object.getOwnPropertyDescriptor(obj, name)Description
Get information on the given property in the object, or undefined
Parameters
obj - The object
name - The name of the property
Returns
An object with a description of the property. The values of writable/enumerable/configurable may not be entirely correct due to Espruino's implementation.
Object.getOwnPropertyNames ⇒
Call type:
Object.getOwnPropertyNames(object)Description
Returns an array of all properties (enumerable or not) found directly on a given object.
Note: This doesn't currently work as it should for built-in objects and their prototypes. See bug #380
Parameters
object - The Object to return a list of property names for
Returns
An array of the Object's own properties
Object.getPrototypeOf ⇒
Call type:
Object.getPrototypeOf(object)Description
Get the prototype of the given object - this is like writing object.__proto__
but is the 'proper' ES6 way of doing it
Parameters
object - An object
Returns
The prototype
function Object.hasOwnProperty ⇒
Call type:
function Object.hasOwnProperty(name)Description
Return true if the object (not its prototype) has the given property.
NOTE: This currently returns false-positives for built-in functions in prototypes
Parameters
name - The name of the property to search for
Returns
True if it exists, false if it doesn't
Object.keys ⇒
Call type:
Object.keys(object)Description
Return all enumerable keys of the given object
Parameters
object - The object to return keys for
Returns
An array of strings - one for each key on the given object
property Object.length ⇒
Call type:
property Object.lengthDescription
Find the length of the object
Returns
The length of the object
constructor Object ⇒
Call type:
new Object(value)Description
Creates an Object from the supplied argument
Parameters
value - A single value to be converted to an object
Returns
An Object
function Object.on ⇒
Call type:
function Object.on(event, listener)Description
Register an event listener for this object, for instance http.on('data', function(d) {...}). See Node.js's EventEmitter.
Parameters
event - The name of the event, for instance 'data'
listener - The listener to call when this event is received
Examples
This function is used in the following places in Espruino's documentation
- Bluetooth BLE 4.0 (HM-10)
- SSD1606 e-Paper display driver
- Espruino Notes
- Troubleshooting
- VT100 Terminal Emulator
- USART / UART / Serial Port
- Waveforms
- Quick Start
- LED Volume (VU) Meter
function Object.removeAllListeners ⇒
Call type:
function Object.removeAllListeners(event)Description
Removes all listeners, or those of the specified event.
Parameters
event - The name of the event, for instance 'data'
Examples
This function is used in the following places in Espruino's documentation
function Object.removeListener ⇒
Call type:
function Object.removeListener(event, listener)Description
Removes the specified event listener.
function foo(d) {
console.log(d);
}
Serial1.on("data", foo);
Serial1.removeListener("data", foo);
Parameters
event - The name of the event, for instance 'data'
listener - The listener to remove
Object.setPrototypeOf ⇒
Call type:
Object.setPrototypeOf(object, prototype)Description
Set the prototype of the given object - this is like writing
object.__proto__ = prototype but is the 'proper' ES6 way of doing it
Parameters
object - An object
prototype - The prototype to set on the object
Returns
The object passed in
function Object.toString ⇒
Call type:
function Object.toString(radix)Description
Convert the Object to a string
Parameters
radix - If the object is an integer, the radix (between 2 and 36) to use. NOTE: Setting a radix does not work on floating point numbers.
Returns
A String representing the object
function Object.valueOf ⇒
Call type:
function Object.valueOf()Description
Returns the primitive value of this object.
Returns
The primitive value of this object
OneWire Class
This class provides a software-defined OneWire master. It is designed to be similar to Arduino's OneWire library.
Methods and Fields
- constructor OneWire(pin)
- function OneWire.read(count)
- function OneWire.reset()
- function OneWire.search()
- function OneWire.search(command)
- function OneWire.select(rom)
- function OneWire.skip()
- function OneWire.write(data, power)
constructor OneWire ⇒
Call type:
new OneWire(pin)Description
Create a software OneWire implementation on the given pin
Parameters
pin - The pin to implement OneWire on
Returns
A OneWire object
function OneWire.read ⇒
Call type:
function OneWire.read(count)Description
Read a byte
Parameters
count - (optional) The amount of bytes to read
Returns
The byte that was read, or a Uint8Array if count was specified and >=0
function OneWire.reset ⇒
Call type:
function OneWire.reset()Description
Perform a reset cycle
Returns
True is a device was present (it held the bus low)
function OneWire.search ⇒
Call type:
function OneWire.search()Description
Search for devices
Returns
An array of devices that were found
Examples
This function is used in the following places in Espruino's documentation
function OneWire.search ⇒
Call type:
function OneWire.search(command)Description
Search for devices
Parameters
command - (Optional) command byte. If not specified (or zero), this defaults to 0xF0. This can could be set to 0xEC to perform a DS18B20 'Alarm Search Command'
Returns
An array of devices that were found
Examples
This function is used in the following places in Espruino's documentation
function OneWire.select ⇒
Call type:
function OneWire.select(rom)Description
Select a ROM - always performs a reset first
Parameters
rom - The device to select (get this using OneWire.search())
function OneWire.skip ⇒
Call type:
function OneWire.skip()Description
Skip a ROM
function OneWire.write ⇒
Call type:
function OneWire.write(data, power)Description
Write one or more bytes
Parameters
data - A byte (or array of bytes) to write
power - Whether to leave power on after write (default is false)
Pin Class
This is the built-in class for Pins, such as D0,D1,LED1, or BTN
You can call the methods on Pin, or you can use Wiring-style functions such as digitalWrite
Methods and Fields
- function Pin.getInfo()
- function Pin.getMode()
- function Pin.mode(mode)
- constructor Pin(value)
- function Pin.read()
- function Pin.reset()
- function Pin.set()
- function Pin.toggle()
- function Pin.write(value)
- function Pin.writeAtTime(value, time)
function Pin.getInfo ⇒
Call type:
function Pin.getInfo()Description
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 only available in not devices with low flash memory
Returns
An object containing information about this pins
function Pin.getMode ⇒
Call type:
function Pin.getMode()Description
Return the current mode of the given pin. See pinMode for more information.
Returns
The pin mode, as a string
function Pin.mode ⇒
Call type:
function Pin.mode(mode)Description
Set the mode of the given pin. See pinMode for more information on pin modes.
Parameters
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.
constructor Pin ⇒
Call type:
new Pin(value)Description
Creates a pin from the given argument (or returns undefined if no argument)
Parameters
value - A value to be converted to a pin. Can be a number, pin, or String.
Returns
A Pin object
function Pin.read ⇒
Call type:
function Pin.read()Description
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"
Returns
Whether pin is a logical 1 or 0
function Pin.reset ⇒
Call type:
function Pin.reset()Description
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 ⇒
Call type:
function Pin.set()Description
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 ⇒
Call type:
function Pin.toggle()Description
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"
function Pin.write ⇒
Call type:
function Pin.write(value)Description
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"
Parameters
value - Whether to set output high (true/1) or low (false/0)
function Pin.writeAtTime ⇒
Call type:
function Pin.writeAtTime(value, time)Description
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 only available in not devices with low flash memory
Parameters
value - Whether to set output high (true/1) or low (false/0)
time - Time at which to write
process Class
This class contains information about Espruino itself
Methods and Fields
process.env ⇒
Call type:
process.envDescription
Returns an Object containing various pre-defined variables. standard ones are BOARD, VERSION
Returns
An object
process.memory ⇒
Call type:
process.memory()Description
Run a Garbage Collection pass, and return an object containing information on memory usage.
free: Memory that is available to be used (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'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 (usually0x8000000)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 withsave().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()
Returns
Information about memory usage
Examples
This function is used in the following places in Espruino's documentation
event process.uncaughtException ⇒
Call type:
process.on('uncaughtException', function() { ... });Description
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.
process.version ⇒
Call type:
process.versionDescription
Returns the version of Espruino as a String
Returns
The version of Espruino
Promise Class
This is the built-in class for ES6 Promises
Methods and Fields
- Promise.all(promises)
- function Promise.catch(onRejected)
- constructor Promise(executor)
- Promise.reject(promises)
- Promise.resolve(promises)
- function Promise.then(onFulfilled, onRejected)
Promise.all ⇒
Call type:
Promise.all(promises)Description
Return a new promise that is resolved when all promises in the supplied array are resolved.
Note: This is only available in not devices with low flash memory
Parameters
promises - An array of promises
Returns
A new Promise
function Promise.catch ⇒
Call type:
function Promise.catch(onRejected)Parameters
onRejected - A callback that is called when this promise is rejected
Returns
The original Promise
constructor Promise ⇒
Call type:
new Promise(executor)Description
Create a new Promise. The executor function is executed immediately (before the constructor even returns) and
Note: This is only available in not devices with low flash memory
Parameters
executor - A function of the form function (resolve, reject)
Returns
A Promise
Promise.reject ⇒
Call type:
Promise.reject(promises)Description
Return a new promise that is already rejected (at idle it'll
call .catch)
Note: This is only available in not devices with low flash memory
Parameters
promises - Data to pass to the .catch handler
Returns
A new Promise
Promise.resolve ⇒
Call type:
Promise.resolve(promises)Description
Return a new promise that is already resolved (at idle it'll
call .then)
Note: This is only available in not devices with low flash memory
Parameters
promises - Data to pass to the .then handler
Returns
A new Promise
function Promise.then ⇒
Call type:
function Promise.then(onFulfilled, onRejected)Parameters
onFulfilled - A callback that is called when this promise is resolved
onRejected - A callback that is called when this promise is rejected (or nothing)
Returns
The original Promise
Puck Class
Class containing Puck.js's utility functions.
Methods and Fields
- Puck.capSense(tx, rx)
- Puck.getBatteryPercentage()
- Puck.IR(data, cathode, anode)
- Puck.light()
- Puck.mag()
- event Puck.mag()
- Puck.magOff()
- Puck.magOn(samplerate)
- Puck.selfTest()
Puck.capSense ⇒
Call type:
Puck.capSense(tx, rx)Description
Capacitive sense. TX must be connected to RX pin and sense plate via 1MOhm resistor.
If no pins are supplied, the NFC ring is used for capacitive sense.
Note: This is only available in NRF52 devices (like Puck.js)
Parameters
tx -
rx -
Returns
Capacitive sense counter
Puck.getBatteryPercentage ⇒
Call type:
Puck.getBatteryPercentage()Description
Return an approximate battery percentage remaining based on a normal CR2032 battery (2.8 - 2.2v)
Returns
A percentage between 0 and 100
Puck.IR ⇒
Call type:
Puck.IR(data, cathode, anode)Description
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)
Parameters
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
Examples
This function is used in the following places in Espruino's documentation
Puck.light ⇒
Call type:
Puck.light()Description
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)
Returns
A light value from 0 to 1
Puck.mag ⇒
Call type:
Puck.mag()Description
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.
Returns
An Object {x,y,z} of magnetometer readings as integers
Examples
This function is used in the following places in Espruino's documentation
event Puck.mag ⇒
Call type:
Puck.on('mag', function() { ... });Description
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()).
Examples
This function is used in the following places in Espruino's documentation
Puck.magOff ⇒
Call type:
Puck.magOff()Description
Turn the magnetometer off
Puck.magOn ⇒
Call type:
Puck.magOn(samplerate)Description
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):
- 80 Hz - 900uA
- 40 Hz - 550uA
- 20 Hz - 275uA
- 10 Hz - 137uA
- 5 Hz - 69uA
- 2.5 Hz - 34uA
- 1.25 Hz - 17uA
- 0.63 Hz - 8uA
- 0.31 Hz - 8uA
- 0.16 Hz - 8uA
- 0.08 Hz - 8uA
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.
Parameters
samplerate - The sample rate in Hz, or undefined
Puck.selfTest ⇒
Call type:
Puck.selfTest()Description
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.
Returns
True if the self-test passed
ReferenceError Class
The base class for reference errors - where a variable which doesn't exist has been accessed.
Methods and Fields
constructor ReferenceError ⇒
Call type:
new ReferenceError(message)Description
Creates a ReferenceError object
Parameters
message - An optional message string
Returns
A ReferenceError object
function ReferenceError.toString ⇒
Call type:
function ReferenceError.toString()Returns
A String
Serial Class
This class allows use of the built-in USARTs
Methods may be called on the USB, Serial1, Serial2, Serial3, Serial4, Serial5 and Serial6 objects. While different processors provide different numbers of USARTs, you can always rely on at least Serial1 and Serial2
Instances
BluetoothThe Bluetooth Serial port - used when data is sent or received over Bluetooth Smart on nRF51/nRF52 chips.LoopbackAA loopback serial device. Data sent to LoopbackA comes out of LoopbackB and vice versaLoopbackBA loopback serial device. Data sent to LoopbackA comes out of LoopbackB and vice versaSerial1The first Serial (USART) portSerial2The second Serial (USART) portSerial3The third Serial (USART) portSerial4The fourth Serial (USART) portSerial5The fifth Serial (USART) portSerial6The sixth Serial (USART) portTelnetA telnet serial device that maps to the built-in telnet console server (devices that have built-in wifi only).USBThe USB Serial port
Methods and Fields
- function Serial.available()
- event Serial.data(data)
- Serial.find(pin)
- event Serial.framing()
- function Serial.onData(function)
- event Serial.parity()
- function Serial.pipe(destination, options)
- function Serial.print(string)
- function Serial.println(string)
- function Serial.read(chars)
- function Serial.setConsole(force)
- function Serial.setup(baudrate, options)
- function Serial.write(data, ...)
function Serial.available ⇒
Call type:
function Serial.available()Description
Return how many bytes are available to read. If there is already a listener for data, this will always return 0.
Returns
How many bytes are available
event Serial.data ⇒
Call type:
Serial.on('data', function(data) { ... });Description
The data event is called when data is received. If a handler is defined with X.on('data', function(data) { ... }) then it will be called, otherwise data will be stored in an internal buffer, where it can be retrieved with X.read()
Parameters
data - A string containing one or more characters of received data
Serial.find ⇒
Call type:
Serial.find(pin)Description
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.
Parameters
pin - A pin to search with
Returns
An object of type Serial, or undefined if one couldn't be found.
event Serial.framing ⇒
Call type:
Serial.on('framing', function() { ... });Description
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.
Note: Even though there was an error, the byte will still be received and
passed to the data handler.
function Serial.onData ⇒
Call type:
function Serial.onData(function)Description
Serial.onData(func) has now been replaced with the event Serial.on(data, func)
Parameters
function -
event Serial.parity ⇒
Call type:
Serial.on('parity', function() { ... });Description
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.
Note: Even though there was an error, the byte will still be received and
passed to the data handler.
function Serial.pipe ⇒
Call type:
function Serial.pipe(destination, options)Description
Pipe this USART to a stream (an object with a 'write' method)
Note: This is only available in not devices with low flash memory
Parameters
destination - The destination file/stream that will receive content from the source.
options - An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished
function Serial.print ⇒
Call type:
function Serial.print(string)Description
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.
Parameters
string - A String to print
Examples
This function is used in the following places in Espruino's documentation
function Serial.println ⇒
Call type:
function Serial.println(string)Description
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, useSerial.write`.
Parameters
string - A String to print
Examples
This function is used in the following places in Espruino's documentation
function Serial.read ⇒
Call type:
function Serial.read(chars)Description
Return a string containing characters that have been received
Parameters
chars - The number of characters to read, or undefined/0 for all available
Returns
A string containing the required bytes.
function Serial.setConsole ⇒
Call type:
function Serial.setConsole(force)Description
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.
Parameters
force - Whether to force the console to this port
Examples
This function is used in the following places in Espruino's documentation
- ESP8266 WiFi Module
- Espruino Pico 'Shims'
- VT100 Terminal Emulator
- USART / UART / Serial Port
- Bluetooth Voice Controlled Robot
function Serial.setup ⇒
Call type:
function Serial.setup(baudrate, options)Description
Setup this Serial port with the given baud rate and options.
If not specified in options, the default pins are used (usually the lowest numbered pins on the lowest port that supports this peripheral)
Parameters
baudrate - The baud rate - the default is 9600
options - An optional structure containing extra information on initialising the serial port.{rx:pin,tx:pin,bytesize:8,parity:null/'none'/'o'/'odd'/'e'/'even',stopbits:1,flow:null/undefined/'none'/'xon',path:null/undefined/string}
You can find out which pins to use by looking at your board's reference page and searching for pins with the UART/USART markers.
Note that even after changing the RX and TX pins, if you have called setup before then the previous RX and TX pins will still be connected to the Serial port as well - until you set them to something else using digitalWrite
Examples
This function is used in the following places in Espruino's documentation
- Bluetooth
- ESP8266 WiFi Module
- EasyVR Voice Recognition Board
- GPS Module
- RN2483 LoRa Modules
- SIMCom SIM800/SIM900 GSM/GPRS Module
- SmartNixie Nixie Tube driver
- xBee radio module
- LPRS easyRadio (eRIC) Radio Modules
- Espruino Pico 'Shims'
- USART / UART / Serial Port
- Bluetooth Voice Controlled Robot
- Logging to Google Sheets
- Pico Weather Station
- Pocket 'walking' GPS
function Serial.write ⇒
Call type:
function Serial.write(data, ...)Description
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.
Parameters
data, ... - One or more items to write. May be ints, strings, arrays, or objects of the form {data: ..., count:#}.
Examples
This function is used in the following places in Espruino's documentation
Server Class
The socket server created by require('net').createServer
Methods and Fields
function Server.close ⇒
Call type:
function Server.close()Description
Stop listening for new connections
function Server.listen ⇒
Call type:
function Server.listen(port)Description
Start listening for new connections on the given port
Parameters
port - The port to listen on
Socket Class
An actual socket connection - allowing transmit/receive of TCP data
Methods and Fields
- function Socket.available()
- event Socket.close(had_error)
- event Socket.data(data)
- event Socket.drain()
- function Socket.end(data)
- event Socket.error(details)
- function Socket.pipe(destination, options)
- function Socket.read(chars)
- function Socket.write(data)
function Socket.available ⇒
Call type:
function Socket.available()Description
Return how many bytes are available to read. If there is already a listener for data, this will always return 0.
Returns
How many bytes are available
event Socket.close ⇒
Call type:
Socket.on('close', function(had_error) { ... });Description
Called when the connection closes.
Parameters
had_error - A boolean indicating whether the connection had an error (use an error event handler to get error details).
event Socket.data ⇒
Call type:
Socket.on('data', function(data) { ... });Description
The 'data' event is called when data is received. If a handler is defined with X.on('data', function(data) { ... }) then it will be called, otherwise data will be stored in an internal buffer, where it can be retrieved with X.read()
Parameters
data - A string containing one or more characters of received data
event Socket.drain ⇒
Call type:
Socket.on('drain', function() { ... });Description
An event that is fired when the buffer is empty and it can accept more data to send.
function Socket.end ⇒
Call type:
function Socket.end(data)Description
Close this socket - optional data to append as an argument
Parameters
data - A string containing data to send
event Socket.error ⇒
Call type:
Socket.on('error', function(details) { ... });Description
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:
- -1: socket closed (this is not really an error and will not cause an error callback)
- -2: out of memory (typically while allocating a buffer to hold data)
- -3: timeout
- -4: no route
- -5: busy
- -6: not found (DNS resolution)
- -7: max sockets (... exceeded)
- -8: unsent data (some data could not be sent)
- -9: connection reset (or refused)
- -10: unknown error
- -11: no connection
- -12: bad argument
- -13: SSL handshake failed
- -14: invalid SSL data
Parameters
details - An error object with an error code (a negative integer) and a message.
function Socket.pipe ⇒
Call type:
function Socket.pipe(destination, options)Description
Pipe this to a stream (an object with a 'write' method)
Note: This is only available in not devices with low flash memory
Parameters
destination - The destination file/stream that will receive content from the source.
options - An optional object { chunkSize : int=32, end : bool=true, complete : function }
chunkSize : The amount of data to pipe from source to destination at a time
complete : a function to call when the pipe activity is complete
end : call the 'end' function on the destination when the source is finished
function Socket.read ⇒
Call type:
function Socket.read(chars)Description
Return a string containing characters that have been received
Parameters
chars - The number of characters to read, or undefined/0 for all available
Returns
A string containing the required bytes.
function Socket.write ⇒
Call type:
function Socket.write(data)Parameters
data - A string containing data to send
Returns
For note compatibility, the boolean false. When the send buffer is empty, a drain event will be sent
SPI Class
This class allows use of the built-in SPI ports. Currently it is SPI master only.
Instances
Methods and Fields
- SPI.find(pin)
- function SPI.send(data, nss_pin)
- function SPI.send4bit(data, bit0, bit1, nss_pin)
- function SPI.send8bit(data, bit0, bit1, nss_pin)
- function SPI.setup(options)
- constructor SPI()
- function SPI.write(data, ...)
SPI.find ⇒
Call type:
SPI.find(pin)Description
Try and find an SPI hardware device that will work on this pin (eg. SPI1)
May return undefined if no device can be found.
Parameters
pin - A pin to search with
Returns
An object of type SPI, or undefined if one couldn't be found.
function SPI.send ⇒
Call type:
function SPI.send(data, nss_pin)Description
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]
Parameters
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.
Returns
The data that was returned
Examples
This function is used in the following places in Espruino's documentation
function SPI.send4bit ⇒
Call type:
function SPI.send4bit(data, bit0, bit1, nss_pin)Description
Send data down SPI, using 4 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols
Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.
Parameters
data - The data to send - either an integer, array, or string
bit0 - The 4 bits to send for a 0 (MSB first)
bit1 - The 4 bits to send for a 1 (MSB first)
nss_pin - An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised.
Examples
This function is used in the following places in Espruino's documentation
function SPI.send8bit ⇒
Call type:
function SPI.send8bit(data, bit0, bit1, nss_pin)Description
Send data down SPI, using 8 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols
Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.
Note: This is only available in not devices with low flash memory
Parameters
data - The data to send - either an integer, array, or string
bit0 - The 8 bits to send for a 0 (MSB first)
bit1 - The 8 bits to send for a 1 (MSB first)
nss_pin - An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised
function SPI.setup ⇒
Call type:
function SPI.setup(options)Description
Set up this SPI port as an SPI Master.
Parameters
options - An optional structure containing extra information on initialising the SPI port
Please note that baud rate is set to the nearest that can be managed - which may be -+ 50%{sck:pin, miso:pin, mosi:pin, baud:integer=100000, mode:integer=0, order:'msb'/'lsb'='msb' }
If sck,miso and mosi are left out, they will automatically be chosen. However if one or more is specified then the unspecified pins will not be set up.
You can find out which pins to use by looking at your board's reference page and searching for pins with the SPI marker.
The SPI mode is between 0 and 3 - see http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase
On STM32F1-based parts, you cannot mix AF and non-AF pins (SPI pins are usually grouped on the chip - and you can't mix pins from two groups). Espruino will not warn you about this.
Examples
This function is used in the following places in Espruino's documentation
- ADNS5050 Optical Mouse Sensor
- ADS7843 Touchscreen
- CC3000 WiFi Module
- Espruino Parallel to Serial Shifting-In with a CD4021BE
- ILI9163 LCD controller
- ILI9341 LCD controller
- MAX7219 7 segment display driver
- MCP23xxx I2C and SPI port expanders
- MFRC522 NFC/RFID module
- Sharp Memory LCD
- NRF24L01+ Wireless Module
- nRF905 Wireless Transceiver
- PCD8544 LCD driver (Nokia 5110)
- CMUcam5 Pixy
- HopeRF RFM69 Wireless Module
- RGB123 LED Matrices/Strips
- Espruino Pico Robot PCB
- SH1106 OLED driver
- SSD1306 OLED driver
- SSD1351 OLED display driver
- ST7565/ST7567 128x64 Monochrome LCD driver
- SX1276/77/78/79 LoRa Modules
- WIZnet WIZ550io/W5500 Ethernet module
- WS2811/WS2812 LED String/Strip
- Espruino Pico 'Shims'
- File IO and SD cards
- Digital Dice
- Ethernet Webcam Display
- Graphical Web Interface
- Individually Addressable LEDs
- Interactive Web-based UI
- Motion Sensing Lights
- Soldering an LCD directly to Espruino
- Pico LCD Display Hello World
- Pocket 'walking' GPS
- Slot Machine
- Snake Game
- Wireless Temperature Sensor
- Word Clock
- LED Volume (VU) Meter
- Reaction Timer using RGB123
- Image Slideshow with ILI9341 display
- Temperature on a PCD8544 display, with DS18B20 temperature sensor
- Temperature Graph on a PCD8544 display, with DS18B20 temperature sensor
- WiFi Xively Humidity/Temperature Sensor with Display
- LED Clock (using WS8111)
constructor SPI ⇒
Call type:
new SPI()Description
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 ⇒
Call type:
function SPI.write(data, ...)Description
Write a character or array of characters to SPI - without reading the result back.
For maximum speeds, please pass either Strings or Typed Arrays as arguments.
Parameters
data, ... - One or more items to write. May be ints, strings, arrays, or objects of the form {data: ..., count:#}.
If the last argument is a pin, it is taken to be the NSS pin
String Class
This is the built-in class for Text Strings.
Text Strings in Espruino are not zero-terminated, so you can store zeros in them.
Methods and Fields
- function String.charAt(pos)
- function String.charCodeAt(pos)
- String.fromCharCode(code, ...)
- function String.indexOf(substring, fromIndex)
- function String.lastIndexOf(substring, fromIndex)
- property String.length
- function String.replace(subStr, newSubStr)
- function String.slice(start, end)
- function String.split(separator)
- constructor String(str, ...)
- function String.substr(start, len)
- function String.substring(start, end)
- function String.toLowerCase()
- function String.toUpperCase()
- function String.trim()
function String.charAt ⇒
Call type:
function String.charAt(pos)Description
Return a single character at the given position in the String.
Parameters
pos - The character number in the string. Negative values return characters from end of string (-1 = last char)
Returns
The character in the string
function String.charCodeAt ⇒
Call type:
function String.charCodeAt(pos)Description
Return the integer value of a single character at the given position in the String.
Note that this returns 0 not 'NaN' for out of bounds characters
Parameters
pos - The character number in the string. Negative values return characters from end of string (-1 = last char)
Returns
The integer value of a character in the string
String.fromCharCode ⇒
Call type:
String.fromCharCode(code, ...)Description
Return the character(s) represented by the given character code(s).
Parameters
code, ... - One or more character codes to create a string from (range 0-255).
Returns
The character
Examples
This function is used in the following places in Espruino's documentation
function String.indexOf ⇒
Call type:
function String.indexOf(substring, fromIndex)Description
Return the index of substring in this string, or -1 if not found
Parameters
substring - The string to search for
fromIndex - Index to search from
Returns
The index of the string, or -1 if not found
Examples
This function is used in the following places in Espruino's documentation
function String.lastIndexOf ⇒
Call type:
function String.lastIndexOf(substring, fromIndex)Description
Return the last index of substring in this string, or -1 if not found
Parameters
substring - The string to search for
fromIndex - Index to search from
Returns
The index of the string, or -1 if not found
property String.length ⇒
Call type:
property String.lengthDescription
Find the length of the string
Returns
The value of the string
function String.replace ⇒
Call type:
function String.replace(subStr, newSubStr)Description
Search and replace ONE occurrance of subStr with newSubStr and return the result. This doesn't alter the original string. Regular expressions not supported.
Parameters
subStr - The string to search for
newSubStr - The string to replace it with
Returns
This string with subStr replaced
function String.slice ⇒
Call type:
function String.slice(start, end)Parameters
start - The start character index, if negative it is from the end of the string
end - The end character index, if negative it is from the end of the string, and if omitted it is the end of the string
Returns
Part of this string from start for len characters
function String.split ⇒
Call type:
function String.split(separator)Description
Return an array made by splitting this string up by the separator. eg. '1,2,3'.split(',')==[1,2,3]
Parameters
separator - The start character index
Returns
Part of this string from start for len characters
constructor String ⇒
Call type:
new String(str, ...)Description
Create a new String
Parameters
str, ... - A value to turn into a string. If undefined or not supplied, an empty String is created.
Returns
A String
function String.substr ⇒
Call type:
function String.substr(start, len)Parameters
start - The start character index
len - The number of characters
Returns
Part of this string from start for len characters
function String.substring ⇒
Call type:
function String.substring(start, end)Parameters
start - The start character index
end - The end character index
Returns
The part of this string between start and end
function String.toLowerCase ⇒
Call type:
function String.toLowerCase()Parameters
Returns
The lowercase version of this string
function String.toUpperCase ⇒
Call type:
function String.toUpperCase()Parameters
Returns
The uppercase version of this string
function String.trim ⇒
Call type:
function String.trim()Description
Return a new string with any whitespace (tabs, space, form feed, newline, carriage return, etc) removed from the beginning and end.
Returns
A String with Whitespace removed from the beginning and end
SyntaxError Class
The base class for syntax errors
Methods and Fields
constructor SyntaxError ⇒
Call type:
new SyntaxError(message)Description
Creates a SyntaxError object
Parameters
message - An optional message string
Returns
A SyntaxError object
function SyntaxError.toString ⇒
Call type:
function SyntaxError.toString()Returns
A String
TelnetServer Library
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
Methods and Fields
TelnetServer.setOptions ⇒
Call type:
TelnetServer.setOptions(options)Parameters
options - Options controlling the telnet console server
tls Library
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.
Methods and Fields
tls.connect ⇒
Call type:
tls.connect(options, callback)Description
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)
Parameters
options - An object containing host,port fields
callback - A function(res) that will be called when a connection is made. You can then call res.on('data', function(data) { ... }) and res.on('close', function() { ... }) to deal with the response.
Returns
Returns a new net.Socket object
tv Library
This library provides TV out capability on the Espruino and Espruino Pico.
See the Television page for more information.
Methods and Fields
tv.setup ⇒
Call type:
tv.setup(options, width)Description
This initialises the TV output. Options for PAL are as follows:
var g = require('tv').setup({ type : "pal",
video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
sync : A6, // Pin - Timer pin to use for video sync
width : 384,
height : 270, // max 270
});
and for VGA:
var g = require('tv').setup({ type : "vga",
video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
hsync : A6, // Pin - Timer pin to use for video sync
vsync : A5, // Pin - pin to use for video sync
width : 220,
height : 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.
Parameters
options - Various options for the TV output
width -
Returns
A graphics object
TypeError Class
The base class for type errors
Methods and Fields
function TypeError.toString ⇒
Call type:
function TypeError.toString()Returns
A String
constructor TypeError ⇒
Call type:
new TypeError(message)Description
Creates a TypeError object
Parameters
message - An optional message string
Returns
A TypeError object
Uint16Array Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Uint16Array ⇒
Call type:
new Uint16Array(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
Uint32Array Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Uint32Array ⇒
Call type:
new Uint32Array(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
Uint8Array Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Uint8Array ⇒
Call type:
new Uint8Array(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
Examples
This function is used in the following places in Espruino's documentation
Uint8ClampedArray Class
This is the built-in JavaScript class for a typed array.
Instantiate this in order to efficiently store arrays of data (Espruino's normal arrays store data in a map, which is inefficient for non-sparse arrays).
Methods and Fields
constructor Uint8ClampedArray ⇒
Call type:
new Uint8ClampedArray(arr, byteOffset, length)Description
Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an ArrayBuffer view (eg. Uint8Array rather than ArrayBuffer) is given, it will be completely copied rather than referenced.
Clamped arrays clamp their values to the allowed range, rather than 'wrapping'. e.g. after a[0]=12345;, a[0]==255.
Parameters
arr - The array or typed array to base this off, or an integer which is the array length
byteOffset - The byte offset in the ArrayBuffer (ONLY IF the first argument was an ArrayBuffer)
length - The length (ONLY IF the first argument was an ArrayBuffer)
Returns
A typed array
url Class
This class helps to convert URLs into Objects of information ready for http.request/get
Methods and Fields
url.parse ⇒
Call type:
url.parse(urlStr, parseQuery)Description
A utility function to split a URL into parts
This is useful in web servers for instance when handling a request.
For instance url.parse("/a?b=c&d=e",true) returns {"method":"GET","host":"","path":"/a?b=c&d=e","pathname":"/a","search":"?b=c&d=e","port":80,"query":{"b":"c","d":"e"}}
Parameters
urlStr - A URL to be parsed
parseQuery - Whether to parse the query string into an object not (default = false)
Returns
An object containing options for http.request or http.get. Contains method, host, path, pathname, search, port and query
Examples
This function is used in the following places in Espruino's documentation
- CC3000 WiFi Module
- Wifi Remote Console
- Internet (HTTP)
- Ethernet Webcam Display
- Graphical Web Interface
- Interactive Web-based UI
- HTTP File Server
Waveform Class
This class handles waveforms. In Espruino, a Waveform is a set of data that you want to input or output.
Methods and Fields
- function Waveform.startInput(output, freq, options)
- function Waveform.startOutput(output, freq, options)
- function Waveform.stop()
- constructor Waveform(samples, options)
function Waveform.startInput ⇒
Call type:
function Waveform.startInput(output, freq, options)Description
Will start inputting the waveform on the given pin that supports analog. If not repeating, it'll emit a finish event when it is done.
Note: This is only available in not devices with low flash memory
Parameters
output - The pin to output on
freq - The frequency to output each sample at
options - Optional options struct {time:float,repeat:bool} where: time is the that the waveform with start output at, e.g. getTime()+1 (otherwise it is immediate), repeat is a boolean specifying whether to repeat the give sample
function Waveform.startOutput ⇒
Call type:
function Waveform.startOutput(output, freq, options)Description
Will start outputting the waveform on the given pin - the pin must have previously been initialised with analogWrite. If not repeating, it'll emit a finish event when it is done.
Note: This is only available in not devices with low flash memory
Parameters
output - The pin to output on
freq - The frequency to output each sample at
options - Optional options struct {time:float,repeat:bool} where: time is the that the waveform with start output at, e.g. getTime()+1 (otherwise it is immediate), repeat is a boolean specifying whether to repeat the give sample
function Waveform.stop ⇒
Call type:
function Waveform.stop()Description
Stop a waveform that is currently outputting
Note: This is only available in not devices with low flash memory
constructor Waveform ⇒
Call type:
new Waveform(samples, options)Description
Create a waveform class. This allows high speed input and output of waveforms. It has an internal variable called buffer (as well as buffer2 when double-buffered - see options below) which contains the data to input/output.
When double-buffered, a 'buffer' event will be emitted each time a buffer is finished with (the argument is that buffer). When the recording stops, a 'finish' event will be emitted (with the first argument as the buffer).
Note: This is only available in not devices with low flash memory
Parameters
samples - The number of samples
options - Optional options struct {doubleBuffer:bool, bits : 8/16} where: doubleBuffer is whether to allocate two buffers or not (default false), and bits is the amount of bits to use (default 8).
Returns
An Waveform object
Wifi Library
The wifi library is a generic cross-platform library to control the Wifi interface. It supports functionality such as connecting to wifi networks, getting network information, starting and access point, etc. Currently this library is ESP8266 specific and needs to be ported to other Espruino platforms.
To get started and connect to your local access point all you need is
var wifi = require("Wifi");
wifi.connect("my-ssid", {password:"my-pwd"}, function(ap){ console.log("connected:", ap); });
If you want the connection to happen automatically at boot, add wifi.save();.
Methods and Fields
- event Wifi.associated(details)
- event Wifi.auth_change(details)
- Wifi.connect(ssid, options, callback)
- event Wifi.connected(details)
- event Wifi.dhcp_timeout()
- Wifi.disconnect(callback)
- event Wifi.disconnected(details)
- Wifi.getAPDetails(callback)
- Wifi.getAPIP(callback)
- Wifi.getDetails(callback)
- Wifi.getDHCPHostname(callback)
- Wifi.getHostByName(hostname, callback)
- Wifi.getHostname(callback)
- Wifi.getIP(callback)
- Wifi.getStatus(callback)
- event Wifi.probe_recv(details)
- Wifi.restore()
- Wifi.save(what)
- Wifi.scan(callback)
- Wifi.setAPIP(settings, callback)
- Wifi.setConfig(settings)
- Wifi.setDHCPHostname(hostname)
- Wifi.setHostname(hostname)
- Wifi.setIP(settings, callback)
- Wifi.setSNTP(server, tz_offset)
- event Wifi.sta_joined(details)
- event Wifi.sta_left(details)
- Wifi.startAP(ssid, options, callback)
- Wifi.stopAP(callback)
event Wifi.associated ⇒
Call type:
Wifi.on('associated', function(details) { ... });Description
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. The details include:
- ssid - The SSID of the access point to which the association was established
- mac - The BSSID/mac address of the access point
- channel - The wifi channel used (an integer, typ 1..14)
Parameters
details - An object with event details
event Wifi.auth_change ⇒
Call type:
Wifi.on('auth_change', function(details) { ... });Description
The 'auth_change' event is called when the authentication mode with the associated access point changes. The details include:
- oldMode - The old auth mode (string: open, wep, wpa, wpa2, wpa_wpa2)
- newMode - The new auth mode (string: open, wep, wpa, wpa2, wpa_wpa2)
Parameters
details - An object with event details
Wifi.connect ⇒
Call type:
Wifi.connect(ssid, options, callback)Description
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:
- the options should include the ability to set a static IP and associated netmask and gateway, this is a future enhancement.
- the only error reported in the callback is "Bad password", all other errors (such as access point not found or DHCP timeout) just cause connection retries. If the reporting of such temporary errors is desired, the caller must use its own timeout and the
getDetails().statusfield. - the
connectcall automatically enabled station mode, it can be disabled again by callingdisconnect.
Parameters
ssid - The access point network id.
options - Connection options (optional).
callback - A function to be called back on completion (optional).
event Wifi.connected ⇒
Call type:
Wifi.on('connected', function(details) { ... });Description
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). The details include:
- ip - The IP address obtained as string
- netmask - The network's IP range mask as string
- gw - The network's default gateway as string
Parameters
details - An object with event details
event Wifi.dhcp_timeout ⇒
Call type:
Wifi.on('dhcp_timeout', function() { ... });Description
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).
Wifi.disconnect ⇒
Call type:
Wifi.disconnect(callback)Description
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.
Parameters
callback - An optional function to be called back on disconnection. The callback function receives no argument.
event Wifi.disconnected ⇒
Call type:
Wifi.on('disconnected', function(details) { ... });Description
The 'disconnected' event is called when an association with an access point has been lost. The details include:
- ssid - The SSID of the access point from which the association was lost
- mac - The BSSID/mac address of the access point
- reason - The reason for the disconnection (string)
Parameters
details - An object with event details
Wifi.getAPDetails ⇒
Call type:
Wifi.getAPDetails(callback)Description
Retrieve the current access point configuration and status. The details object has the following properties:
status- Current access point status:enabledordisabledstations- 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 containsipbeing 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.
Parameters
callback - An optional function to be called back with the current access point details, i.e. the same object as returned directly. The callback function is more portable than the direct return value.
Returns
An object representing the current access point details, if available immediately.
Wifi.getAPIP ⇒
Call type:
Wifi.getAPIP(callback)Description
Return the access point IP information in an object which contains:
- ip - IP address as string (typ "192.168.4.1")
- netmask - The interface netmask as string
- gw - The network gateway as string
- mac - The MAC address as string of the form 00:00:00:00:00:00
Parameters
callback - An optional function to be called back with the the IP information, i.e. the same object as returned directly. The callback function is more portable than the direct return value.
Returns
An object representing the esp8266's Access Point IP information, if available immediately.
Wifi.getDetails ⇒
Call type:
Wifi.getDetails(callback)Description
Retrieve the wifi station configuration and status details. The details object has the following properties:
status- Details about the wifi station connection, one ofoff,connecting,wrong_password,no_ap_found,connect_fail, orconnected. 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.
Parameters
callback - An optional function to be called back with the wifi details, i.e. the same object as returned directly. The callback function is more portable than the direct return value.
Returns
An object representing the wifi station details, if available immediately.
Wifi.getDHCPHostname ⇒
Call type:
Wifi.getDHCPHostname(callback)Description
Deprecated, please use getHostname.
Parameters
callback - An optional function to be called back with the hostname, i.e. the same string as returned directly. The callback function is more portable than the direct return value.
Returns
The currently configured DHCP hostname, if available immediately.
Wifi.getHostByName ⇒
Call type:
Wifi.getHostByName(hostname, callback)Description
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.
Parameters
hostname - The hostname to lookup.
callback - The callback to invoke when the hostname is returned.
Wifi.getHostname ⇒
Call type:
Wifi.getHostname(callback)Description
Returns the hostname announced to the DHCP server and broadcast via mDNS when connecting to an access point.
Parameters
callback - An optional function to be called back with the hostname, i.e. the same string as returned directly. The callback function is more portable than the direct return value.
Returns
The currently configured hostname, if available immediately.
Wifi.getIP ⇒
Call type:
Wifi.getIP(callback)Description
Return the station IP information in an object as follows:
- ip - IP address as string (e.g. "192.168.1.5")
- netmask - The interface netmask as string
- gw - The network gateway as string
- mac - The MAC address as string of the form 00:00:00:00:00:00
Note that the ip, netmask, and gw fields are omitted if no connection is established:
Parameters
callback - An optional function to be called back with the IP information, i.e. the same object as returned directly. The callback function is more portable than the direct return value.
Returns
An object representing the station IP information, if available immediately.
Wifi.getStatus ⇒
Call type:
Wifi.getStatus(callback)Description
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.
Parameters
callback - An optional function to be called back with the current Wifi status, i.e. the same object as returned directly. The callback function is more portable than the direct return value.
Returns
An object representing the current WiFi status, if available immediately.
event Wifi.probe_recv ⇒
Call type:
Wifi.on('probe_recv', function(details) { ... });Description
The 'probe_recv' event is called when a probe request is received from some station by the esp8266's access point. The details include:
- mac - The MAC address of the station in string format (00:00:00:00:00:00)
- rssi - The signal strength in dB of the probe request
Parameters
details - An object with event details
Wifi.restore ⇒
Call type:
Wifi.restore()Description
Restores the saved Wifi configuration from flash. See Wifi.save().
Wifi.save ⇒
Call type:
Wifi.save(what)Description
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:
- mode (off/sta/ap/sta+ap)
- SSIDs & passwords
- phy (11b/g/n)
- powersave setting
- DHCP hostname
Parameters
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 ⇒
Call type:
Wifi.scan(callback)Description
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, orwpa_wpa2.channel: wifi channel 1..13.hidden: true if the SSID is hidden.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.
Parameters
callback - A function to be called back on completion.
Wifi.setAPIP ⇒
Call type:
Wifi.setAPIP(settings, callback)Description
The settings object must contain the following properties.
ipIP address as string (e.g. "192.168.5.100")gwThe network gateway as string (e.g. "192.168.5.1")netmaskThe interface netmask as string (e.g. "255.255.255.0")
Parameters
settings - Configuration settings
callback - The callback to invoke when ip is set
Wifi.setConfig ⇒
Call type:
Wifi.setConfig(settings)Description
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.
Parameters
settings - An object with the configuration settings to change.
Wifi.setDHCPHostname ⇒
Call type:
Wifi.setDHCPHostname(hostname)Description
Deprecated, please use setHostname instead.
Parameters
hostname - The new DHCP hostname.
Wifi.setHostname ⇒
Call type:
Wifi.setHostname(hostname)Description
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.
Parameters
hostname - The new hostname.
Wifi.setIP ⇒
Call type:
Wifi.setIP(settings, callback)Description
The settings object must contain the following properties.
ipIP address as string (e.g. "192.168.5.100")gwThe network gateway as string (e.g. "192.168.5.1")netmaskThe interface netmask as string (e.g. "255.255.255.0")
Parameters
settings - Configuration settings
callback - The callback to invoke when ip is set
Wifi.setSNTP ⇒
Call type:
Wifi.setSNTP(server, tz_offset)Description
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.
Parameters
server - The NTP server to query, for example, us.pool.ntp.org
tz_offset - Local time zone offset in the range -11..13.
event Wifi.sta_joined ⇒
Call type:
Wifi.on('sta_joined', function(details) { ... });Description
The 'sta_joined' event is called when a station establishes an association (i.e. connects) with the esp8266's access point. The details include:
- mac - The MAC address of the station in string format (00:00:00:00:00:00)
Parameters
details - An object with event details
event Wifi.sta_left ⇒
Call type:
Wifi.on('sta_left', function(details) { ... });Description
The 'sta_left' event is called when a station disconnects from the esp8266's access point (or its association times out?). The details include:
- mac - The MAC address of the station in string format (00:00:00:00:00:00)
Parameters
details - An object with event details
Wifi.startAP ⇒
Call type:
Wifi.startAP(ssid, options, callback)Description
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.
Notes:
- the options should include the ability to set the AP IP and associated netmask, this is a future enhancement.
- the
startAPcall automatically enables AP mode. It can be disabled again by callingstopAP.
Parameters
ssid - The network id.
options - Configuration options (optional).
callback - Optional function to be called when the AP is successfully started.
Wifi.stopAP ⇒
Call type:
Wifi.stopAP(callback)Description
Stop being an access point and disable the AP operation mode. Ap mode can be re-enabled by calling startAP.
Parameters
callback - An optional function to be called back on successful stop. The callback function receives no argument.
WIZnet Library
Library for communication with the WIZnet Ethernet module
Methods and Fields
WIZnet.connect ⇒
Call type:
WIZnet.connect(spi, cs)Description
Initialise the WIZnet module and return an Ethernet object
Parameters
spi - Device to use for SPI (or undefined to use the default)
cs - The pin to use for Chip Select
Returns
An Ethernet Object
Examples
This function is used in the following places in Espruino's documentation
WLAN Class
An instantiation of a WiFi network adaptor
Methods and Fields
- function WLAN.connect(ap, key, callback)
- function WLAN.disconnect()
- function WLAN.getIP()
- function WLAN.reconnect()
- function WLAN.setIP(options)
function WLAN.connect ⇒
Call type:
function WLAN.connect(ap, key, callback)Description
Connect to a wireless network
Parameters
ap - Access point name
key - WPA2 key (or undefined for unsecured connection)
callback - Function to call back with connection status. It has one argument which is one of 'connect'/'disconnect'/'dhcp'
Returns
True if connection succeeded, false if it didn't.
function WLAN.disconnect ⇒
Call type:
function WLAN.disconnect()Description
Completely uninitialise and power down the CC3000. After this you'll have to use require("CC3000").connect() again.
function WLAN.getIP ⇒
Call type:
function WLAN.getIP()Description
Get the current IP address
Returns
See description above
function WLAN.reconnect ⇒
Call type:
function WLAN.reconnect()Description
Completely uninitialise and power down the CC3000, then reconnect to the old access point.
function WLAN.setIP ⇒
Call type:
function WLAN.setIP(options)Description
Set the current IP address for get an IP from DHCP (if no options object is specified).
Note: Changes are written to non-volatile memory, but will only take effect after calling wlan.reconnect()
Parameters
options - Object containing IP address options { ip : '1,2,3,4', subnet, gateway, dns }, or do not supply an object in otder to force DHCP.
Returns
True on success




