Sketch stop working if ESP8266 goes offline

I have an arduino MEGA and an ESP8266-01 connected to wifi and everything works just good ONLY when there’s internet. If for some reason the connection drops nothing, neither the simplest thing, works.

I tried to search a lot in the forum and i saw that this is a common problem (and also that @Gunner is an expert) but every solution give me some error message.

This is my sketch:

LedControl lc = LedControl(30, 34, 32, 1); // Pins: DIN,CLK,CS, # of Display connected
#include <LiquidCrystal.h>                        // Includi libreria Display LCD
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);              // Dichiara Pin Display LCD
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "b7f8a7490c2a4aa3a5f7f11e7f403ee4";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "argon-2.4GHz-extended";
char pass[] = "1391abconde0294!=?31415";

// Hardware Serial on Mega, Leonardo, Micro...
#define EspSerial Serial1

// or Software Serial on Uno, Nano...
//#include <SoftwareSerial.h>
//SoftwareSerial EspSerial(2, 3); // RX, TX

// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200

ESP8266 wifi(&EspSerial);
BlynkTimer timer;

int livelloacqua = 0;
int umiditaterra = 0;
int notifica = false;
#define LEDV1 8
#define LEDV2 9
#define LEDR1 10
#define LEDR2 11
unsigned long delayTime = 200; // Delay between Frames

// Put values in arrays
byte felice[] =
{
  B00111100,
  B01000010,
  B10100101,
  B10000001,
  B10100101,
  B10011001,
  B01000010,
  B00111100
};

byte triste[] =
{
  B00111100,
  B01000010,
  B10100101,
  B10000001,
  B10011001,
  B10100101,
  B01000010,
  B00111100
};

void setup()
{
  // Debug console
  Serial.begin(9600);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);
  Blynk.begin(auth, wifi, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, wifi, ssid, pass, "blynk-cloud.com", 8442);
  //Blynk.begin(auth, wifi, ssid, pass, IPAddress(192,168,1,100), 8442);


  lcd.begin(16, 2);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  lcd.clear();
  lc.shutdown(0, false); // Wake up displays
  lc.shutdown(1, false);
  lc.setIntensity(0, 5); // Set intensity levels
  lc.setIntensity(1, 5);
  lc.clearDisplay(0);  // Clear Displays
  lc.clearDisplay(1);
  timer.setInterval(300L, programma); // run programma every 400 millisecond
  timer.setInterval(120000L, checknotifica); // run programma every 2 minutes
}

//  Take values in Arrays and Display them
void sfelice()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0, i, felice[i]);
  }
}

void striste()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0, i, triste[i]);
  }
}

void checknotifica () {
  livelloacqua = analogRead(A0);
  livelloacqua = map(analogRead(A0), 0, 300, 0, 100);
  if (livelloacqua < 160) {
    lcd.setCursor(0, 0);
    lcd.print("Riempire acqua      ");
    Blynk.notify("L'acqua è in esaurimento! Devi riempirla!");
  }
  if (livelloacqua >= 130) {
    lcd.setCursor(0, 0);
    lcd.print("Acqua OK            ");
  }
}

void programma() {
  livelloacqua = analogRead(A0);
  livelloacqua = map(analogRead(A0), 0, 300, 0, 100);
  Blynk.virtualWrite(V1, livelloacqua);
  umiditaterra = analogRead(A1);
  umiditaterra = map(analogRead(A1), 1024, 0, 0, 100);
  Blynk.virtualWrite(V2, umiditaterra);
  lcd.setCursor(0, 0);
  livelloacqua = analogRead(A0);
  if ((livelloacqua < 160 && !notifica)) {
    lcd.setCursor(0, 0);
    lcd.print("Riempire acqua      ");
    Blynk.notify("L'acqua è in esaurimento! Devi riempirla!");
    notifica = true;
  }
  if (livelloacqua >= 130) {
    lcd.setCursor(0, 0);
    lcd.print("Acqua OK            ");
    notifica = false;
  }

  umiditaterra = analogRead(A1);
  if (umiditaterra > 500) {
    lcd.setCursor(0, 1);
    lcd.print("Annaffiare          ");
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, HIGH);
    digitalWrite(11, HIGH);
    striste();
    delay(100);
  }
  if (umiditaterra < 500) {
    lcd.setCursor(0, 1);
    lcd.print("Pianta OKAY         ");
    digitalWrite(8, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
    sfelice();
    delay(100);
  }
}
void loop() {
  timer.run();
  Blynk.run();
}

Yes… this is normal for a basic setup… it is after all a Internet of Things application :wink:

Blynk.begin() is a blocking command: So no connection, no further processing.

