-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebusb03.html
44 lines (40 loc) · 1.54 KB
/
webusb03.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<h6>Version 0.0.1-1</h6>
<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': 0x025B }
];
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>