Web USB send to browser

M0 webusb arduino samd21

Pre-requisites

Send a simple sentence from the MCU to the browser on laptop.

Start the web browser code with make server.

Ensure the browser side of the code is also implemented with serial.js.

Download code

<button id="connect">Connect to device</button>
<p>Open the browser console to see received messages from the MCU!</p>

<!-- serial.js
From https://github.com/webusb/arduino/blob/gh-pages/demos/serial.js
Add 'vendorId': 0x2341 and 0x2a03 in line 27 and line 28
-->
<script src="serial.js"></script>
<script>
serial.requestPort = function() {
  const filters = [
    { 'vendorId': 0x2341 },
    { 'vendorId': 0x2a03 }
  ];
  return navigator.usb.requestDevice({ 'filters': filters }).then(
    device => new serial.Port(device)
  );
}

var port
let connectButton = document.querySelector('#connect')
let textDecoder = new TextDecoder()

connectButton.addEventListener('click', function() {
  if (port) { // If port is already connected, disconnect it
    connectButton.textContent = 'Connect'
    port.disconnect()
    port = null
    console.log('Device is disconnected.')
  } else { // If there is no port, then connect to a new port
    serial.requestPort().then(selectedPort => {
      port = selectedPort
      port.connect().then(() => {
        console.log('Device is connected to Product ID: ' + port.device_.productId.toString(16) + ' and Vendor ID: ' + port.device_.vendorId.toString(16))

        connectButton.textContent = 'Disconnect'
        port.onReceive = data => { console.log(textDecoder.decode(data))}
        port.onReceiveError = error => { console.log('Receive error: ' + error)}
      }, error => { console.log('Connection error: ' + error) })
    }).catch(error => { console.log('Connection error: ' + error) })
  }
})
</script>

Code

Download code
#include <WebUSB.h>

// Modified from example https://webusb.github.io/arduino/demos/console
WebUSB WebUSBSerial(1, "webusb.github.io/arduino/demos/console");

void setup() {
  WebUSBSerial.begin(9600);
  while (!WebUSBSerial) {}
  delay(100);
}

void loop() {
  WebUSBSerial.write("Hello world to the browser!");
  WebUSBSerial.flush();

  delay(2000);
}

References