0

I have a problem, I am trying to get the weight from a Scale with NodeJS and the npm module "Serialport" on Windows.

The problem that I have is that it doesn't matter the command that I sent to the Scale, it is not return any data.

I already compiled the module serialport for the project that I am making on nwJS, and I have the following code:

    var SerialPort = require('serialport');

            var port = new SerialPort('COM4', {
                parser: SerialPort.parsers.readline('W\n'),
                baudRate: 9600,
                dataBits: 7,
                stopBits: 1,
                parity: 'even',
                bufferSize: 1024
            });

function write() {
            port.open(function(err) {
                console.log("Writing serial data: ");
                port.on('data', function(data) {
                    console.log('Data: ' + data);
                });
                port.write(resultString, function(err, res) {
                    if (err) {
                        console.log(err);
                    }
                    port.close();
                });
            });
        }
    port.on('error', function(err) {
                console.log('Error: ', err.message);
            })
            setTimeout(write, 1000);

Note: the parser W\n is the string that the scale needs to sent the weight. I tested that with another application named coolterm

Thanks for any help.

4

2 回答 2

1

Most probably the issue is with parser's config. Instead of a ReadLine parser:

 parser: SerialPort.parsers.readline('W\n'),

Try a Delimiter parser :

var weight_parser = port.pipe(new Delimiter({delimiter: new Buffer('W\n')}));
...
parser: weight_parser,
...
parser.on('data', console.log);

If that does not work, to troubleshoot try a ByteLength parser to see if 'data' event is getting fired or not.

于 2016-10-02T12:50:10.923 回答
1

In my case

1) I am using hapi JS 
2) Using latest serialport package version - 6.2.2 
3) Using Essae weighing machine connected to the port '/dev/ttyUSB0'

Below code is working perfectly and giving correct result once item weight is stabilised(Not varing).

"use strict";
const serialport = require('serialport');
const Readline = require('@serialport/parser-readline')

const getweight = {
  auth:false,
  handler: function(req, res)
  {
    const port = new serialport('/dev/ttyUSB0')
    const parser = port.pipe(new Readline({ delimiter: '\r\n' }))
    parser.on('data', function(w)
    {
      port.close();
      return res({
        weight: w.replace(/[^\d\.]*/g, '').trim()
      });
    });
  }
};

exports.routes = [
  {
    method: 'get',
    path: '/getweight',
    config: getweight,
  },
];
于 2018-08-08T07:19:09.660 回答