Arduino JSON over Serial, Json.Parse returning Unexpected JSON input

Viewed 427

I am building a simple webpage that has data updated via JavaScript DOM manipulation. I want to receive the data from an Arduino, which I accomplished using serialize on Arduino and using SerialPort in node.js.

I am able to console.log the data that comes over the serial as one chunk, which is returned as follows.

{
    "day": "Friday",
    "temperature": 288,
    "humidity": 1099
}

From my research I figured I need to parse my Json object, but I am getting a

(node: 7759) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected end of JSON input at JSON.parse()....

I am very green on this subject, and any help pointing me in the right direction would ber very appreciated.

Node JS code

const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
const port = new SerialPort('/dev/cu.usbmodem14201', { baudRate: 9600 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));// Read the port data

port.on("open", () => {
  console.log('serial port open');
});
parser.on('data', data =>{
  str = data.toString();
  str = JSON.stringify(data);
  str = JSON.parse(data);

  console.log(str.day);
});

Arduino Code

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  myFunction();
  delay(5000);
}

int myFunction(){
   StaticJsonDocument<256> doc;
    int temp = 288;
    int humidity = 1099;
    
    doc["day"] = "Friday";
    doc["temperature"] = temp;
    doc["humidity"] = humidity;

    serializeJsonPretty(doc,Serial);
    Serial.println();
  }
1 Answers

I fixed it, thank you all for pointing me in the right direction. The problem was in my Arduino code. I was using static JSON which was not giving me a compressed string.

I switched it to dynamic, as found on the https://arduinojson.org/ documentation.

My Arduino changed to the following.

#include <ArduinoJson.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  myFunction();
  delay(5000);
}

int myFunction(){
    DynamicJsonDocument doc(260);
    
    int temp = 21;
    int humidity = 99;
    
    doc["day"] = "Monday";
    doc["temperature"] = temp;
    doc["humidity"] = humidity;

    serializeJson(doc,Serial);
    Serial.println();
  }
Related