0
votes

I have uploaded the firebase code in NodeMCU(esp8266) and its fully functional. I have connected arduino uno with nodemcu using Rx, Tx pins. When I get values from sensors and transfer it to nodeMCU. I get half junk values and half correct values. The length of junk keeps on changing, I get perfect value once while its full of junk the other time.

I tried changing baud rates but it didn't work. I came across 2 different baud rates for nodeMCU and arduino.

SoftwareSerial ESP(0,1);
  void setup() {
  ESP.begin(9600);
}
void sendStatus(bool dish, byte gas, int knob, unsigned long alarmIn) {
  DynamicJsonDocument status(50);
  status["K"] = knob;
  status["G"] =  gas;
  status["D"] = dish;
  status["A"] = alarmIn;
  String statusString;
  serializeJson(status, statusString);
  Serial.println(statusString);
  ESP.println(statusString);
}

void readSerial() {
  if (!ESP.available()) return;
  String cmd = "";
  while (ESP.available()) {
    char ch = (char)ESP.read();
    if (ch != 10 && ch != 13) cmd += ch;
    if (ch == '}')
      break;
    delay(1);
 }
while (ESP.available()) {
  ESP.read();
  delay(1);
}                               // for arduino uno

I expected to get the full string but i get last 50-70% of string while the first part gets as junk values. Need to get full string which I am able to see in arduino's serial monitor.

1

1 Answers

1
votes

I can't see a major problem with your code but it seems that you have some memory problem or a faulty serial communication, so I give you some tips maybe it can help:

First, in sendStatus function make sure that DynamicJsonDocument status(50); is large enough to hold your values especially if you are adding large numbers.

Also according to docs:

You can choose to store your JsonDocument in the stack or in the heap:

Use a StaticJsonDocument to store in the stack (recommended for documents smaller than 1KB)

Use a DynamicJsonDocument to store in the heap (recommended for documents larger than 1KB)

So I think using StaticJsonDocument as a global variable with a JsonObject is a better choice since your Json object is not too large and has static keys.

Second, for readSerial I suggest you use a simpler function like readString instead of reading bytes with a delay.

SoftwareSerial ESP(0, 1);
StaticJsonDocument<100> status;
JsonObject object;

void setup()
{
    ESP.begin(9600);
    Serial.begin(9600);
    object = status.to<JsonObject>();
}

void sendStatus(bool dish, byte gas, int knob, unsigned long alarmIn)
{
    object["K"] = knob;
    object["G"] = gas;
    object["D"] = dish;
    object["A"] = alarmIn;
    char statusString[100];
    serializeJson(status, statusString);
    Serial.println(statusString);
    ESP.println(statusString);
}

void readSerial()
{
    String cmd;
    while (ESP.available())
    {
        cmd = ESP.readString();
        Serial.println(cmd);
    }
}

void loop()
{
    sendStatus(...);
    readSerial();
    delay(1000);
}