依赖插件:serilaport
安装:npm install serialport -save
node程序:
var SerialPort = require("serialport").SerialPort; var serialPort = new SerialPort("COM2", { baudrate: 115200 }); serialPort.on( "data", function( data ) { data = +data; console.log(data); });
tips:
1.COM2指的是端口号,很多示例代码上的/dev/tty-usbserial1指的是linux系统下的端口号。
2.程序运行之前要先将端口关闭,不能有其他设备或软件占用,比如串口调试工具。否则会报错:Access Denied
列出所有端口详细信息:
var serialPort = require("serialport"); serialPort.list(function (err, ports) { ports.forEach(function(port) { console.log(port.comName); console.log(port.pnpId); console.log(port.manufacturer); }); });
串口发送消息:
var SerialPort = require("serialport").SerialPort; var serialPort = new SerialPort("COM2", { baudrate: 115200 }); function callbackFun(){ console.log('22222') } function writeAndDrain (data,callback) { serialPort.write(data, function () { serialPort.drain(callback); }); } setInterval(function(){ writeAndDrain('66',callbackFun) },1000);
串口调试工具:AccessPoart
虚拟串口:vspd
serialport文档:https://www.npmjs.com/package/serialport#installation-instructions