There are differing commands that you can use… they didn’t use to work with Arduino/ESP combos, but now there are a bit better… so you can test.

Setup your WiFi connection first, then use…

Blynk.config() instead of Blynk.begin()

I use this on my Mega/ESP-01 combo

In pre-setup

char auth[] = "xxxxxxxxxx";
char ssid[] = "xxxxxxxxxx";
char pass[] = "xxxxxxxxxx";
char server[] = "xxx.xxx.xxx.xxx";
int port = 8080;

In void setup()

  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, server, port);  // Attempt general connection to network
  if (Blynk.connectWiFi(ssid, pass)) {  // If connected to WiFi...
    Blynk.connect();  // ...connect to Server
  }
1 Like

What i have to put in server?

EDIT

I put my IP in the server space and the sketch now works even offline but there’s some very strange. All the things thath shoul do my code happens with a delay of 3 or 5 seconds. And i need that when the sketch works offline it tries the reconnection. Is it possible? How do i solve the delay?

Yes… various differing ways… I use this one (unedited… you may have to dig through and tweek it to work for you).

void loop() {
  timer.run();
  if (Blynk.connected()) {  // If connected run as normal
    Blynk.run();
  } else if (ReCnctFlag == 0) {  // If NOT connected and not already tring to reconnect, set timer to try to reconnect in 60 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);
      wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
      Blynk.config(wifi, auth, server, port);
      Blynk.connect();  // Try to reconnect to the server
      if (Blynk.connectWiFi(ssid, pass)) {
        Blynk.connect();
      }
    });  // END Timer Function
  }
}

I tried this lines but i have another problem. The esp connects, finds the wifi and everything but it never shows the line “ping” in the serial monitor, after that it tries to reconnect over and over

LedControl lc = LedControl(30, 34, 32, 1); // Pins: DIN,CLK,CS, # of Display connected
#include <LiquidCrystal.h>                        // Includi libreria Display LCD
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);              // Dichiara Pin Display LCD
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "b7f8a7490c2a4aa3a5f7f11e7f403ee4";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "argon-2.4GHz-extended";
char pass[] = "b7f8a7490c2a4aa3a5f7f11e7f403ee4";
char server[] = "82.57.136.110";
int port = 8080;

// Hardware Serial on Mega, Leonardo, Micro...
#define EspSerial Serial1

// or Software Serial on Uno, Nano...
//#include <SoftwareSerial.h>
//SoftwareSerial EspSerial(2, 3); // RX, TX

// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200

ESP8266 wifi(&EspSerial);
BlynkTimer timer;

int livelloacqua = 0;
int umiditaterra = 0;
int notifica = false;
#define LEDV1 8
#define LEDV2 9
#define LEDR1 10
#define LEDR2 11
unsigned long delayTime = 200; // Delay between Frames

int ReCnctFlag;  // Reconnection Flag
int ReCnctCount = 0;  // Reconnection counter

// Put values in arrays
byte felice[] =
{
  B00111100,
  B01000010,
  B10100101,
  B10000001,
  B10100101,
  B10011001,
  B01000010,
  B00111100
};

byte triste[] =
{
  B00111100,
  B01000010,
  B10100101,
  B10000001,
  B10011001,
  B10100101,
  B01000010,
  B00111100
};

void setup()
{
  // Debug console
  Serial.begin(9600);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);
  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, server, port);  // Attempt general connection to network
  if (Blynk.connectWiFi(ssid, pass)) {  // If connected to WiFi...
    Blynk.connect();  // ...connect to Server
  }

  lcd.begin(16, 2);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  lcd.clear();
  lc.shutdown(0, false); // Wake up displays
  lc.shutdown(1, false);
  lc.setIntensity(0, 5); // Set intensity levels
  lc.setIntensity(1, 5);
  lc.clearDisplay(0);  // Clear Displays
  lc.clearDisplay(1);
  timer.setInterval(300L, programma); // run programma every 400 millisecond
  timer.setInterval(120000L, checknotifica); // run programma every 2 minutes
}

//  Take values in Arrays and Display them
void sfelice()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0, i, felice[i]);
  }
}

void striste()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0, i, triste[i]);
  }
}

void checknotifica () {
  livelloacqua = analogRead(A0);
  livelloacqua = map(analogRead(A0), 0, 300, 0, 100);
  if (livelloacqua < 160) {
    lcd.setCursor(0, 0);
    lcd.print("Riempire acqua      ");
    Blynk.notify("L'acqua è in esaurimento! Devi riempirla!");
  }
  if (livelloacqua >= 130) {
    lcd.setCursor(0, 0);
    lcd.print("Acqua OK            ");
  }
}

