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:
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)
Write data to the serial port:
Serial.Device
reports when its state changes, eg from ‘connecting’ to ‘connected’ state.