0

SERIAL COMMUNICATION ARDUINO ESP8266 (Node MCU)

What is this project about?

In this project i built a serial communication between an ArduinoMega and a NodeMCU. Arduino Mega sends data packages (serialized with Json) to NodeMcu. NodeMcu deserializes and uploads data to MySQL Database.

Wiring Diagramm:

On the Arduino Mega side we are using the 2nd Serial port. On the receiving end (node Mcu) we use a different approach. As you can see we connect the Rx2 Tx2 of the Arduino to Digital Pin D5 (16 ->D5) / (17-> D6). Node Mcu has 2 Uarts but the 2nd Uart is used to flash the chip and cannot be used to receive data. The first UART is used by the computer USB to read/debug the software during runtime. So we choose the ESP-Software-Serial Libary to realize a 2nd Uart Port. (https://github.com/plerup/espsoftwareserial)

I used the following Libarys:

Arduino Code (Sender):

#include <ArduinoJson.h>

StaticJsonDocument<1024> doc;

// If you want to calculate the exact amount of buffer size:
// https://arduinojson.org/v5/assistant/

doc["temp1"] = temp1;
doc["temp2"]   = temp2;
doc["temp3"]   = temp3;

serializeJson(doc, Serial2);
// Using Serial 2 port of Mega, S1 is used for USB connection.

Node MCU Code/ESP8622 (Receiver):

#include <SoftwareSerial.h>
SoftwareSerial s(D5,D6);
void setup() {
  // Initialize ports
  Serial.begin(9600);
  s.begin(9600);
}
void loop() {
// Flushing Serial input buffer
while (s.available())
  s.read();

// Waiting for a JSON document in Serial
while (!s.available())
 { delay(50);}


          StaticJsonDocument<1024> doc;
          deserializeJson(doc, s);
          auto error = deserializeJson(doc, s);
          serializeJsonPretty(doc, Serial);

        if (error) {
            //Serial.print(F("deserializeJson() failed"));
            Serial.println(error.c_str());
            return;
        }

        temp1 = doc["temp1"];
        temp2 = doc["temp2"];
        temp3 = doc["temp3"];
}

It´s not the full code, but you get the idea how this stuff works. Json really made this project way easier. At first i tried to handle the data transfer by using serial.write but somewhere in the middle of the journey i discovered Json. It made me rethink the idea of transferring data arrays via serial write which can be real pain in the a**

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.