serialport.js //node实现串口通信 扫描到内容后控制继电器开闭const SerialPort = require('serialport');//引入模块//初始化扫描枪串口const port_read = new SerialPort('/dev/ttyACM0');//初始化继电器串口const
//node实现串口通信 扫描到内容后控制继电器开闭 const SerialPort = require('serialport');//引入模块 //初始化扫描枪串口 const port_read = new SerialPort('/dev/ttyACM0'); //初始化继电器串口 const port_write = new SerialPort('/dev/ttyUSB0'); //标签 继电器是否连接 port_write.connected=false; port_read.on('open', function(err) { debug('Port Read Opened!'); }); port_read.on('error',function(err){ debug(err); }); port_write.on('open', function(err) { debug('Port Ctrl Opened!'); port_write.connected=true; }); port_write.on('error',function(err){ debug(err); }); //遍历出所有串口 SerialPort.list(function (err,ports){ ports.forEach(function (p){ //console.log(p.comName,p.pnpId); }); }); var buffer = new Buffer(4); //继电器是否打开 默认关闭 port_write.open=false; //扫描枪扫描到数据 port_read.on('data', function(data) { debug("Data:"+data.toString()); if(port_write.connected){ //根据继电器状态写入不同指令 if(port_write.open){ buffer = new Buffer([0xA0,0x01,0x0,0xA1]); }else{ buffer = new Buffer([0xA0,0x01,0x01,0xA2]); } //写入继电器命令 port_write.write(buffer, function(err) { if (err) { debug('Error:', err.message); }else{ debug('Data Send!'); port_write.open=!port_write.open; } }); } }); function debug(msg) { console.log("Console\t" + getTime() + "\t" + msg); } function getTime() { var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.getSeconds(); if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } if (seconds < 10) { seconds = "0" + seconds; } return hours + ":" + minutes + ":" + seconds; }