Arduino Mega+ESP8266 code not working

So, i have a Arduino Mega Wi-fi that's integrated with a ESP8266: Arduino MEGA 2560 ESP8266 WIFI · MohanadSinan/IoT-Based-Healthcare-System Wiki · GitHub

#include <ESP8266WiFi.h>

const char* ssid     = "sua-rede";
const char* password = "sua-senha";

WiFiServer server(80);
String header;

unsigned long currentTime = millis();
unsigned long previousTime = 0;
const long timeoutTime = 2000;

String temperatura = "--";
String umidade = "--";

void setup() {
  Serial.begin(115200);
  Serial3.begin(9600);
  delay(5000);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi conectado.");
  Serial.println("IP: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop() {
  if (Serial3.available()) {
    String data = Serial3.readStringUntil('\n');
    int separator = data.indexOf(',');
    if (separator > 0) {
      temperatura = data.substring(0, separator);
      umidade = data.substring(separator + 1);
    }
  }

  WiFiClient client = server.available();   
  if (client) {                             
    String currentLine = "";                
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) {
      currentTime = millis();
      if (client.available()) {             
        char c = client.read();             
        header += c;
        if (c == '\n') {                    
          if (currentLine.length() == 0) {  
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println("h1,p {font-weight: bold;color: #126e54; font-size: 32px;}");
            client.println("p {font-size: 16px;}");
            client.println("</style></head>");

            client.println("<body><h1>Arduino Mega WiFi Web Server</h1>");
            
            client.println("<h2>Dados do Sensor</h2>");
            client.println("<p>Temperatura: " + temperatura + " °C</p>");
            client.println("<p>Umidade: " + umidade + " %</p>");
            
            client.println("</body></html>");
            client.println();
            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
        }
      }
    }
    header = "";
    client.stop();
  }
}

This is for the ESP8266

#include <DHT.h>

#define DHTPIN 22  // Pino do DHT11
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  Serial3.begin(115200);
  dht.begin();
}

void loop() {
  float temperatura = dht.readTemperature();
  float umidade = dht.readHumidity();

  if (!isnan(temperatura) && !isnan(umidade)) {
    Serial.print("Temperatura: ");
    Serial.print(temperatura);
    Serial.print(" °C, Umidade: ");
    Serial.print(umidade);
    Serial.println(" %");

    // Envia os dados via Serial3 para o ESP8266 no formato "temperatura,umidade"
    Serial3.print(temperatura);
    Serial3.print(",");
    Serial3.println(umidade);
  } else {
    Serial.println("Falha ao ler do sensor DHT11!");
  }

  delay(2000); // Aguarda 2 segundos antes da próxima leitura
}

And that's for the Arduino Mega

Initially i have them both to Serial3, but for some reason the IDE dosen't let me use Serial3. The server is running and the Arduino Mega is collecting the information, however the Arduino Mega is not sending to the ESP code, i really don't know what to do. Please help!

esp8266 doesn't have Serial3

I know, them how i use serial communication to send the data that the Arduino Mega collected to the ESP?

over Serial on the esp8266 side

Like this?

#include <DHT.h>

#define DHTPIN 22  // Pino do DHT11
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
    Serial.begin(9600);   // Debug no PC
    Serial1.begin(9600); // Comunicação com ESP8266
    dht.begin();
}

void loop() {
    float temperatura = dht.readTemperature();
    float umidade = dht.readHumidity();
    
    if (!isnan(temperatura) && !isnan(umidade)) {
        Serial.println("Temp");
        Serial3.print(temperatura);
        Serial3.print(",");
        Serial3.println(umidade);
    }

    delay(2000);
}

The ESP:

#include <ESP8266WiFi.h>

int postmessage = 0;

void setup() {
    Serial.begin(115200);   // Debug no PC
}

void loop() {
  if (Serial.available() > 0) {
    postmessage = Serial.parseFloat(); // read the incoming byte:
    Serial.print(" I received:");
    Serial.println(postmessage);
  }
}

you must know to which Serial of Mega you wired the esp8266

Is there a real reason to use an Arduino Mega?

Do you need a lot of IO-pins or a lot of ADC-inputs or pwm-channels?

If all not, I would change to a ESP32 stand-alone. This eliminates the hassle of serial communication between Mega and ESP

I will suggest to follow this page
Serial | Arduino Documentation

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.