0

I am using an Arduino Uno and a DTH11 temperature sensor to read temperature and then send that value to a computer via the serial port.

A NodeJS application is running on the computer and captures that value and writes to a log file.

When I try to get values from my NodeJS application, sometimes the value is broken into two values. Eg: 25 -> 2 and 5

This is my Arduino code:

dht DHT;
#define DHT11_PIN 7
float tem [4];
void setup() {
 Serial.begin(9600);
 pinMode(12, OUTPUT); 
}
void loop() {
 int chk = DHT.read11(DHT11_PIN);
 int val = (int)(DHT.temperature);
 Serial.println(val);
 delay(600000);
}

This is my NodeJS program.

var fs = require('fs')
var logger = fs.createWriteStream('/data/Temperature/temperature.csv', {
 flags: 'a' // 'a' means appending (old data will be preserved)
})
var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM0", {
 baudRate: 9600,
});
serialPort.on("open", function () {
 serialPort.on('data', function(data) {
 var moment = require('moment');
 var dayTime = moment().format('YYYY-MM-DD,hh:mm');
 var val1 = data.toString();
 var val = val1.trim();
 if (val == '') {
 console.log('no data');
 else {
 console.log(val);
 logger.write(dayTime + ',' + val + '\n');
 }
 });
});

Is it a problem with my code?

Thanks in advance.

dda
1,5951 gold badge12 silver badges17 bronze badges
asked Nov 20, 2017 at 9:31
3
  • 1
    You assume that all the serial data will arrive in one packet. That's is not the case most of the time. You need to code to read data char by char and reconstruct the value in the receiving side. Commented Nov 20, 2017 at 9:36
  • @LookAlterno yes, sometimes its getting data properly. So how I can get char by char? Commented Nov 20, 2017 at 9:39
  • 1
    You concatenate parcial readings until reaching a delimiter that signal you the end of the data. I think something like val1 = val1 + data.toString(). Maybe. I don't program in Javascript nor PHP. Commented Nov 20, 2017 at 9:44

1 Answer 1

1

As Look Alterno wrote in a comment, you need to parse the incoming data on the receiving side. In this instance, you have to look for the line terminators. The Node.js serialport module provides a parser for this called Readline. Read that doc and use it.

answered Nov 20, 2017 at 9:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.