Arduino Mega with ESP01 (AT commands) - lost wifi connection and not able to reconnect

Hello,
I have following setup for my curing chamber project:

I have issue with wifi connection. Everything is working fine, Arduino has connect to Blynk server and I can see all data in app.
But after some time the wifi connection is lost and is not reconnected automatically. Actually last run was for 8 hours till connection has been lost.
When the connection is down rest of application is still working.

A read many articles and forum posts to solve this issue, but nothing is working. I already tried following:

  • remove all code from loop void
  • upgrade Blynk and libraries version to last one
  • use soldered joints instead of connectors
  • change ESP01 module

I also tried to force lost wifi connection byl covering ESP01 by my hand and when it has been lost I remove my hand and it successfully reconnect to wifi.

Next what I tried was to check if arduino is connected to Blynk server and in other case to restart ESP by ESP.restart() and also call again Blynk.connect().

Nothing helps me.
Please give me sime next tip if you see something what I have wrong in my code.

Thank you

Ladis

Code:


#define BLYNK_PRINT Serial
#include <ESP8266_Lib.h>
#include "DHT.h"
#include <BlynkSimpleShieldEsp8266.h>

char auth[] = "***";
char ssid[] = "***";
char pass[] = "***";

// PINOUT
int dhtPin[] = {3,4}; // IN, OUT

int pinCooling = 8;
int pinHeating = 9;
int pinDrying = 10;
int pinHumidification = 11;
int pinFreshAir = 12;

// VARIABLES
float dhtH[2], dhtT[2];
float dhtHBuffer[2], dhtTBuffer[2];
boolean wifiConnected = false;
int bufferIndex = 0;
float temp = 0;
float hum = 0;
unsigned long waitFromTime = 0;
unsigned long lastFreshAirTime = 0;
unsigned long wifiLostTime = 0;
unsigned long wifiTimeout = 30000;
int wifiReconnecting = 0;

// Input variables
int tempMin = 0; // V100
int tempMax = 100; // V101
double tempDiff = 0; // V102
int humMin = 0; // V103
int humMax = 100; // V104
int humDiff = 0; // V105
int freshAirDuration = 0; // V106
int freshAirTimeout = 0; // V107
int bufferCount = 10; // V110
unsigned long waitAfterAction = 0; // V111

// Output variables
int cooling = 0;
int heating = 0;
int drying = 0;
int humidification = 0;
int waiting = 0;
int freshAir = 0;

WidgetLED coolingLed(V10);
WidgetLED heatingLed(V11);
WidgetLED dryingLed(V12);
WidgetLED humidificationLed(V13);
WidgetLED waitingLed(V14);
WidgetLED freshAirLed(V15);

WidgetTerminal terminal(V125);

DHT dht0(dhtPin[0], DHT21);
DHT dht1(dhtPin[1], DHT21);

ESP8266 wifi(&Serial2);
unsigned long startMillis;
unsigned long currentMillis;
boolean sendValues = false;

BlynkTimer timer;

void sendToBlynk()
{
  // Start sending data after buffer is filled
  if (sendValues) {
    if (!isnan(dhtT[0]) && dhtT[0] != 0) Blynk.virtualWrite(V0, dhtT[0]); // TEMP IN
    if (!isnan(dhtT[1]) && dhtT[1] != 0) Blynk.virtualWrite(V1, dhtT[1]); // TEMP OUT
    
    if (!isnan(dhtH[0]) && dhtH[0] != 0) Blynk.virtualWrite(V5, dhtH[0]); // HUM IN
    if (!isnan(dhtH[1]) && dhtH[1] != 0) Blynk.virtualWrite(V6, dhtH[1]); // HUM OUT

   if(cooling) coolingLed.on();
    else coolingLed.off();
   if(heating) heatingLed.on();
    else heatingLed.off();
   if(drying) dryingLed.on();
    else dryingLed.off();
   if(humidification) humidificationLed.on();
    else humidificationLed.off();
   if(waiting) waitingLed.on();
    else waitingLed.off();
   if(freshAir) freshAirLed.on();
    else freshAirLed.off();    
  }  

  sendValues = false;
}
void readSensors()
{
  // Read DHT 
    dhtHBuffer[0] = dhtHBuffer[0] + dht0.readHumidity();
    dhtTBuffer[0] = dhtTBuffer[0] + dht0.readTemperature();
    dhtHBuffer[1] = dhtHBuffer[1] + dht1.readHumidity();
    dhtTBuffer[1] = dhtTBuffer[1] + dht1.readTemperature();

    // count buffer
    bufferIndex++;
    if (bufferIndex >= bufferCount) {
      bufferIndex = 0;
      dhtH[0] = dhtHBuffer[0] / bufferCount;
      dhtT[0] = dhtTBuffer[0] / bufferCount;
      dhtH[1] = dhtHBuffer[1] / bufferCount;
      dhtT[1] = dhtTBuffer[1] / bufferCount;

      dhtHBuffer[0] = 0;
      dhtTBuffer[0] = 0;
      dhtHBuffer[1] = 0;
      dhtTBuffer[1] = 0;
      
      temp = dhtT[0];
      hum = dhtH[0];

      Serial.print("DHT0 Temperature value is: ");
      Serial.println(dhtT[0]);
      Serial.print("DHT0 Humidity value is: ");
      Serial.println(dhtH[0]);

      Serial.print("DHT1 Temperature value is: ");
      Serial.println(dhtT[1]);
      Serial.print("DHT1 Humidity value is: ");
      Serial.println(dhtH[1]);

      terminal.print("DHT0 Temperature value is: ");
      terminal.println(dhtT[0]);
      terminal.print("DHT0 Humidity value is: ");
      terminal.println(dhtH[0]);

      terminal.print("DHT1 Temperature value is: ");
      terminal.println(dhtT[1]);
      terminal.print("DHT1 Humidity value is: ");
      terminal.println(dhtH[1]);
      
      sendValues = true;
    }    
}

