nodejs串口通信
作者:互联网
nodejs串口通信(基础)
let bodyParser = require('body-parser');
let express = require("express"),
app = express();
let port = 8686;
app.listen(port, () => {
console.log(`server is success,listen on ${port}`);
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static('./static'));
//引入串口通信的模块
let SerialPort = require('serialport');
//打开一个串口
let serialPort = new SerialPort('COM5', {
//波特率
baudRate : 115200,
autoOpen:false
});
app.post("/sendMsg",async (req,res)=>{
let {msg=''} = req.body;
//前端发送请求,后端接收到数据msg后,通过串口进行写入
serialPort.write(msg);
});
//连接串口后
serialPort.open(function (err) {
//连接串口后执行此方法
console.log('IsOpen:',serialPort.isOpen)
console.log('err:',err)
})
//指令监听
serialPort.on('data',async function (data) {
//接收到串口传递来的数据后,对数据处理
console.log('data received: '+data)
})
//错误监听
serialPort.on('error',function (error) {
console.log('error: '+error)
})
标签:console,log,nodejs,app,通信,serialPort,let,串口 来源: https://blog.csdn.net/gmh1118/article/details/117754024