Code to Re-Connect Blynkserver Automatically

Issue: Sometimes the hardware(eg. Nodemcu) doesn't connect to router automatically, when there is a break in connection.




Solution: 
In this we'll add a timer. When there is no connection, the timer will start and try to reconnect in every specified time interval. to make this happen we need a library called as simple timer.
Extract this library to the library folder in Arduino folder in my documents.

Write the  following code:

#include <SimpleTimer.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

SimpleTimer timer;    //Creating simple timer variable 

char auth[] = "MxLDc********************KtUI";

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

void setup()
{
  
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(10000, reconnectBlynk); //Setting interval to 10 seconds to Run function"reconnectBlynk"
}

void reconnectBlynk() {
  if (!Blynk.connected()) {
    if(Blynk.connect()) {
      BLYNK_LOG("Reconnected");
    } else {
      BLYNK_LOG("Not reconnected");
    }
  }
}
void loop()
{
  
  if (Blynk.connected()) {
    Blynk.run();
  }
  if (!Blynk.connected()) {
    timer.run();
  }
}

No comments:

Post a Comment