npm 使用Node JS从串行端口获取体重秤数据

mspsb9vt  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(235)

我是新的节点js,我想从串行端口获得重量数据,我已经安装了节点js(v14.19.0)和npm(6.14.16),我想使用localhost:8080/get_weight获得重量数据,但脚本不工作,有人能帮助我吗?
下面是我的代码:

const http = require('http');
const hostname = 'localhost';
const { SerialPort, ReadlineParser } = require('serialport')
const { io } = require('socket.io')(3000);
const serialport = new SerialPort({ 
    path: '/dev/ttyS4',
    baudRate: 7500000 ,
})
const parser = new ReadlineParser()
serialport.pipe(parser)
/*serialport.on('data', console.log)  */

let express = require('express')
let app = express();

var port = 8080;

const server = http.createServer(app);

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
app.get('/get_weight', function(req, res) {
    serialport.on('open',function(){
        serialport.on('data', function(data){
            console.log('DATA:::::', data)
            const buf2 = Buffer.from(data)
            let wArray = buf2.toString('utf8');
            let wSlice = wArray.slice(3, wArray.length);
            let rawWeight = wSlice.slice(0, -3);
            let fWeight = rawWeight.trim();
            let weight = parseInt(fWeight);
            console.log(weight);
        });
    });
});
oaxa6hgo

oaxa6hgo1#

您的脚本仅处理从秤读取数据。但是,您还应向串行端口写入命令,只有这样您才能等待并接收数据。请阅读设备的用户手册,它应该有一个用于与之通信的接口。

相关问题