void doAction(){
      // Reset waiting
      if ( (millis() - waitFromTime) > waitAfterAction * 1000 ) waiting = 0;
      
      // Cooling
      if (waiting == 0 && temp > tempMax) {
        cooling = 1;                
        waitFromTime = millis();
      }
      if (cooling == 1 && temp <= (tempMax - tempDiff)) {
        cooling = 0;        
        waiting = 1;
      }

      // Heating
      if (waiting == 0 && temp < tempMin) {
        heating = 1;
        waitFromTime = millis();
      }
      if (heating == 1 && temp >= tempMin + tempDiff) {
        heating = 0;
        waiting = 1;
      }

      // Drying
      if (waiting == 0 && hum > humMax) {
        drying = 1;
        waitFromTime = millis();
      }
      if (drying == 1 && hum <= (humMax - humDiff)) {
        drying = 0;
        waiting = 1;
      }

      // Humidification
      if (waiting == 0 && hum < humMin) {
        humidification = 1;
        waitFromTime = millis();
      }
      if (humidification == 1 && hum >= (humMin + humDiff)) {
        humidification = 0;
        waiting = 1;
      }      

      // Fresh air
      if (freshAir == 0 && millis() >= (lastFreshAirTime + ((unsigned long)freshAirTimeout * 1000 * 60) ) ) {
        freshAir = 1;
        lastFreshAirTime = millis();
      }
      if (freshAir == 1 && millis() >= (lastFreshAirTime + ((unsigned long)freshAirDuration * 1000) ) ) {
        freshAir = 0;
        lastFreshAirTime = millis();
      }      
      
      // set relays
      if (cooling == 1) digitalWrite(pinCooling, LOW);
      else digitalWrite(pinCooling, HIGH);

      if (heating == 1) digitalWrite(pinHeating, LOW);
      else digitalWrite(pinHeating, HIGH);

      if (drying == 1) digitalWrite(pinDrying, LOW);
      else digitalWrite(pinDrying, HIGH);

      if (humidification == 1) digitalWrite(pinHumidification, LOW);
      else digitalWrite(pinHumidification, HIGH);

      digitalWrite(pinFreshAir, LOW);
      
      if (freshAir == 1) digitalWrite(pinFreshAir, LOW);
      else digitalWrite(pinFreshAir, HIGH);

      Serial.print("cooling value is: ");
      Serial.println(cooling);
      Serial.print("heating value is: ");
      Serial.println(heating);
      Serial.print("drying value is: ");
      Serial.println(drying);
      Serial.print("humidification value is: ");
      Serial.println(humidification);
      Serial.print("waiting value is: ");
      Serial.println(waiting);
      Serial.print("freshAir value is: ");
      Serial.println(freshAir);

      terminal.print("cooling value is: ");
      terminal.println(cooling);
      terminal.print("heating value is: ");
      terminal.println(heating);
      terminal.print("drying value is: ");
      terminal.println(drying);
      terminal.print("humidification value is: ");
      terminal.println(humidification);
      terminal.print("waiting value is: ");
      terminal.println(waiting);
      terminal.print("freshAir value is: ");
      terminal.println(freshAir);

}
void syncVariables(){
  
  // System info - Wifi status
  if (!wifiConnected && Blynk.connected()) {
    wifiConnected = true;
    Serial.println("Sync Virtual pins from server");
    terminal.println("Sync Virtual pins from server");
    // Temp
    Blynk.syncVirtual(V100,V101,V102);
    // Humidity
    Blynk.syncVirtual(V103, V104, V105);
    // Fresh air
    Blynk.syncVirtual(V106, V107);
    // System
    Blynk.syncVirtual(V110, V111);
  }
  if (wifiConnected && !Blynk.connected()) {      
      wifiConnected = false;
    }
  
}

