Skip to content

Serial

Module Io.Serial

The class Serial.Device is a wrapper around the underlying browser WebSerial API.

It doesn’t do too much, mostly handling buffering and text encoding/decoding.

For interactivity purposes, it’s useful for connecting to microcontrollers like Arduino, ESP32, Raspberry Pico, Microbit, Espruino Pico etc. For example, sending a command to the microcontroller to move a motor, or receive sensor data from something connected to the microcontroller.

It’s possible to send simple strings back and forth, but very quickly you’ll find yourself needing to send structured data. JSON is a good-enough solution to this - very easy from the Javascript side, and all platforms have libraries create and consume JSON.

For example, you might have an analog joystick module connected to a microcontroller that sends readings every 100ms:

// Type: { x: number, y: number, pressed: boolean }
// Example:
{ x: 1, y: 103, pressed: false }

These would be sent as “string-encoded” JSON, which is then decoded on the Javascript side with JSON.parse.

Connecting to a serial port has to be via user interaction, such as in a button event handler (not shown in the example below)

import { Serial } from 'https://unpkg.com/ixfx/dist/io.js'
// Create
const s = new Serial.Device({ baudRate: 9600 });
// Listen for incoming data
s.addEventListener(`data`, evt => {
// Eg, assume we're getting JSON
try {
const o = JSON.parse(evt.data);
queue.enqueue(o); // Enqueue data for processing...
} catch (ex) {
}
});
// In a UI event handler, call .connect()
s.connect();

Write data to the serial port:

// Eg. a command to to set LED #120 to white
// (obvs. needs to be interpreted and used on the microcontroller side)
s.write(JSON.stringify({ cmd:"set", led: 120, value: "ffffff" }));

Serial.Device reports when its state changes, eg from ‘connecting’ to ‘connected’ state.

s.addEventListener(`change`, evt => {
console.log(`State change ${evt.priorState} -> ${evt.newState}`);
});