void programma() {
  livelloacqua = analogRead(A0);
  livelloacqua = map(analogRead(A0), 0, 300, 0, 100);
  Blynk.virtualWrite(V1, livelloacqua);
  umiditaterra = analogRead(A1);
  umiditaterra = map(analogRead(A1), 1024, 0, 0, 100);
  Blynk.virtualWrite(V2, umiditaterra);
  lcd.setCursor(0, 0);
  livelloacqua = analogRead(A0);
  if ((livelloacqua < 160 && !notifica)) {
    lcd.setCursor(0, 0);
    lcd.print("Riempire acqua      ");
    Blynk.notify("L'acqua è in esaurimento! Devi riempirla!");
    notifica = true;
  }
  if (livelloacqua >= 130) {
    lcd.setCursor(0, 0);
    lcd.print("Acqua OK            ");
    notifica = false;
  }

  umiditaterra = analogRead(A1);
  if (umiditaterra > 500) {
    lcd.setCursor(0, 1);
    lcd.print("Annaffiare          ");
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, HIGH);
    digitalWrite(11, HIGH);
    striste();
    delay(100);
  }
  if (umiditaterra < 500) {
    lcd.setCursor(0, 1);
    lcd.print("Pianta OKAY         ");
    digitalWrite(8, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
    sfelice();
    delay(100);
  }
}
void loop() {
  timer.run();
  if (Blynk.connected()) {  // If connected run as normal
    Blynk.run();
  } else if (ReCnctFlag == 0) {  // If NOT connected and not already tring to reconnect, set timer to try to reconnect in 60 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);
      wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
      Blynk.config(wifi, auth, server, port);
      Blynk.connect();  // Try to reconnect to the server
      if (Blynk.connectWiFi(ssid, pass)) {
        Blynk.connect();
      }
    });  // END Timer Function
  }
}

I don’t know… Try a simpler sketch and make sure you have all the proper physical connections…Serial RX to TX crossover, external 3.3v PSU for ESP, voltage divider or level shifter in-between TX from Mega (5v output signal) to RX on ESP (3.3v Max input signal), etc…

The wiring is perfect i’m using an esp adaptor 5V to 3.3V. I really don’t know what is the problem. It seems that he doesn’t even connect anymore, it just continues to try and try and try without any connection

You have your auth token as the password for your WiFi. That may be your issue.

1 Like

Good catch!! :smiley:

@Gonick Also, why use what appears to be an external IP for your Local Server… if your hardware device and Server are on the same network, use the internal IP of the server.

Ups, thanks a lot for your help by the way. I update the code with my local IP and the correct password (:sweat_smile:) but i think that the problem is that the ESP doesn’t show me the ping in the serial monitor. I see “connected to wifi” and then the reconnection lines.
Like this:

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

[606] Connecting to argon-2.4GHz-extended
[3656] AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaeaebb)
Ai-Thinker Technology Co. Ltd.
Jun 13 2016 11:29:20
OK
[6791] +CIFSR:STAIP,"192.168.1.104"
+CIFSR:STAMAC,"b4:e6:2d:28:93:9d"
[6799] Connected to WiFi
Starting reconnection timer in 30 seconds...
Attempting reconnection #1

This is the actual sketch

LedControl lc = LedControl(30, 34, 32, 1); // Pins: DIN,CLK,CS, # of Display connected
#include <LiquidCrystal.h>                        // Includi libreria Display LCD
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);              // Dichiara Pin Display LCD
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "b7f8a7490c2a4aa3a5f7f11e7f403ee4";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "argon-2.4GHz-extended";
char pass[] = "1391abconde0294!=?31415";
char server[] = "192.168.1.100";
int port = 8080;

// Hardware Serial on Mega, Leonardo, Micro...
#define EspSerial Serial1

// or Software Serial on Uno, Nano...
//#include <SoftwareSerial.h>
//SoftwareSerial EspSerial(2, 3); // RX, TX

// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200

ESP8266 wifi(&EspSerial);
BlynkTimer timer;

int livelloacqua = 0;
int umiditaterra = 0;
int notifica = false;
#define LEDV1 8
#define LEDV2 9
#define LEDR1 10
#define LEDR2 11
unsigned long delayTime = 200; // Delay between Frames

int ReCnctFlag;  // Reconnection Flag
int ReCnctCount = 0;  // Reconnection counter

// Put values in arrays
byte felice[] =
{
  B00111100,
  B01000010,
  B10100101,
  B10000001,
  B10100101,
  B10011001,
  B01000010,
  B00111100
};

byte triste[] =
{
  B00111100,
  B01000010,
  B10100101,
  B10000001,
  B10011001,
  B10100101,
  B01000010,
  B00111100
};

