Web USB LED

Updated on 27 August 2021
dev board RobotDyn M0 mini
firmware Arduino
chip SAMD21
features WebUSB
This tutorial is more than 1 year old. If the steps below do not work, then please check the latest versions and the documentations of the individual tools used.

Before starting

Dependancies

Ensure the following dependancies are downloaded and available:

Pre-requisites

Try these simpler or similar examples:

Code

Download code View demo webusb-led-demo.html
<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

Description

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.

References