Web USB LED

M0 webusb arduino samd21

Pre-requisites

Turn on/off LED on-board compatible arduino hardware through a button press in the browser on the laptop which is connected to the hardware.

Use this firmware with the mcu firmware.

Code

Download code View demo
<title>WebUSB</title>
<button id="connect">Connect to device</button>

<p>
  <button id="on">LED ON</button>
  <button id="off">LED OFF</button>
</p>

<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()
let textEncoder = new TextEncoder()

document.querySelector('#on').addEventListener('click', function(event) {
  if (port !== undefined) {
    port.send(textEncoder.encode('H')).catch(error => {
      console.log('Send error: ' + error)
    })

    console.log('Sending H')
  }
})

document.querySelector('#off').addEventListener('click', function(event) {
  if (port !== undefined) {
    port.send(textEncoder.encode('L')).catch(error => {
      console.log('Send error: ' + error)
    })

    console.log('Sending L')
  }
})

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>
</body>
</html>

Browser console

Open the browser developer console.

Web USB LED browser

References