Skip to content
Jordan Yoon-Buck edited this page Mar 9, 2021 · 1 revision

Adding p5.WebSerial to your page

Option 1: Add script directly

Download the p5.webserial.js script from Releases and add it to your website with a script tag. If you're using p5, add p5.WebSerial afterwards.

<script src="./p5.min.js"></script>
<script src="./p5.webserial.js"></script>

Alternatively, use a CDN such as unpkg to serve p5.

<script src="https://unpkg.com/p5-webserial@0.1.1/build/p5.webserial.js"></script>

Note: You do not need p5 to use p5.WebSerial.

You can then create a new p5.WebSerial object in your script (e.g., sketch.js).

const serial = new p5.WebSerial();

Option 2: Use npm

p5.webserial is also available as a package from npm, which may be useful if you're using a bundler to generate your website's javascript.

npm install p5-webserial
import WebSerial from "p5-webserial";
const serial = new WebSerial();

Checking for WebSerial support

If you expect that your application might be used in an environment where WebSerial isn't available, you can use the static method checkSupport() to determine whether the browser supports WebSerial.

if (!WebSerial.checkSupport()) {
  alert("WebSerial is not supported.");
}

Important: WebSerial is only available in secure contexts. When debugging your application locally, you will need to serve the webpage and access it via localhost. When deploying your application, you will need to ensure it is served via https.

Choosing a serial port

To show the user a prompt to choose a serial port, call the requestPort method. You can optionally pass in filters to limit the serial ports shown. If the user selects a serial port, the portavailable event will be fired. If the user cancels, or no port is available, the requesterror event will be fired.

serial.requestPort();
serial.on("portavailable", function() {
  // we have a serial port, do something with it!
});
serial.on("requesterror", function() {
  // no serial port :(
});

Important: you can only call requestPort as a result of a user gesture with your webpage (e.g., as the result of a click event).

Once a user has granted access to a serial port, it may be available in the future (even in subsequent page loads). You can choose previously selected ports without requiring a user gesture using the getPorts method. This method fires portavailable if a port is selected and noport if no previously user-selected ports are available.

serial.getPorts(); // see if any ports are already available
serial.on("noport", function() {
  // we don't have access to any ports yet, so we need to request them.
  // add an event listener for a user clicking on the page
  // you could also, for example, show a "select port" button
  document.addEventListener("click", function() {
    // request a port from the user
    serial.requestPort();
  }, { once: true })
})
serial.on("portavailable", function() {
  // we have a serial port, do something with it!
})
serial.on("requesterror", function() {
  // no serial port :(
})

Opening the serial port

Once a serial port is selected, it can be opened using the open method. open optionally takes an argument to specify serial options. If an error occurs, the openerror event will be fired. Otherwise, open will be emitted once the port is ready.

Once the serial port is opened, the data event will be fired whenever data is available on the serial port.

If an error occurs at any point while reading from the serial port, the readerror event will be fired.

serial.on("portavailable", function() {
  serial.open();
});
serial.on("open", function() {
  // we're ready to receive or send data!
});
serial.on("data", function() {
  // data is available on the serial port
});
serial.on("readerror", function() {
  // an error occurred whiel reading
});

Closing the serial port

To close the serial port, call the close method. If an error occurs, closeerror is emitted. Once the port is closed, the close event will be emitted.

Reading from the serial port

A variety of methods are available to read data from the serial port. The p5.WebSerial library queues data as it arrives, and data can be retrieved on demand. Each of these methods that reads data will remove it from the queue. More details about these methods are available in the API documentation.

  • read() — reads a single byte from the queue (returns a number)
  • readChar() — reads a single byte from the queue as a character (returns a string)
  • readBytes() — reads all data currently available in the queue as a Uint8Array.
  • readBytesUntil(charToFind) — reads bytes until a character is found (returns a Uint8Array)
  • readStringUntil(stringToFind) — reads out a string until a certain substring is found (returns a string)
  • readLine() — read a string until a line ending is found (returns a string)

One common operation is to read from the serial buffer one line at a time.

serial.on("data", function() {  // fires every time data arrives
  let line = serial.readLine(); // returns null when a full line isn't available
  if (line) {
    // do something with the line of data!
  }
});

Two additional methods are available to interact with the queue:

  • available() — returns the number of bytes still in the queue
  • clear() — clears the input queue without reading it

Writing to the serial port

You can use the following methods to write to the serial port.

  • write(data) — write data to the serial port. Data can be a number (written directly as a byte), an array of numbers (written as bytes), a string (encoded as UTF-8), or a Uint8Array (written directly as bytes).
  • print(data) — synonym of write; usually used for writing strings.
  • println(data) — write a string to the serial port followed by a line ending.

If an error occurs during writing, the writeerror event will be thrown.

Listening for events

Use the on method to add an event listener.

serial.on("data", function() {
  // inline function expression
});

serial.on("data", onData);
function onData() {
  // separate function
}

Use the off method to remove an event listener.

serial.on("data", onData);
// later:
serial.off("data", onData);

Possible events:

  • noport — no port available from getPorts()
  • portavailable — port selected
  • open — serial port opened
  • close — serial port closed
  • data — data received over serial
  • requesterror
  • openerror
  • closeerror
  • readerror
  • writeerror
  • error

All error events will pass the associated Error as the first argument to the event listener.

serial.on("openerror", function(error) {
  alert(error.message);
});

The error event is fired when any type of error occurs. If desired, you can stop propagation to the error event by calling the second argument to your event listener.

serial.on("requesterror", function(error, stopPropagation) {
  stopPropagation();
});
serial.on("error", function(error) {
  // some other type of error occurred
})
Clone this wiki locally