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.

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.
    – user31481
    Nov 20, 2017 at 9:36
  • @LookAlterno yes, sometimes its getting data properly. So how I can get char by char? 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.
    – user31481
    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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.