原生js的webserial实现连接串口数据

作者 : admin 本文共2109个字,预计阅读时间需要6分钟 发布时间: 2023-12-4 共2人阅读

文章目录

  • 前言
  • js为什么要连接串口数据
  • 直接上代码
  • 后言

前言

hello world欢迎来到前端的新世界


😜当前文章系列专栏:javaScript
🐱‍👓博主在前端领域还有很多知识和技术需要掌握,正在不断努力填补技术短板。(如果出现错误,感谢大家指出)🌹
💖感谢大家支持!您的观看就是作者创作的动力

js为什么要连接串口数据

在JavaScript中,连接串口数据通常是为了与外部设备进行通信和交互。例如,许多硬件设备(如Arduino板、传感器等)使用串口来与计算机通信。通过连接串口数据,JavaScript可以发送和接收与这些设备之间的数据。

连接串口数据可以带来以下好处:

  • 与硬件设备通信:通过连接串口数据,JavaScript可以与硬件设备进行通信,以控制和监测设备的状态。这为创建物联网应用或与传感器、机器人等进行交互提供了便利。

  • 数据采集:某些设备通过串口发送数据,例如传感器采集的实时数据。通过连接串口数据,JavaScript可以读取设备发送的数据,进行实时的数据采集和监测。

  • 数据处理和分析:连接串口数据使得JavaScript能够获取设备发送的数据,从而进行数据处理和分析。例如,可以对传感器数据进行实时的计算和图表展示。

需要注意的是,连接串口数据需要一些额外的设置和操作,因为JavaScript在浏览器运行时不直接提供对串口的访问。通常需要使用特定的库或API来实现串口连接和数据交互,如Web Serial API、node-serialport等。

直接上代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Serial API</title>
</head>
<body>
<button id="connectButton">连接串口</button>
<button id="disconnectButton">断开连接</button>
<select id="serialPortSelect"></select>
<pre id="serialData"></pre>
<script>
async function connectSerial() {
const filters = [
{ usbVendorId: 0x2341, usbProductId: 0x8036 } // 替换为你的串口设备的供应商ID和产品ID
];
try {
const port = await navigator.serial.requestPort({ filters });
await port.open({ baudRate: 9600 });
const reader = port.readable.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
const textDecoder = new TextDecoder();
const data = textDecoder.decode(value);
document.getElementById('serialData').textContent += data;
}
} catch (error) {
console.error(error);
}
}
function disconnectSerial() {
// 断开连接逻辑
}
function updateSerialPortList(ports) {
const select = document.getElementById('serialPortSelect');
select.innerHTML = '';
ports.forEach(port => {
const option = document.createElement('option');
option.value = port.path;
option.textContent = port.path;
select.appendChild(option);
});
}
async function getSerialPorts() {
const ports = await navigator.serial.getPorts();
updateSerialPortList(ports);
}
document.getElementById('connectButton').addEventListener('click', connectSerial);
document.getElementById('disconnectButton').addEventListener('click', disconnectSerial);
navigator.serial.addEventListener('connect', getSerialPorts);
navigator.serial.addEventListener('disconnect', getSerialPorts);
getSerialPorts();
</script>
</body>
</html>

后言

创作不易,要是本文章对广大读者有那么一点点帮助 不妨三连支持一下,您的鼓励就是博主创作的动力

本站无任何商业行为
个人在线分享 » 原生js的webserial实现连接串口数据
E-->