0

Arduino code:

I'm trying to send json structure data with three values

#include <dht.h>
#include <ArduinoJson.h>

DHT d = DHT();

int avalue=0;

void setup() {
  Serial.begin(9600);
  while (!Serial) continue;

  d.attach(A0);
  delay(1000);
}

int data[3];

void loop() {
  d.update();

  data[0] = analogRead(A1);
  data[1] = d.getTemperatureInt();
  data[2] = d.getHumidityInt();
  StaticJsonBuffer<200> jsonBuffer;

  JsonObject& root = jsonBuffer.createObject();

  root["Moisture"] = data[0];
  root["Temperature"] = data[1];
  root["Humidity"] = data[2];

  Serial.println();
  root.prettyPrintTo(Serial);
}

Here you can see output of arduino

I need to get data on NodeJs

My problem is that i can not get data in json

What options do I have?

Or how can I solve this problem?

I'm trying read data by SerialPort

Node Js code:

var express = require('express');
var app = express();
var SerialPort = require('serialport');
var firebase = require('firebase');
var port = new SerialPort('COM4', {
  baudRate: 9600
});

var Readline = SerialPort.parsers.Readline

var parser = new Readline()
port.pipe(parser)

parser.on('data', function (data) {

    console.log(data);
})

Here you can see output of node server

But when I'm trying to get child data I'm receiving undefined

console.log(data.Temperature);

undefined value

1 Answers1

2

In node js you should firstly:

1)Convert to string

2)And remove '\r' from this String

3)Convert to JSON

4)Then parse it

parser.on('data', function (data) {
    str = data.toString(); //Convert to string
    str = str.replace(/\r?\n|\r/g, ""); //remove '\r' from this String
    str = JSON.stringify(data); // Convert to JSON
    str = JSON.parse(data); //Then parse it

    console.log(str.Moisture);
    console.log(str.Temperature);
    console.log(str.Humidity);


})

Leave the rest of the code unchanged

  • that can’t possibly be correct. lines 1-4 of the function overwrite `str` repeatedly, meaning only line 4 does anything. – James Jan 29 '21 at 13:35