直接代码,需要自行填写波特率
注释部分为debug信息
代码如下
<!DOCTYPE html>
<html>
<head>
<title>Web Serial API Hex Output</title>
</head>
<body>
<h1>Serial Device Reader</h1>
<button id="request-port">Request Port</button>
<div id="output"></div>
<div id="debug"></div>
<script>
const output = document.getElementById('output');
const debug = document.getElementById('debug');
const requestPortButton = document.getElementById('request-port');
function toHexString(byteArray) {
return Array.from(byteArray, byte => {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
}
requestPortButton.addEventListener('click', async () => {
try {
// Request a port and open a connection.
const port = await navigator.serial.requestPort();
await port.open({ baudRate: 115200 });
//debug.textContent = 'Port opened';
const reader = port.readable.getReader();
//debug.textContent += '\nReader created';
while (true) {
const { value, done } = await reader.read();
//debug.textContent += '\nRead: ' + JSON.stringify(value);
if (done) {
//debug.textContent += '\nDone reading';
break;
}
if (value) {
const hexString = toHexString(value);
output.innerHTML += hexString + ' <br/>';
}
}
reader.releaseLock();
await port.close();
//debug.textContent += '\nPort closed';
} catch (error) {
output.textContent = 'Error: ' + error;
}
});
</script>
</body>
</html>
评论 (0)