BLYNK_WRITE(V100)
{
  tempMin = param.asInt(); 
  Serial.print("tempMin value is: ");
  Serial.println(tempMin);
}
BLYNK_WRITE(V101)
{
  tempMax = param.asInt(); 
  Serial.print("tempMax value is: ");
  Serial.println(tempMax);
}
BLYNK_WRITE(V102)
{
  tempDiff = param.asDouble(); 
  Serial.print("tempDiff value is: ");
  Serial.println(tempDiff);
}
BLYNK_WRITE(V103)
{
  humMin = param.asInt(); 
  Serial.print("humMin value is: ");
  Serial.println(humMin);
}
BLYNK_WRITE(V104)
{
  humMax = param.asInt(); 
  Serial.print("humMax value is: ");
  Serial.println(humMax);
}
BLYNK_WRITE(V105)
{
  humDiff = param.asInt(); 
  Serial.print("humDiff value is: ");
  Serial.println(humDiff);
}
BLYNK_WRITE(V106)
{
  freshAirDuration = param.asInt(); 
  Serial.print("freshAirDuration value is: ");
  Serial.println(freshAirDuration);
}
BLYNK_WRITE(V107)
{
  freshAirTimeout = param.asInt(); 
  Serial.print("freshAirTimeout value is: ");
  Serial.println(freshAirTimeout);
}
BLYNK_WRITE(V110)
{
  bufferCount = param.asInt(); 
  Serial.print("bufferCount value is: ");
  Serial.println(bufferCount);
}
BLYNK_WRITE(V111)
{
  waitAfterAction = param.asInt(); 
  Serial.print("waitAfterAction value is: ");
  Serial.println(waitAfterAction);
}

void setup()
{
  // Debug console
  Serial.begin(9600);
  delay(10);
  // Set ESP8266 baud rate
  Serial2.begin(115200);
  delay(10);

  // DHT
  dht0.begin();
  dht1.begin();

  // Relay
  pinMode(pinCooling, OUTPUT);
  pinMode(pinHeating, OUTPUT);
  pinMode(pinDrying, OUTPUT);
  pinMode(pinHumidification, OUTPUT);
  pinMode(pinFreshAir, OUTPUT);
  
  digitalWrite(pinCooling, HIGH); 
  digitalWrite(pinHeating, HIGH); 
  digitalWrite(pinDrying, HIGH); 
  digitalWrite(pinHumidification, HIGH); 
  digitalWrite(pinFreshAir, HIGH); 

 terminal.clear();

  terminal.println(F("Blynk v" BLYNK_VERSION ": Device started"));
  terminal.flush();

    
  Blynk.begin(auth, wifi, ssid, pass);      
  timer.setInterval(5000L, sendToBlynk);
  timer.setInterval(1000L, readSensors);
  timer.setInterval(5000L, doAction);
  timer.setInterval(10000L, syncVariables);  
}

void loop()
{
  Blynk.run();  
  timer.run();  
}

The ESP.restart() command only works if the sketch is running on the ESP device. In this case the sketch is running on a Mega, which only communicates with the ESP-01 by AT commands.
If you want to restart the ESP-01 then you’ll need to connect its RST pin to a pin on the Mega, and pull that pin LOW when you want to restart the ESP-01.
If you want to restart the Mega then you can use a similar technique, or try one of the documented soft reset techniques documented on the internet.

Personally, I wouldn’t try to read any DHT sensor more than once every 5 seconds, they are just too slow. I’d also add some NAN testing into the readSensors() routine BEFORE storing the values in your arrays.

This type of millis() comparison isn’t necessary if you use your BlynkTimers correctly.

Your syncVariables() function appears to be trying to mimick much of the functionality of the BLYNK_CONNECTED() function.

I’d also add some memory checking code, using freeMemory() to see how much dynamic memory you have available. I’d also use the “F Macro” in some of your Serial.print statements to free-up some memory.

Pete.

Hello Pete,
thank you for your reply.

I will leave restarting of ESP as last option. I still hope, this issue can be solved by software way.

I update read interval fo DHT to 5 seconds.
I think that the issue can your next point - testing NAN in readSensors(). In case of DHT returns nan , I am trying to tho number plus nan. This is not good.
This is first what changed and I am going to check if it works.

Thank you

Ladis

Really strange, it is still not working properly.

I tried following:

  • remove DHT and use SHT
  • remove all serial and terminal prints
  • set much longer timers
  • added testing nan values
  • remove syncVariables
  • checked memory by free memory - still same value of free memory also in time of freeze

Currently I am thinking about monitoring of this solution by other Arduino and check heart beat. My idea is to restart / power off and power on the solution in case of freeze.

I added new Blynk timer every one second and I switch bluild in LED every time. Standard it is blynking every second.

When the system freeze now the heart beat of internal LED is about 14 seconds in each state.
Application looks like working but it is very slow.

I tried to restart it by pushing build it button and nothing happens. Tried three times.

When I take power off for few seconds and again power on, it is working.

Actually is my idea to measure duration of heart beat by other Arduino and set some treshold to switch power.
But I still think, this must be some software issue and I hope there is some solution for it.

Any idea?

Thank you
Ladis

Impossible to say without seeing what you’ve done with your sketch.

TBH, you’d be far better off using an IoT enabled device such as a NodeMCU or ESP32 rather than struggling with an old and slow Arduino that was never built for this type of role.

Pete.

1 Like