### Load Waveform from Storage Example Source: https://www.espruino.com/Reference/ESPRUINOBOARD Example showing how to load waveform data from storage (e.g., a .pcm file) and output it. It reads the file into an ArrayBuffer, creates a Waveform object from it, and starts playback on a specified pin. Includes an event listener for the 'finish' event. ```javascript // On 2v25, from Storage var f = require("Storage").read("sound.pcm"); var w = new Waveform(E.toArrayBuffer(f)); w.on("finish", () => print("Done!")) w.startOutput(H0,8000); // start playback ``` -------------------------------- ### Espruino: Handle Initialization Event Source: https://www.espruino.com/Reference/ESPRUINOBOARD Registers a function to be called immediately after the Espruino board starts up. Subsequent calls add new handlers, allowing for modular code. This is similar to an `onInit` function but supports multiple handlers. Example provided shows logging 'Hello World!' on startup. ```javascript E.on('init', function() { console.log("Hello World!"); }); ``` -------------------------------- ### String.prototype.startsWith Example Source: https://www.espruino.com/Reference/PICO_R1_3 Shows how to check if a string begins with a specific set of characters. An optional position can be provided to start the search from. ```javascript let text = "Espruino is great!"; console.log(text.startsWith("Espruino")); // Output: true console.log(text.startsWith("is", 9)); // Output: true (starts checking from index 9) ``` -------------------------------- ### Output Sine Wave Example Source: https://www.espruino.com/Reference/ESPRUINOBOARD Example demonstrating how to output a sine wave using the Waveform class. It initializes a Waveform object, fills its buffer with sine wave data, sets up an analog output pin, and starts the waveform playback. It also includes an event listener for the 'finish' event. ```javascript // Output a sine wave var w = new Waveform(1000); for (var i=0;i<1000;i++) w.buffer[i]=128+120*Math.sin(i/2); analogWrite(H0, 0.5, {freq:80000}); // set up H0 to output an analog value by PWM w.on("finish", () => print("Done!")) w.startOutput(H0,8000); // start playback ``` -------------------------------- ### Full Espruino Device Interaction: LED Control (Standard) Source: https://www.espruino.com/Reference/PUCKJS This is a comprehensive example of interacting with an Espruino Bluetooth device. It requests a device by name prefix, connects to its GATT server, gets a specific primary service and characteristic, writes a command to turn on an LED, and then disconnects. It highlights the asynchronous nature of these operations using promises. ```javascript var gatt; NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) { return device.gatt.connect(); }).then(function(g) { gatt = g; return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); }).then(function(service) { return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); }).then(function(characteristic) { return characteristic.writeValue("LED1.set()\n"); }).then(function() { gatt.disconnect(); console.log("Done!"); }); ``` -------------------------------- ### SPI Constructor and Setup Source: https://www.espruino.com/Reference/PUCKJS Initializes a software SPI port and configures its parameters. ```APIDOC ## SPI Constructor ### Description Creates 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. ### Method `new SPI()` ### Returns A SPI object ## SPI Setup ### Description Sets up this SPI port as an SPI Master. Options can contain the following (defaults are shown where relevant): ### Method `SPI.setup(options)` ### Parameters #### Path Parameters - **options** (Object) - Required - An Object containing extra information on initialising the SPI port. ### Request Body ```json { "sck": "pin", "miso": "pin", "mosi": "pin", "baud": "integer" = 100000, "mode": "integer" = 0, "order": "string" = 'msb', "bits": "integer" = 8 } ``` ### Request Example ```json { "sck": A0, "miso": A1, "mosi": A2, "baud": 200000, "mode": 3, "order": "lsb", "bits": 16 } ``` ### Response #### Success Response (200) - **None** - This function configures the SPI port and does not return a value. ``` -------------------------------- ### Serial Setup with Error Handling Source: https://www.espruino.com/Reference/ESPRUINOWIFI Example of setting up a Serial port with error event listeners enabled. The 'errors:true' option in the setup configuration allows the 'framing' and 'parity' events to be triggered. This feature is supported on STM32 and NRF52 based devices. ```javascript SerialX.setup(..., { ..., errors:true }); ``` -------------------------------- ### Espruino Waveform Output Example Source: https://www.espruino.com/Reference/ESPRUINOWIFI Demonstrates how to create and output a sine wave using the Espruino Waveform class. It involves initializing an analog pin, generating waveform data, and starting playback. This functionality requires devices with sufficient flash memory. ```javascript var w = new Waveform(1000); for (var i=0;i<1000;i++) w.buffer[i]=128+120*Math.sin(i/2); analogWrite(H0, 0.5, {freq:80000}); // set up H0 to output an analog value by PWM w.on("finish", () => print("Done!")) w.startOutput(H0,8000); // start playback ``` -------------------------------- ### String.prototype.toLowerCase and String.prototype.toUpperCase Examples Source: https://www.espruino.com/Reference/PICO_R1_3 Provides examples of converting a string to its lowercase and uppercase equivalents. ```javascript let mixedCase = "JavaScript is Fun"; console.log(mixedCase.toLowerCase()); // Output: "javascript is fun" console.log(mixedCase.toUpperCase()); // Output: "JAVASCRIPT IS FUN" ``` -------------------------------- ### SPI Class and Methods Source: https://www.espruino.com/Reference/ESPRUINOWIFI Documentation for the SPI class, including setup, data transmission methods, and finding SPI devices. ```APIDOC ## SPI Class ### Description This class allows use of the built-in SPI ports. Currently it is SPI master only. #### Instances * `SPI1` - The first SPI port * `SPI2` - The second SPI port * `SPI3` - The third SPI port ## Function SPI.find ### Description **DEPRECATED** - this will be removed in subsequent versions of Espruino. Try and find an SPI hardware device that will work on this pin. ### Method `SPI.find(pin)` ### Parameters * `pin` (pin) - A pin to search with. ### Returns * (object) - An object of type `SPI`, or `undefined` if one couldn't be found. ## Function SPI.send ### Description Sends data over the SPI interface. ### Method `function SPI.send(data, nss_pin)` ### Parameters * `data` (buffer or array) - The data to send. * `nss_pin` (pin) - The chip select (NSS) pin. ## Function SPI.send4bit ### Description Sends 4 bits of data at a time over the SPI interface. ### Method `function SPI.send4bit(data, bit0, bit1, nss_pin)` ### Parameters * `data` (buffer or array) - The data to send. * `bit0` (integer) - The value of the first bit. * `bit1` (integer) - The value of the second bit. * `nss_pin` (pin) - The chip select (NSS) pin. ## Function SPI.send8bit ### Description Sends 8 bits of data at a time over the SPI interface. ### Method `function SPI.send8bit(data, bit0, bit1, nss_pin)` ### Parameters * `data` (buffer or array) - The data to send. * `bit0` (integer) - The value of the first bit. * `bit1` (integer) - The value of the second bit. * `nss_pin` (pin) - The chip select (NSS) pin. ## Function SPI.setup ### Description Configures the SPI interface. ### Method `function SPI.setup(options)` ### Parameters * `options` (object) - An object with configuration options (e.g., `mode`, `hz`, `mosi`, `miso`, `sck`). ## Constructor SPI ### Description Creates a new SPI instance. ### Method `new SPI()` ## Function SPI.write ### Description Writes data to the SPI interface. This is an alias for `SPI.send`. ### Method `function SPI.write(data, ...)` ### Parameters * `data` (buffer or array) - The data to write. * `...` - Additional arguments, typically NSS pin. ``` -------------------------------- ### Start Waveform Input Source: https://www.espruino.com/Reference/ESPRUINOBOARD Starts inputting a waveform on a specified analog-capable pin. If not repeating, a 'finish' event is emitted upon completion. Requires devices with sufficient flash memory. ```javascript Waveform.startInput(output, freq, options) ``` -------------------------------- ### Setup Serial Port with Baud Rate and Options Source: https://www.espruino.com/Reference/PICO_R1_3 Configures a serial port with a specified baud rate and various options like pins, data bits, parity, stop bits, and flow control. On Linux, a device path must be specified. Software serial setup is also supported but with fewer options. ```javascript Serial1.setup(9600,{rx:a_pin, tx:a_pin}); ``` ```javascript var s = new Serial(); s.setup(9600,{rx:a_pin, tx:a_pin}); ``` ```javascript Serial1.setup(9600,{path:"/dev/ttyACM0"}); ``` -------------------------------- ### Event: E.on('init') Source: https://www.espruino.com/Reference/PUCKJS Executes a callback function immediately after the Espruino board starts up. This is useful for setting up initial configurations or running startup routines. ```APIDOC ## Event: E.on('init') ### 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: ```javascript 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`. ### Call type: `E.on('init', function() { ... });` ``` -------------------------------- ### Waveform.startInput Source: https://www.espruino.com/Reference/PUCKJS Starts inputting waveform data on a specified pin. Supports options for timing and repetition. ```APIDOC ## `Waveform.startInput(output, freq, options)` ### Description Initiates the inputting of waveform data on a pin that supports analog input. If the waveform is not set to repeat, a 'finish' event will be emitted upon completion. ### Method `Function` ### Endpoint N/A (Class method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **output** (Pin) - The pin on which to start inputting the waveform. * **freq** (number) - The frequency at which to sample the waveform. * **options** (object) - [Optional] An object containing: * **time** (number) - The time (in seconds from `getTime()`) at which to start inputting the waveform. Defaults to immediate. * **repeat** (boolean) - If `true`, the waveform will repeat. Defaults to `false`. ### Request Example ```json { "example": "Waveform.startInput(A0, 1000, {time: getTime() + 0.5, repeat: true})" } ``` ### Response #### Success Response (200) * **None** #### Response Example ```json { "example": "N/A" } ``` ``` -------------------------------- ### RegExp.exec() Example in JavaScript Source: https://www.espruino.com/Reference/PICO_R1_3 Example of using the RegExp.exec() method to find matches within a string and return detailed result arrays, including captured groups. Note: Not available on devices with low flash memory. ```javascript /Wo/.exec("Hello World") // Example with groups: /W(o)rld/.exec("Hello World") ``` -------------------------------- ### SyntaxError Constructor Example Source: https://www.espruino.com/Reference/PICO_R1_3 Demonstrates how to create a new SyntaxError object, optionally with a message string. ```javascript try { // Some code that might cause a syntax error throw new SyntaxError("Invalid syntax encountered"); } catch (e) { console.error(e.toString()); // Output: "SyntaxError: Invalid syntax encountered" ``` -------------------------------- ### Waveform.startOutput Source: https://www.espruino.com/Reference/PUCKJS Starts outputting waveform data on a specified pin. Allows configuration of frequency, timing, repetition, and an optional notification pin. ```APIDOC ## `Waveform.startOutput(output, freq, options)` ### Description Starts outputting waveform data on the specified pin. This method allows for precise control over the output frequency and timing. ### Method `Function` ### Endpoint N/A (Class method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **output** (Pin) - The pin on which to start outputting the waveform. * **freq** (number) - The frequency at which to output each sample of the waveform. * **options** (object) - [Optional] An object containing: * **time** (number) - The time (in seconds from `getTime()`) at which to start outputting the waveform. Defaults to immediate. * **repeat** (boolean) - If `true`, the waveform will repeat. Defaults to `false`. * **npin** (Pin) - [Optional] A pin to notify when the waveform finishes outputting. ### Request Example ```json { "example": "Waveform.startOutput(D5, 50, {time: getTime() + 1, repeat: false, npin: D6})" } ``` ### Response #### Success Response (200) * **None** #### Response Example ```json { "example": "N/A" } ``` ``` -------------------------------- ### Start Waveform Output Source: https://www.espruino.com/Reference/ESPRUINOBOARD Starts outputting a waveform on a specified pin, which must be initialized with analogWrite. If not repeating, a 'finish' event is emitted upon completion. Supports splitting output across two pins using the `npin` option to avoid DC bias. Requires devices with sufficient flash memory. ```javascript Waveform.startOutput(output, freq, options) ``` -------------------------------- ### String Constructor Example Source: https://www.espruino.com/Reference/PICO_R1_3 Demonstrates the creation of new String objects in JavaScript. An empty string is created if no value is provided. ```javascript let str1 = new String("Hello"); let str2 = new String(); // Creates an empty string console.log(str1.toString()); // Output: "Hello" console.log(str2.toString()); // Output: "" ``` -------------------------------- ### HTTP Server Control Source: https://www.espruino.com/Reference/ESPRUINOWIFI Methods for controlling the HTTP server instance, including starting and stopping. ```APIDOC ## httpSrv Class ### Description The HTTP server created by `require('http').createServer`. ### Methods and Fields * `function httpSrv.close()` * `function httpSrv.listen(port)` ## httpSrv.close ⇒ ### Description Stop listening for new HTTP connections. ### Method `function httpSrv.close()` ### Endpoint N/A (Instance method) ### Parameters None ### Request Example ```javascript httpSrv.close(); ``` ### Response #### Success Response (200) None #### Response Example None ## httpSrv.listen ⇒ ### Description Start listening for new HTTP connections on the given port. ### Method `function httpSrv.listen(port)` ### Endpoint N/A (Instance method) ### Parameters - **port** (Number) - The port to listen on. ### Request Example ```javascript httpSrv.listen(8080); ``` ### Response #### Success Response (200) - **return value** (Object) - The HTTP server instance that 'listen' was called on. #### Response Example ```javascript // Returns the httpSrv instance ``` ``` -------------------------------- ### Get Espruino System Time Source: https://www.espruino.com/Reference/ESPRUINOWIFI Returns the current system time as a floating-point number representing seconds since the system started. ```javascript var currentTime = getTime(); ``` -------------------------------- ### Serial Setup and Configuration Source: https://www.espruino.com/Reference/PUCKJS Configure serial ports with specific baud rates and options, including pin assignments, data bits, parity, stop bits, and flow control. Also covers setting up software serial. ```APIDOC ## Serial.setup ### Description Setup this Serial port with the given baud rate and options. ### Method `Serial.setup(baudrate, options)` ### Parameters #### Path Parameters - `baudrate` (number) - The desired baud rate for the serial communication. - `options` (object) - An object containing configuration options: - `rx` (pin) - Receive pin (data in to Espruino). - `tx` (pin) - Transmit pin (data out of Espruino). - `ck` (pin) - Clock Pin (default: none). - `cts` (pin) - Clear to Send Pin (default: none). - `bytesize` (number) - Number of data bits (7 or 8, default: 8). - `parity` (string) - Parity bit ('none', 'o', 'odd', 'e', 'even', default: 'none'). - `stopbits` (number) - Number of stop bits (default: 1). - `flow` (string) - Software flow control ('none', 'xon', default: 'none'). - `path` (string) - Linux Only - the path to the Serial device to use (e.g., "/dev/ttyACM0"). - `errors` (boolean) - Whether to forward framing/parity errors (default: false). ### Request Example ```javascript Serial1.setup(9600, { rx: A0, tx: A1 }); var s = new Serial(); s.setup(9600, { rx: B0, tx: B1 }); ``` ### Response (This method does not return a value, it configures the serial port.) ### Notes - Default pins are used if not specified in options. - `ck` and `cts` are only used if specified. - Previous RX and TX pins remain connected until explicitly changed. - Flow control options include 'xon' or hardware control via `cts` pin. - Setting `errors: true` enables reporting of framing and parity errors. - On Linux, `path` must be specified. ``` -------------------------------- ### Server Listen API Source: https://www.espruino.com/Reference/PICO_R1_3 Start listening for incoming connections on a specified network port. ```APIDOC ## Server.listen ### Description Start listening for new connections on the given port ### Method `Server.listen(port)` ### Endpoint N/A (This is a method of the Server class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **port** (number) - The port number to listen on. ### Request Example ```javascript server.listen(8080); ``` ### Response #### Success Response (200) - **Server instance** - The HTTP server instance that 'listen' was called on. #### Response Example N/A ``` -------------------------------- ### Serial.setup() Source: https://www.espruino.com/Reference/PICO_R1_3 Configures the serial port with a specified baud rate and options. ```APIDOC ## Serial.setup() ### Description Configures the serial port with a specified baud rate and options. ### Method `function Serial.setup(baudrate, options)` ### Parameters * `baudrate` (number) - The desired baud rate (e.g., 9600, 115200). * `options` (object, optional) - Configuration options for the serial port (e.g., `{ parity: 'n', bits: 8, stop: 1, flow: 0, echo: 0, bytesize: 8, errors: false }`). ``` -------------------------------- ### Flash Memory: Get Page Info Source: https://www.espruino.com/Reference/PICO_R1_3 Retrieves the start address and length of a flash memory page containing a given address. This function is not available on devices with limited flash memory. ```javascript Flash.getPage(addr) ``` -------------------------------- ### Serial Setup API Source: https://www.espruino.com/Reference/PICO_R1_3 Configure and initialize a serial port with specified baud rate and options. This includes defining pins for RX, TX, clock, and control, as well as data bit size, parity, stop bits, and flow control. ```APIDOC ## Serial.setup ### Description Setup this Serial port with the given baud rate and options. ### Method `Serial.setup(baudRate, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **baudRate** (number) - The desired baud rate for the serial communication. - **options** (object) - An object containing configuration settings for the serial port: - **rx** (pin) - Receive pin (data in to Espruino). - **tx** (pin) - Transmit pin (data out of Espruino). - **ck** (pin) - Clock Pin (default none). - **cts** (pin) - Clear to Send Pin (default none). - **bytesize** (number) - How many data bits - 7 or 8 (default 8). - **parity** (null | 'none' | 'o' | 'odd' | 'e' | 'even') - Parity bit (default none). - **stopbits** (number) - Number of stop bits to use (default 1). - **flow** (null | undefined | 'none' | 'xon') - Software flow control (default none). - **path** (null | undefined | string) - Linux Only - the path to the Serial device to use. - **errors** (boolean) - Whether to forward framing/parity errors (default false). ### Request Example ```javascript Serial1.setup(9600, { rx: a_pin, tx: a_pin }); ``` ### Response #### Success Response (200) N/A (This is a setup function, no direct return value for success) #### Response Example N/A ``` -------------------------------- ### Espruino Flash Memory: Get Page Information Source: https://www.espruino.com/Reference/ESPRUINOWIFI Retrieves the start address and length of the flash memory page containing a given address. This function is not available on devices with limited flash memory. It returns an object with 'addr' and 'length' properties, or undefined if no page is found. ```javascript require("Flash").getPage(addr) ``` -------------------------------- ### constructor I2C Source: https://www.espruino.com/Reference/ESPRUINOBOARD Creates a software I2C port. Use I2C.setup to configure this port. ```APIDOC ## constructor I2C ### Description Create a software I2C port. ### Method Constructor ### Endpoint `new I2C()` ### Returns An I2C object ### Example ```javascript var i2c = new I2C(); ``` ``` -------------------------------- ### Waveform.startOutput Method Source: https://www.espruino.com/Reference/PUCKJS Begins waveform output on a specified pin. Configurable with frequency and options for timing, repetition, and an optional 'npin'. ```javascript const outputPin = D1; const outputFrequency = 2000; Waveform.startOutput(outputPin, outputFrequency, { time: 10, repeat: true, npin: D2 }); ``` -------------------------------- ### Serial Port Configuration Source: https://www.espruino.com/Reference/ESPRUINOBOARD Methods for configuring and managing serial ports, including setting the console, setup, and unsetup operations. ```APIDOC ## Serial Console Setup ### Description Set the current Serial port as the port for the JavaScript console (REPL). Changes in connection state may cause the console to change unless `force` is true. See `E.setConsole` for a more flexible alternative. ### Method Implicit (Console assignment) ### Endpoint N/A (Function call) ### Parameters * **force** (boolean) - Optional - If true, prevents console changes on connection state changes. ### Request Example ```javascript // Example of setting console (conceptual) Serial1.setAsConsole(true); ``` ### Response N/A --- ## Serial Port Setup ### Description Setup a Serial port with a given baud rate and options for communication. ### Method `Serial.setup(baudrate, options)` ### Endpoint N/A (Instance method) ### Parameters * **baudrate** (number) - The baud rate for the serial connection. Defaults to 9600. * **options** (object) - Optional. A structure containing extra information for initialising the serial port. * **rx** (pin) - Receive pin (data in to Espruino). * **tx** (pin) - Transmit pin (data out of Espruino). * **ck** (pin) - Clock Pin. Not used unless specified. * **cts** (pin) - Clear to Send Pin. Used for hardware flow control (receive only). * **bytesize** (number) - Number of data bits (7 or 8). Defaults to 8. * **parity** (string | null) - Parity bit ('none', 'o', 'odd', 'e', 'even'). Defaults to null. * **stopbits** (number) - Number of stop bits. Defaults to 1. * **flow** (string | null | undefined) - Software flow control ('none', 'xon'). Defaults to none. * **path** (string | null | undefined) - Linux Only: the path to the Serial device. * **errors** (boolean) - Whether to forward framing/parity errors. Defaults to false. ### Request Example ```javascript Serial1.setup(9600, { rx: A0, tx: A1, bytesize: 8, parity: 'none', stopbits: 1, flow: 'none', errors: false }); // Linux example Serial1.setup(9600, { path: "/dev/ttyACM0" }); // Software serial example var s = new Serial(); s.setup(9600, { rx: A0, tx: A1 }); ``` ### Response N/A --- ## Serial Port Unsetup ### Description Uninitialise the serial (or software serial) device if it was previously set up. ### Method `Serial.unsetup()` ### Endpoint N/A (Instance method) ### Parameters None ### Request Example ```javascript Serial1.unsetup(); ``` ### Response N/A --- ## Serial Port Write ### Description Write data to the serial port. Data is written unmodified. ### Method `Serial.write(data, ...)` ### Endpoint N/A (Instance method) ### Parameters * **data, ...** (any) - One or more items to write. Can be ints, strings, arrays, or special objects. ### Request Example ```javascript Serial1.write("Hello"); Serial1.write([65, 66, 67]); // Writes "ABC" ``` ### Response N/A ``` -------------------------------- ### Promise Constructor and Methods in JavaScript Source: https://www.espruino.com/Reference/PICO_R1_3 Demonstrates the creation and usage of Promises for asynchronous operations. Includes methods like .catch(), .then(), .resolve(), and .reject(). Note: Not available on devices with low flash memory. ```javascript new Promise(executor) Promise.reject(promises) Promise.resolve(promises) Promise.prototype.catch(onRejected) Promise.prototype.then(onFulfilled, onRejected) ``` -------------------------------- ### HTTP Server Class API Source: https://www.espruino.com/Reference/PICO_R1_3 APIs for creating and managing an HTTP server instance, including starting and stopping the server. ```APIDOC ## httpSrv Class The HTTP server created by `require('http').createServer` ### function httpSrv.close ⇒ ### Description Stop listening for new HTTP connections. ### Method Function ### Endpoint N/A ### Parameters None ### Request Example ```javascript httpSrv.close(); ``` ### Response #### Success Response (200) None #### Response Example N/A ### function httpSrv.listen ⇒ ### Description Start listening for new HTTP connections on the given port. ### Method Function ### Endpoint N/A ### Parameters - **port** (Number) - The port to listen on. ### Request Example ```javascript httpSrv.listen(8080); ``` ### Response #### Success Response (200) - **Object** - The HTTP server instance that 'listen' was called on. #### Response Example N/A ``` -------------------------------- ### Setup TV Output in Espruino Source: https://www.espruino.com/Reference/ESPRUINOWIFI Initializes TV out capability on supported Espruino devices. It takes an options object and a width parameter, returning a graphics object for drawing. ```javascript var graphics = require("tv").setup({ color: true }, 128); // Use the graphics object to draw on the TV output ``` -------------------------------- ### Make HTTP GET Request (http Library - Espruino) Source: https://www.espruino.com/Reference/ESPRUINOWIFI Performs an HTTP GET request to a specified URL. This is a convenience function that simplifies making GET requests. It automatically sets the HTTP method to 'GET' and calls `end` on the request. The callback function receives a response object, and data can be processed using `res.on('data', ...)` and connection closure can be monitored with `res.on('close', ...)`. ```javascript 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"); }); }); ``` -------------------------------- ### HTTP Server Start Listening Source: https://www.espruino.com/Reference/PICO_R1_3 Initiates the HTTP server to listen for new connections on a specified port. It returns the HTTP server instance. ```javascript function httpSrv.listen(port) ``` -------------------------------- ### Listen on Espruino Network Server Port Source: https://www.espruino.com/Reference/ESPRUINOWIFI Starts a network server to listen for new connections on a specified port. ```javascript server.listen(port); ``` -------------------------------- ### Access HTTP Request Method (httpSRq) Source: https://www.espruino.com/Reference/PICO_R1_3 Gets the HTTP method used for the request, typically a string like 'GET'. ```javascript var method = httpSRq.method; ``` -------------------------------- ### Object.getOwnPropertyDescriptor - Get Property Descriptor Source: https://www.espruino.com/Reference/PUCKJS Returns a property descriptor object for a specified property of an object. This descriptor details configuration like `value`, `writable`, `get`, and `set`. ```javascript var obj = { prop: 42 }; var descriptor = Object.getOwnPropertyDescriptor(obj, 'prop'); console.log(descriptor); // Output: { value: 42, writable: false, enumerable: true, configurable: false } ``` -------------------------------- ### Serial Instances Source: https://www.espruino.com/Reference/PUCKJS Overview of available serial port instances like Bluetooth, Loopback, and standard Serial ports. ```APIDOC ## Serial Instances ### Bluetooth ``` The Bluetooth Serial port - used when data is sent or received over Bluetooth ``` ### LoopbackA ``` A loopback serial device. Data sent to `LoopbackA` comes out of `LoopbackB` ``` ### LoopbackB ``` A loopback serial device. Data sent to `LoopbackA` comes out of `LoopbackB` ``` ### Serial1 ``` The first Serial (USART) port ``` ``` -------------------------------- ### Array.join Example in Espruino Source: https://www.espruino.com/Reference/ESPRUINOWIFI The `join` function concatenates all elements of an array into a single string, using a specified separator between elements. For example, `[1,2,3].join(' ')` results in the string `'1 2 3'`. ```javascript [1,2,3].join(' ') ``` -------------------------------- ### Setup I2C Port Source: https://www.espruino.com/Reference/PUCKJS Configures the I2C port with optional parameters for pins (SCL, SDA) and bitrate. If options are not provided, default pins are used. The maximum bitrate for most devices is 400kHz. Ensure pins are marked with 'I2C' on your board's reference page. ```javascript I2C.setup(options) // options: {scl:pin, sda:pin, bitrate:100000} ``` -------------------------------- ### Start Bluetooth Notifications (Espruino JS) Source: https://www.espruino.com/Reference/PUCKJS Starts receiving notifications for a Bluetooth GATT characteristic. A 'characteristicvaluechanged' event is fired when the value changes, and the new value is available as a DataView. This requires NRF52 devices or ESP32 boards. ```javascript 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); // this is a DataView }); return c.startNotifications(); }).then(function(d) { console.log("Waiting for notifications"); }).catch(function() { console.log("Something's broken."); }); ``` ```javascript var gatt; NRF.connect("pu:ck:js:ad:dr:es random").then(function(g) { gatt = g; return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); }).then(function(service) { return service.getCharacteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); }).then(function(characteristic) { characteristic.on('characteristicvaluechanged', function(event) { console.log("RX: "+JSON.stringify(event.target.value.buffer)); }); return characteristic.startNotifications(); }).then(function() { console.log("Done!"); }); ``` -------------------------------- ### SPI Class Methods Source: https://www.espruino.com/Reference/ESPRUINOBOARD Documentation for the SPI class, including finding SPI devices, setting up SPI communication, and sending data. ```APIDOC ## SPI Find Device ### Description **DEPRECATED** - Tries to find an SPI hardware device that can work with the given pin. ### Method `SPI.find(pin)` ### Endpoint N/A (Static method) ### Parameters * **pin** (pin) - A pin to search with. ### Returns * An object of type `SPI`, or `undefined` if no device is found. ### Request Example ```javascript var spiDevice = SPI.find(A0); if (spiDevice) { console.log("SPI device found"); } ``` --- ## SPI Setup ### Description Setup the SPI port with the specified options. ### Method `SPI.setup(options)` ### Endpoint N/A (Instance method) ### Parameters * **options** (object) - A structure containing options for the SPI setup. * **mode** (number) - SPI mode (0-3). Default is 0. * **hz** (number) - SPI speed in Hz. Default is 4MHz. * **mosi** (pin) - Master Out Slave In pin. * **miso** (pin) - Master In Slave Out pin. * **sck** (pin) - Serial Clock pin. ### Request Example ```javascript SPI1.setup({ mosi: A0, miso: A1, sck: A2, baudrate: 1000000, // 1MHz mode: 0 }); ``` ### Response N/A --- ## SPI Send Data ### Description Send data over the SPI interface. This method sends raw data bytes. ### Method `SPI.send(data, nss_pin)` ### Endpoint N/A (Instance method) ### Parameters * **data** (Array | string) - The data to send. Can be an array of numbers or a string. * **nss_pin** (pin) - The Not-Slave-Select pin. This pin will be set low before sending and high after. ### Request Example ```javascript var dataToSend = [0x12, 0x34, 0x56]; SPI1.send(dataToSend, NSS); ``` --- ## SPI Send 4-bit Data ### Description Send data over the SPI interface, sending 4 bits at a time. ### Method `SPI.send4bit(data, bit0, bit1, nss_pin)` ### Endpoint N/A (Instance method) ### Parameters * **data** (Array | string) - The data to send. * **bit0** (number) - The first bit to send. * **bit1** (number) - The second bit to send. * **nss_pin** (pin) - The Not-Slave-Select pin. ### Request Example ```javascript SPI1.send4bit([0x1, 0x2], 0, 1, NSS); ``` --- ## SPI Send 8-bit Data ### Description Send data over the SPI interface, sending 8 bits at a time. ### Method `SPI.send8bit(data, bit0, bit1, nss_pin)` ### Endpoint N/A (Instance method) ### Parameters * **data** (Array | string) - The data to send. * **bit0** (number) - The first bit to send. * **bit1** (number) - The second bit to send. * **nss_pin** (pin) - The Not-Slave-Select pin. ### Request Example ```javascript SPI1.send8bit([0x11, 0x22], 0, 1, NSS); ``` --- ## SPI Constructor ### Description Creates a new SPI instance. Note that this does not automatically set up the pins; use `SPI.setup` for that. ### Method `new SPI()` ### Endpoint N/A ### Parameters None ### Request Example ```javascript var customSPI = new SPI(); customSPI.setup({ mosi: B5, miso: B6, sck: B7, baudrate: 2000000 }); ``` ### Response An instance of the SPI class. ``` -------------------------------- ### Object.length Source: https://www.espruino.com/Reference/PUCKJS Gets the length of an object. ```APIDOC ## Object.length ### Description Find the length of the object. ### Method `property Object.length` ### Returns The length of the object ``` -------------------------------- ### Waveform.startInput Method Source: https://www.espruino.com/Reference/PUCKJS Initiates waveform input on a specified analog-capable pin. It supports setting frequency and options for timing and repetition. A 'finish' event is emitted if not repeating. ```javascript const pin = A0; const frequency = 1000; Waveform.startInput(pin, frequency, { time: getTime() + 1, repeat: false }); ``` -------------------------------- ### SPI.setup Source: https://www.espruino.com/Reference/ESPRUINOWIFI Configures the SPI port as an SPI Master. It accepts an options object to define pins, baud rate, mode, data order, and bits per transfer. ```APIDOC ## SPI.setup ### Description Set up this SPI port as an SPI Master. Options can contain the following (defaults are shown where relevant): ```json { sck: pin, miso: pin, mosi: pin, baud: integer = 100000, // ignored on software SPI mode: integer = 0, // between 0 and 3 order: string = 'msb' // can be 'msb' or 'lsb' bits: 8 // only available for software SPI } ``` 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. Some boards such as those based on `nRF52` chips can have SPI on any pins, so don't have specific markings. 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. ### Method `SPI.setup(options)` ### Parameters #### Request Body - **options** (object) - An Object containing extra information on initialising the SPI port. - **sck** (pin) - The SPI clock pin. - **miso** (pin) - The SPI Master In Slave Out pin. - **mosi** (pin) - The SPI Master Out Slave In pin. - **baud** (integer, optional) - The baud rate for SPI communication. Defaults to 100000. - **mode** (integer, optional) - The SPI mode (0-3). Defaults to 0. - **order** (string, optional) - The data transmission order ('msb' or 'lsb'). Defaults to 'msb'. - **bits** (integer, optional) - The number of bits per transfer (only for software SPI). Defaults to 8. ### Request Example ```javascript SPI1.setup({ mosi : Node.GPIO.getPin('D0'), miso : Node.GPIO.getPin('D1'), sck : Node.GPIO.getPin('D2') }); ``` -------------------------------- ### Start Advanced NFC Mode - Espruino Source: https://www.espruino.com/Reference/PUCKJS Enables NFC and starts advertising, enabling `NFCrx` events for received data. An optional 7-byte UID can be provided. This is for advanced usage, as `NRF.nfcURL` is simpler for URL advertising. Available on NRF52 devices with NFC. ```javascript NRF.nfcStart(); ``` -------------------------------- ### Get Memory Address of a Variable Source: https://www.espruino.com/Reference/ESPRUINOBOARD Retrieves the memory address of a given JavaScript variable. The `flatAddress` option can be used to get the address of data within Flat Strings or ArrayBuffers. This is useful for low-level memory manipulation with peek/poke functions. ```javascript E.getAddressOf(v, flatAddress); ``` -------------------------------- ### Array.fill() - Populate Array Elements Source: https://www.espruino.com/Reference/PUCKJS Fills all the elements of an array from a start index to an end index with a static value. The `start` and `end` parameters are optional and can be negative to indicate an offset from the end of the array. Note: This method is not available on devices with limited flash memory. ```javascript Array.fill(value, start, end) ``` -------------------------------- ### String.padStart() - Pad string at the beginning Source: https://www.espruino.com/Reference/PICO_R1_3 Pads the current string with another string until the resulting string reaches the given length. The padding occurs at the beginning of the current string. If the padString is too long, it will be truncated. ```javascript "Hello".padStart(10) // Returns " Hello" "123".padStart(10, ".-") // Returns ".-.-.-.123" ``` -------------------------------- ### Pin.getInfo() Source: https://www.espruino.com/Reference/PUCKJS Get information about this pin and its capabilities. ```APIDOC ## function Pin.getInfo ⇒ ### Description Get information about this pin and its capabilities. Of the form: ```json { "port" : "A", // the Pin's port on the chip "num" : 12, // the Pin's number "mode" : (2v25+) // string: the pin's mode (same as Pin.getMode()) "output" : (2v25+) // 0/1: the state of the pin's output register "in_addr" : 0x..., // (if available) the address of the pin's input address in bit-banded memory (can be used with peek) "out_addr" : 0x..., // (if available) the address of the pin's output address in bit-banded memory (can be used with poke) "analog" : { ADCs : [1], channel : 12 }, // If analog input is available "functions" : { "TIM1":{type:"CH1, af:0"}, "I2C3":{type:"SCL", af:1} } } ``` Will return undefined if pin is not valid. **Note:** This is not available in devices with low flash memory ### Method `function Pin.getInfo()` ### Returns An object containing information about this pins ``` -------------------------------- ### Espruino NetworkJS Initialization with Callbacks Source: https://www.espruino.com/Reference/ESPRUINOWIFI Initializes network functionality using a configuration object with callback functions for socket creation, closing, accepting connections, receiving data, and sending data. The `create` callback is essential for setting up the network interface. Handles different socket types like UDP. ```javascript require("NetworkJS").create({ create : function(host, port, socketType, options) { // Create a socket and return its index, host is a string, port is an integer. // If host isn't defined, create a server socket console.log("Create",host,port); return 1; }, close : function(sckt) { // Close the socket. returns nothing }, accept : function(sckt) { // Accept the connection on the server socket. Returns socket number or -1 if no connection return -1; }, recv : function(sckt, maxLen, socketType) { // Receive data. Returns a string (even if empty). // If non-string returned, socket is then closed return null;//or ""; }, send : function(sckt, data, socketType) { // Send data (as string). Returns the number of bytes sent - 0 is ok. // Less than 0 return data.length; } }); ``` -------------------------------- ### Object.getOwnPropertyDescriptors Source: https://www.espruino.com/Reference/PUCKJS Gets information about all properties of an object. ```APIDOC ## Object.getOwnPropertyDescriptors ### Description Get information on all properties in the object (from `Object.getOwnPropertyDescriptor`), or just `{}` if no properties. ### Method `Object.getOwnPropertyDescriptors(obj)` ### Parameters - **obj** (object) - The object ### Returns An object containing all the property descriptors of an object ### Notes This is not available in devices with low flash memory. ```