Reputation: 87
I am using an arduino to obtain values from different sensors and printing these values(e.g 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!
Upvotes: 1
Views: 1756
Reputation: 3566
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));
});
Upvotes: 2