3

My node.js script uses the serialport npm package to read and write to COM5 port, which is connected to an RS-232 device. This device only writes to the serial port when it receives a command sent by the PC connected to it.

How can I read what is returned by the RS-232 device after writing to it?

var SerialPort = require('serialport');
var port = new SerialPort('COM5', {
    parser: SerialPort.parsers.readline('\r')
}, function() {
    port.write('#01RD\r', function(err) {
        if(err)
            console.log('Write error')
        else {
            // HOW TO READ RESPONSE FROM DEVICE?
        }
    });
    port.write('#01VER\r', function(err) {
        if(err)
            console.log('Write error')
        else {
            // HOW TO READ RESPONSE FROM DEVICE?
        }
    });
});     

1 Answer 1

0

I think this is a better way to do it. By function calling, first create your function of reading and writing:

var serialport = require("serialport");
var SerialPort = serialport.SerialPort;

var sp = new SerialPort("/dev/ttyACM0", {
  baudrate: 9600,
  parser: serialport.parsers.readline("\n")
});

function write() //for writing
{
    sp.on('data', function (data) 
    {
        sp.write("Write your data here");
    });
}

function read () // for reading
{
    sp.on('data', function(data)
    {
        console.log(data); 
    });
}

sp.on('open', function() 
{
    // execute your functions
    write(); 
    read(); 
});
Sign up to request clarification or add additional context in comments.

3 Comments

I have a button on a UI that the user clicks on to initiate a serial write. How should I handle this read/write using an event driven approach?
I see, so we are doing the same thing. Im now in that part too. And they say we can use Express for this. Check my thread stackoverflow.com/questions/41647971/…
Your read/write function create a event emitter memory leak.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.