#9 Basic “Keeps running without WiFi or Blynk Server connection, but reconnects as soon as they are available” sketch
Simply does what the title says… Flashes the built in LED and sends UpTime data to both App and Serial monitor to show operation either way. Also has a lot of serial print commands to show general operation for troubleshooting… Remove them when you are comfortable that everything works for you.
#define BLYNK_PRINT Serial // This prints to Serial Monitor
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <ESP8266mDNS.h> // For OTA
#include <WiFiUdp.h> // For OTA
#include <ArduinoOTA.h> // For OTA
char auth[] = "xxxxxxxxxx";
char ssid[] = "xxxxxxxxxx";
char pass[] = "xxxxxxxxxx";
//char server[] = "xxx.xxx.xxx.xxx"; // IP for Local Cloud Server
char server[] = "blynk-cloud.com"; // URL for Blynk Cloud Server
int port = 8080;
int DeviceLED = 2;
int ReCnctFlag; // Reconnection Flag
int ReCnctCount = 0; // Reconnection counter
BlynkTimer timer;
void setup() {
Serial.begin(115200);
pinMode(2, OUTPUT);
WiFi.begin(ssid, pass); // Non-blocking if no WiFi available
Blynk.config(auth, server, port);
Blynk.connect();
timer.setInterval(1000L, UpTime);
ArduinoOTA.setHostname("Loss of connection test"); // For OTA
ArduinoOTA.begin(); // For OTA
}
BLYNK_CONNECTED() {
Serial.println("Cconnected");
ReCnctCount = 0;
}
void UpTime() {
Blynk.virtualWrite(V0, millis() / 1000); // Send UpTime seconds to App
Serial.print("UpTime: ");
Serial.println(millis() / 1000); // Send UpTime seconds to Serial
digitalWrite(DeviceLED, !digitalRead(DeviceLED)); // Blink onboard LED
}
void loop() {
timer.run();
ArduinoOTA.handle(); // For OTA
if (Blynk.connected()) { // If connected run as normal
Blynk.run();
} else if (ReCnctFlag == 0) { // If NOT connected and not already trying to reconnect, set timer to try to reconnect in 30 seconds
ReCnctFlag = 1; // Set reconnection Flag
Serial.println("Starting reconnection timer in 30 seconds...");
timer.setTimeout(30000L, []() { // Lambda Reconnection Timer Function
ReCnctFlag = 0; // Reset reconnection Flag
ReCnctCount++; // Increment reconnection Counter
Serial.print("Attempting reconnection #");
Serial.println(ReCnctCount);
Blynk.connect(); // Try to reconnect to the server
}); // END Timer Function
}
}
NOTE: And here is an enhanced version made by another Blynk Forum member