简体   繁体   中英

Separating data obtained from node serial port

I am using an arduino to obtain values from different sensors and printing these values(eg temperature and moisture).

serial.println(tempval);
serial.println(moistval);

I want to separate the data that I obtain from node-serial port so that I can clearly define the temperature and moisture values in node.

Here is my NodeJS code:

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

var portName = process.argv[2];


var myPort = new SerialPort(portName,{
   baudRate:9600,
   parser: serialport.parsers.readline('\n')

});

myPort.on('data', function (data) {
  console.log('Data: ' + data);
});

I think that I should arrays but I cannot implement.Any suggestions on how I can do this?

Thanks in advance!

You should ask the Arduino to tell what kind of data it is sending, not only the raw data itself. For example:

Serial.print(F("temperature: "));
Serial.println(tempval);
Serial.print(F("moisture: "));
Serial.println(moistval);

Then your Node.js code can parse each line as a name:value pair. You can make this parsing simpler by having the Arduino format the line as JSON.

Also, if you happen to have both pieces of data available at the same time, then you can send them both in the same line. This can make things slightly simpler. Arduino side:

Serial.print(F("{\"temperature\": "));
Serial.print(tempval);
Serial.print(F(", \"moisture\": "));
Serial.print(moistval);
Serial.println(F("}"));

Node.js side:

myPort.on('data', function (data) {
  console.log(JSON.parse(data));
});

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