void setup()
{
  // Debug console
  Serial.begin(9600);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);
  wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
  Blynk.config(wifi, auth, server, port);  // Attempt general connection to network
  if (Blynk.connectWiFi(ssid, pass)) {  // If connected to WiFi...
    Blynk.connect();  // ...connect to Server
  }

  lcd.begin(16, 2);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  lcd.clear();
  lc.shutdown(0, false); // Wake up displays
  lc.shutdown(1, false);
  lc.setIntensity(0, 5); // Set intensity levels
  lc.setIntensity(1, 5);
  lc.clearDisplay(0);  // Clear Displays
  lc.clearDisplay(1);
  timer.setInterval(300L, programma); // run programma every 400 millisecond
  timer.setInterval(120000L, checknotifica); // run programma every 2 minutes
}

//  Take values in Arrays and Display them
void sfelice()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0, i, felice[i]);
  }
}

void striste()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0, i, triste[i]);
  }
}

void checknotifica () {
  livelloacqua = analogRead(A0);
  livelloacqua = map(analogRead(A0), 0, 300, 0, 100);
  if (livelloacqua < 160) {
    lcd.setCursor(0, 0);
    lcd.print("Riempire acqua      ");
    Blynk.notify("L'acqua è in esaurimento! Devi riempirla!");
  }
  if (livelloacqua >= 130) {
    lcd.setCursor(0, 0);
    lcd.print("Acqua OK            ");
  }
}

void programma() {
  livelloacqua = analogRead(A0);
  livelloacqua = map(analogRead(A0), 0, 300, 0, 100);
  Blynk.virtualWrite(V1, livelloacqua);
  umiditaterra = analogRead(A1);
  umiditaterra = map(analogRead(A1), 1024, 0, 0, 100);
  Blynk.virtualWrite(V2, umiditaterra);
  lcd.setCursor(0, 0);
  livelloacqua = analogRead(A0);
  if ((livelloacqua < 160 && !notifica)) {
    lcd.setCursor(0, 0);
    lcd.print("Riempire acqua      ");
    Blynk.notify("L'acqua è in esaurimento! Devi riempirla!");
    notifica = true;
  }
  if (livelloacqua >= 130) {
    lcd.setCursor(0, 0);
    lcd.print("Acqua OK            ");
    notifica = false;
  }

  umiditaterra = analogRead(A1);
  if (umiditaterra > 500) {
    lcd.setCursor(0, 1);
    lcd.print("Annaffiare          ");
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, HIGH);
    digitalWrite(11, HIGH);
    striste();
    delay(100);
  }
  if (umiditaterra < 500) {
    lcd.setCursor(0, 1);
    lcd.print("Pianta OKAY         ");
    digitalWrite(8, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
    sfelice();
    delay(100);
  }
}
void loop() {
  timer.run();
  if (Blynk.connected()) {  // If connected run as normal
    Blynk.run();
  } else if (ReCnctFlag == 0) {  // If NOT connected and not already tring to reconnect, set timer to try to reconnect in 60 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);
      wifi.setDHCP(1, 1, 1); //Enable dhcp in station mode and save in flash of esp8266
      Blynk.config(wifi, auth, server, port);
      Blynk.connect();  // Try to reconnect to the server
      if (Blynk.connectWiFi(ssid, pass)) {
        Blynk.connect();
      }
    });  // END Timer Function
  }
}

Try adding in BLYNK_DEBUG and see what it shows…

http://docs.blynk.cc/#blynk-firmware-debugging-define-blynk_debug

Also… is your server actually running?

Emmmmh…sorry if this sounds stupid but i’m a beginner.

I don’t run a server, i just connected my ESP to my home wifi (that works perfectly) and put the blynk token in the sketch to control and visualize the values of 2 analog sensors on my phone (water sensor and a moisture sensor).

With the debug the serial monitor shows exactly the same things. I put both lines at the top like the site said.

Ahh… OK, I guess we took too much for granted based on some of what you were saying.

Try this…

Blynk.config(wifi, auth, "blynk-cloud.com"); // Attempt general connection to network

You put me in a dilemma. I was going to tell you that it’s not convenient to show sensitive data like the auth token or the wifi key … but that’s precisely where you made a mistake later …

If you are clear that you have not made mistakes in those points … it is better to change the data for something like … xx.xx.xx.xx

Not everyone that you meet on the internet are sisters of charity.

Nothing may ever happen … but it is better to prevent than to lament.

I found your question very interesting since I had a similar problem and thanks to this post I solved it :slight_smile:

2 Likes

It works perfectly. Thanks a lot :slight_smile:

1 Like