前端串口serialport.js串口通信库快速入门(附经验总结)
公司项目需要开发一个windows客户端,提供串口modbusRTU数据读取、处理、显示和控制功能。
项目使用了electron 31.0.2版本,串口通信库使用了serialport 12.0.0版本。

- serialport.js官方文档地址:https://serialport.io/docs/
- npm包地址:https://www.npmjs.com/package/serialport
- github项目地址:https://github.com/serialport/node-serialport
一、serialport简介
serialport.js 是一个用于 Node.js 的串口通信库,允许开发者通过 JavaScript 与串口设备(如 Arduino、传感器、GPS 模块等)进行通信。它提供了一个简单且强大的 API,用于打开、配置、读取和写入串口数据。serialport.js 是开源的,基于 MIT 许可证,广泛应用于物联网(IoT)、嵌入式系统和硬件开发项目中。
重点,serialport.js必须运行与Node.js环境,在浏览器环境是无法使用的,所以一般结合electron.js使用,serialport.js在electron的主进程中调用并使用。
1.1 安装
可以通过 npm 安装 serialport.js(cnpm、pnpm、yarn都是一样的)
现在默认安装的应该是12.0.0版本
npm i serialport
1.2 基本用法
import {
SerialPort } from 'serialport';
// 打开串口
const port = new SerialPort('/dev/ttyUSB0', {
baudRate: 9600, // 设置波特率
dataBits: 8, // 数据位
parity: 'none', // 校验位
stopBits: 1, // 停止位
autoOpen: false // 不自动打开
});
// 打开串口时触发
port.open((err) => {
if (err) {
return console.error('Error opening port:', err.message);
}
console.log('Port opened successfully');
});
// 监听数据事件
port.on('data', (data) => {
console.log('Received data:', data.toString());
});
// 监听错误事件
port.on('error', (err) => {
console.error('Error:', err.message);
});
// 关闭串口
setTimeout(() => {
port.close((err) => {
if (err) {
return console.error('Error closing port:', err.message);
}
console.log

最低0.47元/天 解锁文章
1964

被折叠的 条评论
为什么被折叠?



