Web Serial API 串口通信 Demo:连接、发送和接收数据
要实现一个串口通信的demo,可以使用Web Serial API来连接和通信。\n\n首先,需要在HTML文件中添加一个按钮和一些文本框,用于输入和显示数据。然后,可以使用以下JavaScript代码来连接和通信串口。\n\njavascript\n// 获取页面元素\nconst connectButton = document.getElementById('connectButton');\nconst disconnectButton = document.getElementById('disconnectButton');\nconst sendButton = document.getElementById('sendButton');\nconst receivedData = document.getElementById('receivedData');\nconst inputData = document.getElementById('inputData');\n\n// 串口对象\nlet serialPort;\n\n// 连接串口\nconnectButton.addEventListener('click', async () => {\n try {\n // 请求用户授权\n const port = await navigator.serial.requestPort();\n\n // 打开串口\n await port.open({ baudRate: 9600 });\n\n // 设置串口对象\n serialPort = port;\n\n // 监听数据接收事件\n const reader = port.readable.getReader();\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n receivedData.textContent += new TextDecoder().decode(value);\n }\n\n // 禁用连接按钮,启用发送和断开按钮\n connectButton.disabled = true;\n sendButton.disabled = false;\n disconnectButton.disabled = false;\n } catch (error) {\n console.error(error);\n }\n});\n\n// 断开连接\ndisconnectButton.addEventListener('click', async () => {\n try {\n // 关闭串口\n await serialPort.close();\n\n // 清空接收数据\n receivedData.textContent = '';\n\n // 启用连接按钮,禁用发送和断开按钮\n connectButton.disabled = false;\n sendButton.disabled = true;\n disconnectButton.disabled = true;\n } catch (error) {\n console.error(error);\n }\n});\n\n// 发送数据\nsendButton.addEventListener('click', async () => {\n try {\n const data = inputData.value;\n\n // 发送数据\n await serialPort.write(new TextEncoder().encode(data));\n\n // 清空输入框\n inputData.value = '';\n } catch (error) {\n console.error(error);\n }\n});\n\n\n在HTML文件中,需要添加以下内容:\n\nhtml\n<button id="connectButton">连接</button>\n<button id="disconnectButton" disabled>断开</button>\n<input type="text" id="inputData" />\n<button id="sendButton" disabled>发送</button>\n<div id="receivedData"></div>\n\n\n这样就可以通过Web Serial API实现一个简单的串口通信demo了。
原文地址: https://www.cveoy.top/t/topic/pEa3 著作权归作者所有。请勿转载和采集!