Exploring Web Serial API

Chrome introduced support for Web Serial API which in Origin trials state(Available on all desktop platforms). This opens up lot possibilities to control physical devices which provide a serial interface. In this post we will see how to control the onboard led present in the arduino board. I am using wio terminal, any arduino compatible device with onboard led should work.

First enable the serial api using the following flag.

chrome://flags/#enable-experimental-web-platform-features
enable Web Serial API in chrome

How to access serial port from web page

Serial API provides asynchronous methods to access the serial port. First we need to request for a serial port (browser will prompt the user to a select a serial port), once the port object is available we can open it with required baud rate.

const port = await navigator.serial.requestPort();
await port.open({  baudRate : 9600 }); 
opening serial port from web

Now we can access read/write streams on it

const writer = port.writable.getWriter();
const reader = port.readable.getReader();  

For more details on the web serial API see this page

We will be using a simple serial protocol to switch on/off the led. The arduino code will be listening to serial part for valid integers, in case it receives 1 it will switch on the led and for -1 it will switch off the led.

Load above code to arduino and click on connect button below, chrome will prompt with available serial ports, select arduino port and click connect. Once connected send either 1 or -1 to control the led.



5 Comments

Add a Comment

Your email address will not be published. Required fields are marked *