How to reconnect wifi Arduino Mega and ESP8266 module after reset router

Hello, I am doing a project to control my aquarium with Blynk.

I am testing the wifi connection to be sure it works fine.but, if I restart the router it doesn’t
reconnect itself.

• Hardware model + communication type. Arduino Mega + ESP8266 module
• Smartphone OS (iOS or Android) + version
• Blynk server
• Blynk Library version: last


void loop() {

    isConnected = Blynk.connected();
       if (isConnected == true) {
        
    // Serial.println("Conectado");    

    contador_global ++;  //   Serial.print(contador_global);
 
    
    if (contador_global == 50) {
    Serial.println(isConnected);
    blynk();             // envia valores de las variables de arduino a blynk
    check_temp();        // Comprueba valores temperatura
    check_ventilador();  // Comprueba si activa ventilador
    check_calentador();  // Comprueba si activa el calentador
    getDHT();            // lee sensor dth   
    contador_global = 0;
    }
    /////////////////////////////////////////////////////
   
    check_UV();           // Comprobamos horario para encender UV
    check_ai();           // Comprobamos horario para encender AIREADOR
    check_nivel();       // Comprobamos el nivel del agua
  //  envio_datos();     // Enviamos datos a thingspeak
    Blynk.run();        // Aplicacion Blynk
    timer.run();
         
     }
     
  if (isConnected == false){

    
  //  Blynk.tweet("Pierde conexion y reconecta www.atorcha.es");
    Serial.println(isConnected);
    Serial.println("Reconectando...");
    Serial.println(" Espero 5 segundos.");
    delay(5000);
    tweet_enviado = false;
    Serial.println("Serial.begin... ");
    Serial.begin(9600);
    delay(10); 
    Serial.println("EspSerial.begin... ");
     // Set ESP8266 baud rate;
    EspSerial.begin(ESP8266_BAUD);
    delay(10);
   
   Serial.println("blynk.begin... ");
   Blynk.begin(auth, wifi, ssid, pass);    
        
  }

And Serial show that:

   ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.5.4 on Arduino Mega

[610] Connecting to atorcha
[3659] AT version:1.2.0.0(Jul  1 2016 20:04:45)
SDK version:1.5.4.1(39cb9a32)
Ai-Thinker Technology Co. Ltd.
Dec  2 2016 14:21:16
OK
[10791] +CIFSR:STAIP,"192.168.1.5"
+CIFSR:STAMAC,"5c:cf:7f:f6:8a:2b"
[10799] Connected to WiFi
[21009] Ready (ping: 11ms).
V1 modo_ai value is: 3
V2 modo_uv value is: 1
V30 modo_relleno value is: 1
V41 modo_temp uv value is: 0
V40 modo_ai value is: 0
Temp Deseada blynk: 24.50
[21884] Time sync: OK
Falta el sensores de temperatura del agua
Falta el sensores de temperatura de la tapa
Falta el sensores de temperatura de la habitacion
Test the serial monitor!
1
Envía tweet
1
1
0.   **HERE I PRESSED THE ROUTER BUTTON AND ROUTER RESTARTS**
Reconectando...
 Espero 5 segundos.
Serial.begin... 
EspSerial.begin... 
blynk.begin... 
[77007] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.5.4 on Arduino Mega

[77646] Connecting to atorcha
[80697] AT version:1.2.0.0(Jul  1 2016 20:04:45)
SDK version:1.5.4.1(39cb9a32)
Ai-Thinker Technology Co. Ltd.
Dec  2 2016 14:21:16
OK
[90809] Failed to connect WiFi

When it changes to 0 is the moment I reset the router.

And it finish here.

1 Like

Not sure about the connection issue, but you may want to take a look at this:

1 Like

thanks, but when I start my sketch it works fine, as you see in code it only sends data to Blynk every 50 loops ( contador_global==50)
The problem is when I turn OFF the router and turn ON again. then it show in serial port “[90809] Failed to connect Wifi” and code stops.

I think that I SOLVED it changing

Serial.println("blynk.begin… ");
Blynk.begin(auth, wifi, ssid, pass);

by

Serial.println("blynk.begin… ");
Blynk.connect();

You should take head of what @Toro_Blanco has said - he knows what he’s talking about.

Your :fish: :fish: :fish: will thank you for it in the end.

Pete.

OK and I read the article but in my loop only check different sensors of my aquarium, and only every 60 seconds it send data to Blynk,

Okay, you know best!

Pete.

According to the link I had posted, a simple void loop() can run up to 117,000 times per second. So even only sending data to blynk every 50 loops can be up to 2350 times per second (117,000/50) (although I am sure much less in your case do to the other tasks, but still a lot).

Additionally, It is not only about how often you send the data to blynk, but also about the device (esp) staying connected to the blynk server.

If the time it takes to read/check all of the sensors is short you may not have an issue. If there is too much time between the Blynk.run(); commands, then you will have connection issues. That is why it is suggested that you keep the void loop() to a minimum, and also not use any delay();'s anywhere in your code (which I am not sure if you have/have not as you only posted a portion of your code).

1 Like

Thanks, yes my code is bigger, It has to ches many parameters, but I changed now the code and it sends data to Blynk every 30 seconds.
But anyway I had modified my code and now it is:


void loop() {

    isConnected = Blynk.connected();
       if (isConnected == true) {
         Blynk.run();        // Aplicacion Blynk
         timer.run();        
     }
     
  if (isConnected == false){
    
     // ############## Inicio "pantalla error" ####### 
     u8g.firstPage(); 
     do { 
      p_error();
     } while( u8g.nextPage() ); 
    // ############## Fin "pantalla error" ########## 
    
  //  Blynk.tweet("Pierde conexion y reconecta www.atorcha.es");
    tweet_enviado = false;  
    Serial.println(isConnected);
    Serial.println("Reconectando... Espero 30 segundos.");
    delay(30000);
  
   Serial.println("Envia blynk.connect... ");
   Blynk.connect();
   //Blynk.begin(auth, wifi, ssid, pass);           
  }  
}

this in setup:

  timer.setInterval(60000L, SendToThingspeak);  // envia dato cada minuto a thingspeak
  timer.setInterval(30000L, blynk); //timer will run every 30 sec a blynk
  timer.setInterval(20000L, check_1); //timer will run every 20 sec
  timer.setInterval(10000L, check_2); //timer will run every 10 sec 

and this:

void check_1(){
  
    check_temp();        // Comprueba valores temperatura
    check_ventilador();  // Comprueba si activa ventilador
    check_calentador();  // Comprueba si activa el calentador
    getDHT();            // lee sensor dth
    tweeter();           // envia tweet si está conectado.

    // ############## Inicio "picture loop" ####### 
     u8g.firstPage(); 
     do { 
      draw();
     } while( u8g.nextPage() ); 
   // ############## Fin "picture loop" ########## 
  
}

void check_2(){
  
    check_UV();           // Comprobamos horario para encender UV
    check_ai();           // Comprobamos horario para encender AIREADOR
    check_nivel();       // Comprobamos el nivel del agua 
}

But I don’t know how to wait 30 seconds in each retry to connect without a “delay”

You need to stager these… the way they are some or all will converge (trying to run their respective functions at the exact same time) every 20, 60 seconds at least.

With a timeout timer… for an example of such use…

1 Like

As @Gunner mentioned, use a timeout timer.

 // Timed Lambda Function - 
  timer.setTimeout(30000L, []() {  // Run every 30 seconds
     Serial.println("Envia blynk.connect... ");
     Blynk.connect();
  });  // END Timer Function

I did modifications in my code, with upper tips but It runs worst. It was all the night losing connection.

I dont know if it was by timeout.timer or what else.