简体   繁体   中英

Serial read node js

I do need to get the weight of an balance that`s connected to my computer at a serial port, but when I get the data from the device it returns me a Buffer Array

The documentation of the balance says that the return is: [STX][PPPPPP][CR] Where PPPPPP is the weight coming from the balance.

This is the return :

Buffer(8) [24, 24, 0, 24, 24, 24, 152, 248]
Buffer(8) [24, 158, 0, 0, 24, 24, 24, 24]
Buffer(8) [248, 0, 120, 24, 24, 24, 24, 24]

This is my code:

let SerialPort = require('serialport');
let port = new SerialPort('/dev/tty.usbserial', { autoOpen: false });

SerialPort.list(function (err, ports) {
    ports.forEach(function(port) {
        console.log(port.comName);
    });
});

port.open(function (err) {
    if (err) {
        return console.log('Error opening port: ', err.message);
    }
});

// The open event is always emitted
port.on('open', function() {
    console.log('Open Port');
});

const ByteLength = SerialPort.parsers.ByteLength;
const parser = port.pipe(new ByteLength({length: 8}));
parser.on('data', function (data) {
    console.log('Data: ', data);
});

This is the longer that I could reach with info the internet once that I know nothing about Serial reading, any one can explain what or how I can make this data "readable" ?

Other info that may be useful about the serial device: 1 Stop Bit; 8 Bits of data; No parity.

I had almost the same exact issue and I am also working with a scale/balance to read data over a COM serial port. What ended up fixing my issue was changing port settings when newing up the node serialport and the settings in the device manager for the COM port.

According to the the device manual (Ohaus Navigator XT) it defaults to 2400 baud, 7 bit, no parity, no handshake and I changed the port settings in the Device Manager (windows 10) for that COM port on my machine to match. (Using their software I was able to read data coming from the balance but it came over as garbage data when I ran the serialport code.)

Changing the settings in the device manager back to the windows defaults (9600 baud, 8 bit no parity, 1 stop bits, flow-control: none) and then matching those values when newing up the serial port AND changing the settings on the device to match these settings allowed readable data to come through with no conversion in the code.

const SerialPort = require('serialport')
const Readline = SerialPort.parsers.Readline
const port = new SerialPort('COM3', { 
    baudRate: 9600, 
    databits: 8, 
    parity: 'none', 
    stopBits: 1, 
    flowControl: false
})
const parser = new Readline()
port.pipe(parser)
parser.on('data', data => console.log(`data: ${data}`)) // data:    26.0 g

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM