MQTT > jsonobject version 6 (Think Buffer problem)

Hey guys,

I have a Wemos D1 Mini that got a LDR on it’s A0 pin connected.
Now I’m looking at my Serialmonitor and for the first seconds everything seems to work fine until my A0 measurements fill my Serialmonitor from top to bottom and much much more :smiley:

I think that is because I didn’t understand the correct useage of creating json objects and send them over mqtt.

A part of my sketch looks like this:

void LDRsensorReadout(unsigned long LDR_EFFECT_TIMER)
{
  if ((millis() - LDRsensor_delayStart) >= LDR_EFFECT_TIMER) {
    LDRsensor_delayStart += LDR_EFFECT_TIMER;
    int l = analogRead(A0);

    if (isnan(l)) {
      if (debug) {
        Serial.println((String)"[LDR] Failed to read Light Sensor" + l);
      }
    } else {
      if (debug) {
        Serial.println((String)"[LDR] Light: " + l);
      }
      DynamicJsonDocument json(1024);
      JsonObject object = json.createNestedObject("sensor");
      JsonObject ldr = object.createNestedObject("ldr");
      ldr["light"] = l;
      char buffer[512];
      serializeJson(json, buffer);
      client.publish(mqtt_pub_topic, buffer);
    }
  }
}

void loop()
{
  mqttConnection();
  LDRsensorReadout(LDRTimer);


  if (LEDswitch) {
    LED_effect();
  }
}

As you can see I call my LDR void from the loop. The LDRTimer is set to 60 seconds.
I think the problem belongs to the dynamic jsondocument with that high 1024 and the char buffer 512.

I tested much lower values but that didn’t change anything :frowning:

What you have to know is that I’m using those lines 2-3 times in my sketch for other variables and they are everytime coded with the same values. I googled a lot but unfurtunately I can’t find anything helpfull. Most posts are for json version 5 and not version 6.

The most json object creations are looking like this:

    DynamicJsonDocument json(1024);
    json["status"] = "reconnected";
    json["switch"] = SWITCH;
    json["effect"] = EFFECT;
    json["speed"] = DELAY_TIME;
    json["subTopic"] = mqtt_sub_topic;
    JsonObject object = json.createNestedObject("color");
    object["h"] = hue;
    object["s"] = sat;
    object["v"] = bri;
    char buffer[512];
    serializeJson(json, buffer);
    client.publish(mqtt_pub_topic, buffer);
    client.subscribe(mqtt_sub_topic);

The attachment is a screen of my Serialmonitor.

I hope anybody can help me to understand that json object thing with mqtt :confused:

Think I found a solution by try and error?

I just changed 'json' to 'jsonLDR' so it has its own json document.
Maybe that was what I'm doing wrong.

Everywhere I create a new json document with the same name.

Can anyone confirm that?

EDIT: Mhhh maybe I have to clear the json buffer everytime I sent the json over mqtt and then create it again?