NodeMCU ESP8266 goes off line for no apparent reason

Dear Blinkers,
First of all, I’m sorry for my bad english…
I made a simple project to read temperature and humidity (including max and min of the day and the time they occur) using a DHT11 sensor and display all this data on Blink app.
Everything is working very well. I have a very fast and stable wifi, however, the connection to blynk goes offline in a day or two and even with the system still connected to wifi, blynk app shows it offline and shows nothing.
The system also shows information on a 16x2 LCD display that keeps showing all informations even when Blynk is offline.
I need to restart it manually. This is very frustrating! :frowning:
Does anyone have any suggestions?
Thank you all in advance.
Alan - Brasil

Post your full sketch, correctly formatted with triple backticks.

Post your serial monitor output at the point when the device goes offline (also with triple backticks).

Provide full details of your hardware setup, including the sensors and display, and how they are powered.

Provide details of the Blynk library version and ESP8266 core version that you are using.

Pete.

First of all,thank you very much for your attention Pete. I include backticks as you ask me to do and
below are the full sketch and the BlynkSimpleEsp8266.h library.
The serial monitor listing is impossible to transcribe here because the system is far from the computer and it is completely unpredictable when the problem will occur. Everything is normal for one, two and even three days until the problem occurs.
I think I would solve the problem myself if there was a command that identified that the system was disconnected from Blynk, so I could reset it via software, since, when this happens, if I reset the system manually it starts working again.

------------------- sketch -------------------------
#define BLYNK_TEMPLATE_ID "TMPL-EJV5qe3"
#define BLYNK_TEMPLATE_NAME "Quickstart Template"
#define BLYNK_AUTH_TOKEN "6-ShPHbaKu9n8RuoInyPwBqCw8vU4l4A"

// Comment this out to disable prints and save space
#define BLYNK_PRINT Serial

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

char auth[] = BLYNK_AUTH_TOKEN;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "ACGKIK";
char pass[] = "acgkik190407";
BlynkTimer timer;

// PARAMETROS PARA CONFIGURAR E INSTANCIAR O SENSOR DHT11
#include <DHT.h>
#define DHTTYPE DHT11
#define dht_dpin D3
DHT dht(dht_dpin, DHTTYPE);

// PARAMETROS PARA CONFIGURAR O LCD 16x2 i2c
#include <LiquidCrystal_I2C.h>
// OBS: PARA DEFINIR O ENDEREÇO ABAIXO USE O SKETCH I2C_Scanner
#define endereco 0x27  // Endereços comuns: 0x27, 0x3F, ...
#define colunas 16
#define linhas 2
LiquidCrystal_I2C lcd(endereco, colunas, linhas);  // INSTANCIA O OBJETO lcd

// PARAMETOS PARA CONFITURAR O RTC
#include "RTClib.h"  // Inclusão da biblioteca RTClib da Adafruit
RTC_DS3231 rtc;      // Instancia o objeto rtc modulo DS3231
//RTC_DS1307 rtc;    // Para o módulo DS1307

// FUNÇÃO QUE EXECUTA UM SOFT RESET
void (*funcReset)() = 0;

//DECLARAÇÃO DOS DIAS DA SEMANA
//char daysOfTheWeek[7][8] = { "Domingo", "Segunda", "Terca  ", "Quarta ", "Quinta ", "Sexta  ", "Sabado " };
char daysOfTheWeek[7][4] = { "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab" };

float tempC;  //variável para armazenar a temperatura em ºC
// float tempF;                           //variável para armazenar a temperatura em ºF
float umidade;  //Variável para armazenar a umidade
// float sensTermCelsius;                 //Variável para indice de sensação térmica em graus Celsius
// float sensTermFahrenh;                 //Variável para índice de sensação térmica em graus Fahrenheit
bool mostraSerial = true;                 //Se true, mostra dados no monitor Serial
bool mostraLCD = true;                    //Se true, mostra dados no display LCD
bool mostraTime = true;                   //Se true, mostra dados da hora no serial e no LCD
bool mostraMinMax = true;                 //Se true, mostra temperaturas Min e Max no LCE
float tMaxDia, tMinDia;                   //Para armazenar as temp MAX e MIN do dia
String hMaxDia, hMinDia;                  //Para armazenar os horários que ocorreram as temp max e min
int contador = 0;                         //variável para controlar a alternação entre temp/umidade e horario no LCD
int errosDeLeitura = 0;                   //variável para armazenar os erros de leitura do sensor DHT11
int diasConectado = 1;                    //variável para computar os dias que o sistema está conectado sem problemas
String acrescentaZero(String str_valor);  // função para inserir zeros à esquerda de números < 10
#define resetPin D6                       // pino para resetar o ESP8266 via aplicativo Blynk
int estadoResetPin = 0;                   // SE o botao vinculado ao pino virtual V6 for pressionado, reseta o ESP8266
#define pinBuzz D7                        // pino do Buzzer
String diaAtual;                          // variável detectar quando mudou de dia para cálculo das Temperaturas MAX e MIN
String diaNovo;                           // idem
//String diaSemanaAnterior;               // NÃO FOI USADO
//int fake = 0;                           // variável só para debug

// ======================================= INICIO SETUP ======================================
void setup() {
  dht.begin();
  Serial.begin(9600);

  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin, HIGH);
  pinMode(pinBuzz, OUTPUT);
  digitalWrite(pinBuzz, LOW);

  // Setup a function to be called every second
  timer.setInterval(1000L, myTimerEvent);
  Blynk.begin(auth, ssid, pass);

  // PARAMETROS DE INICIALIZAÇÃO DO DISPLAY LCD 16x2
  lcd.init();       // INICIA A COMUNICAÇÃO COM O DISPLAY
  lcd.backlight();  // LIGA A ILUMINAÇÃO DO DISPLAY
  lcd.clear();      // LIMPA O DISPLAY

  // PARAMETROS DE INICIALIZAÇÃO DO MÓDULO REAL TIME CLOCK "RTC"
  //rtc.begin();
  //delay(1000);

  if (!rtc.begin()) {                                          // Inicializa o rtc e SE O RTC NÃO FOR ENCONTRADO fica no loop
    Serial.println(F("<<<<<  DS3231 não encontrado  >>>>>"));  //IMPRIME O TEXTO NO MONITOR SERIAL
    while (1) {};                                              //FICA NO LOOP
  }
  if (rtc.lostPower()) {  //SE RTC FOI LIGADO PELA PRIMEIRA VEZ / FICOU SEM ENERGIA / ESGOTOU A BATERIA, FAZ O ABAIXO
    Serial.println(F("************************** DS3231 OK! **************************"));

    //REMOVA O COMENTÁRIO DE UMA DAS LINHAS ABAIXO PARA INSERIR AS INFORMAÇÕES ATUALIZADAS EM SEU RTC
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));  //CAPTURA A DATA E HORA EM QUE O SKETCH É COMPILADO
    //rtc.adjust(DateTime(2023, 9,1 , 22, 57, 00));  //(ANO), (MÊS), (DIA), (HORA), (MINUTOS), (SEGUNDOS)
  }

  DateTime now = rtc.now();
  delay(500);
  diaAtual = now.day();  // Armazena o dia que o sistema iniciou para cálculo dos MAX e MIN
  //diaSemanaAnterior = daysOfTheWeek[now.dayOfTheWeek()]; // NÃO FOI UTILIZADO

  // LÊ O SENSOR DHT11
  leSensorDHT11();
  delay(500);
  // INICIALIZA AS TEMP MAX E MÍN E OS HORÁRIOS QUE ELAS OCORRERAM
  tMinDia = tempC;
  tMaxDia = tempC;
  hMinDia = acrescentaZero(String(now.hour(), DEC)) + ":" + acrescentaZero(String(now.minute(), DEC));
  hMaxDia = acrescentaZero(String(now.hour(), DEC)) + ":" + acrescentaZero(String(now.minute(), DEC));
  Serial.println("Setup OK");

}  // ====================================== FIM SETUP =======================================

void loop() {
  Blynk.run();
  timer.run();
  DateTime now = rtc.now();  //CHAMADA DE FUNÇÃO

  leSensorDHT11();       // Lê o sensor de temperatura e umidade (RETORNA tempC e umidade)
  atualizaTempMaxMin();  // Atualiza as temp MAX e MIN do dia e da semana
  enviaDadosBlynk();

  if (mostraSerial) {
    delay(500);
    mostraNoSerial();
  }

  contador++;
  if (mostraLCD && (contador < 4)) {
    showLCD(0, 0, " TEMP:    UMID: ");
    showLCD(0, 1, " " + String(tempC) + "    " + String(umidade) + " ");
  }

  if (mostraTime && (contador > 3) && (contador < 7)) {
    showLCD(0, 0, "  " + acrescentaZero(String(now.day(), DEC)) + "/" + acrescentaZero(String(now.month(), DEC)) + "/" + String((now.year() - 2000), DEC) + " " + daysOfTheWeek[now.dayOfTheWeek()] + " ");
    showLCD(0, 1, "    " + acrescentaZero(String(now.hour(), DEC)) + ":" + acrescentaZero(String(now.minute(), DEC)) + ":" + acrescentaZero(String(now.second(), DEC)) + "    ");
  }

  if (mostraMinMax && (contador > 6) && (contador < 10)) {
    showLCD(0, 0, "DIA:" + acrescentaZero(String(now.day(), DEC)) + "  Dias:" + acrescentaZero(String(diasConectado)));
    showLCD(0, 1, "Min:" + String(tMinDia) + " " + String(hMinDia));
  }

  if (mostraMinMax && (contador > 9)) {
    showLCD(0, 0, "DIA:" + acrescentaZero(String(now.day(), DEC)) + "  Dias:" + acrescentaZero(String(diasConectado)));
    showLCD(0, 1, "Max:" + String(tMaxDia) + " " + String(hMaxDia));
    if (contador > 11) contador = 0;
  }
}  // ======================================= FIM LOOP ========================================

// This function is called every time the device is connected to the Blynk.Cloud
BLYNK_CONNECTED() {
  // Change Web Link Button message to "Congratulations!"
  Blynk.setProperty(V4, "offImageUrl", "https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations.png");
  Blynk.setProperty(V4, "onImageUrl", "https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations_pressed.png");
  Blynk.setProperty(V4, "url", "https://docs.blynk.io/en/getting-started/what-do-i-need-to-blynk/how-quickstart-device-was-made");
}  // ------------------------------------------------------------------------------

void myTimerEvent() {  // This function sends Arduino's uptime every second to Virtual Pin 2.
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V10, millis() / 1000);
}  // ------------------------------- FIM CLASSE myTimerEvent ---------------------------------

void enviaDadosBlynk() {
  Blynk.virtualWrite(V0, tempC);
  Blynk.virtualWrite(V1, umidade);
  Blynk.virtualWrite(V2, tMinDia);
  Blynk.virtualWrite(V3, tMaxDia);
  Blynk.virtualWrite(V4, hMinDia);        // envia para o Blynk o horario que ocorreu a temp mínima
  Blynk.virtualWrite(V5, hMaxDia);        // envia para o Blynk o horário que ocorreu a temp máxima
  Blynk.virtualWrite(V6, diasConectado);  // Dias que o dispositivo está conectado SEM interrupção
}  // ------------------------------ FIM CLASSE enviaDadosBlynk -------------------------------


BLYNK_WRITE(V0) {  // This function is called every time the Virtual Pin 0 state changes
  // Set incoming value from pin V0 to a variable
  float value = param.asFloat();
}  // ------------------------------------------------------------------------------

BLYNK_WRITE(V1) {  // This function is called every time the Virtual Pin 0 state changes
  // Set incoming value from pin V0 to a variable
  float value = param.asFloat();
}  // ------------------------------------------------------------------------------

BLYNK_WRITE(V2) {  // This function is called every time the Virtual Pin 0 state changes
  // Set incoming value from pin V0 to a variable
  float value = param.asFloat();
}  // ------------------------------------------------------------------------------

BLYNK_WRITE(V3) {  // This function is called every time the Virtual Pin 0 state changes
  // Set incoming value from pin V0 to a variable
  float value = param.asFloat();
}  // ------------------------------------------------------------------------------

BLYNK_WRITE(V4) {  // This function is called every time the Virtual Pin 0 state changes
  // Set incoming value from pin V0 to a variable
  String value = param.asString();
}  // ------------------------------------------------------------------------------

BLYNK_WRITE(V5) {  // This function is called every time the Virtual Pin 0 state changes
  // Set incoming value from pin V0 to a variable
  String value = param.asString();
}  // ------------------------------------------------------------------------------

BLYNK_WRITE(V6) {  // This function is called every time the Virtual Pin 0 state changes
  // Set incoming value from pin V0 to a variable
  String value = param.asString();
}  // ------------------------------------------------------------------------------

String acrescentaZero(String str_valor) {  // FUNÇÃO PARA ACRESCENTAR UM ZERO À ESQ DE UM STRING <10 E RETORNAR COMO STRING
  String valorComZero = str_valor;
  if ((str_valor.toInt()) < 10) {    // converte String em inteiro para verificar se é menor do que 10
    valorComZero = "0" + str_valor;  // se for < 10 acrescenta um zero à esquerda
  }
  return valorComZero;
}  // ------------------------------- FIM FUNÇÃO acrescentaZero -------------------------------

void leSensorDHT11() {            // CLASSE PARA LER O SENSOR DHT11 E armazenar dados nas variáveis globais tempC e umidade
  tempC = dht.readTemperature();  // Realiza a leitura da temp em ºC
  //tempF = dht.readTemperature(true);  // Realiza a leitura de temp em ºF
  umidade = dht.readHumidity();  // Realiza a leitura da umidade EM %
  // sensTermCelsius = dht.computeHeatIndex(tempC, umidade, false);  // Sensação térmica em ºC
  // sensTermFahrenh = dht.computeHeatIndex(tempF, umidade);         // Sensação térmica em ºF

  if (isnan(tempC) || isnan(umidade)) {
    errosDeLeitura++;
    Serial.print(F("Erro de leitura "));
    Serial.print(errosDeLeitura);
    Serial.println(F(" no sensor DHT11!"));
    showLCD(0, 0, "  ERRO " + String(errosDeLeitura) + " DHT11  ");
    showLCD(0, 1, "  ============  ");
    for (int k = 0; k < 34; k++) {
      Serial.print(F("+"));
      delay(100);
    }
    Serial.println();
    Serial.println();
    if (errosDeLeitura > 5) {
      Serial.println(F("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  Vai executar um Soft RESET  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"));
      Serial.println();
      errosDeLeitura = 0;
      funcReset();  // COMO DEU 6 ERROS DE LEITURA, RESETA O SISTEMA TODO (também pode usar a função ESP.reset())
    }
    return;
  }
}  // ----------------------------- FIM CLASSE leSensorDHT11 -----------------------

void showLCD(int col, int lin, String texto) {
  //lcd.clear();
  lcd.setCursor(col, lin);
  lcd.print(texto);
}  // ----------------------------- FIM CLASSE showLCD -----------------------------

void mostraNoSerial() {
  Serial.println(F("Nome do Sketch: DHT11_NodeMCU_Blynk_DisplayLCD16x2_i2C_New_OK"));
  Serial.println(F("                ÚLTIMO TESTE EM 01/09/2023 -> COM NodeMCU ESP8266 - CONECTOU AO BLYNK e FUNCIONANDO OK"));
  Serial.println(F("                Autor: Prof. Alan C Giese"));
  Serial.println();

  showTime();

  Serial.print(F("Temperatura : "));
  Serial.print(tempC);
  Serial.print(F(" ºC"));
  Serial.print(F("  -  "));
  Serial.print(F("  Umidade: "));
  Serial.print(umidade);
  Serial.println(F(" %"));
  Serial.println(F("===================================================================="));
}  // -------------------------- FIM CLASSE mostraNoSerial --------------------------

void showTime() {
  DateTime now = rtc.now();                                 //CHAMADA DE FUNÇÃO
  Serial.print(F("Data: "));                                //IMPRIME O TEXTO NO MONITOR SERIAL
  Serial.print(acrescentaZero(String(now.day(), DEC)));     //IMPRIME NO MONITOR SERIAL O DIA
  Serial.print(F("/"));                                     //IMPRIME O CARACTERE NO MONITOR SERIAL
  Serial.print(acrescentaZero(String(now.month(), DEC)));   //IMPRIME NO MONITOR SERIAL O MÊS
  Serial.print(F("/"));                                     //IMPRIME O CARACTERE NO MONITOR SERIAL
  Serial.print(now.year(), DEC);                            //IMPRIME NO MONITOR SERIAL O ANO
  Serial.print(F(" - "));                                   //IMPRIME O TEXTO NA SERIAL
  Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);          //IMPRIME NO MONITOR SERIAL O DIA
  Serial.print(F(" - "));                                   //IMPRIME O TEXTO NA SERIAL
  Serial.print(acrescentaZero(String(now.hour(), DEC)));    //IMPRIME NO MONITOR SERIAL A HORA
  Serial.print(F(":"));                                     //IMPRIME O CARACTERE NO MONITOR SERIAL
  Serial.print(acrescentaZero(String(now.minute(), DEC)));  //IMPRIME NO MONITOR SERIAL OS MINUTOS
  Serial.print(F(":"));                                     //IMPRIME O CARACTERE NO MONITOR SERIAL
  Serial.print(acrescentaZero(String(now.second(), DEC)));  //IMPRIME NO MONITOR SERIAL OS SEGUNDOS
  Serial.print(F("  Dias conectado: "));
  Serial.print(diasConectado);
  Serial.println();  //QUEBRA DE LINHA NA SERIAL
  //delay(1000);                                    //delay(1000); //INTERVALO DE 1 SEGUNDO
}  // ------------------------------- FIM CLASSE showTime ---------------------------------

void atualizaTempMaxMin() {
  DateTime now = rtc.now();  //CHAMADA DE FUNÇÃO PARA FAZER LEITURA DE DATA/HORA
  delay(100);
  diaNovo = now.day();

  //String diaSemanaAtual = daysOfTheWeek[now.dayOfTheWeek()];
  float tempAgora = dht.readTemperature();
  delay(100);

  // Cálculo da tMinDia e tMaxDia (Temp Min e Max do DIA)
  if (diaNovo == diaAtual) {                                                                                // se diaNovo = diaAtual, está no mesmo dia: Armazena a temp max e min
    if ((tempAgora < tMinDia) && ((tempAgora - tMinDia) <= 5)) {                                            // ignora mudança brusca na temp mínima maiores que 5 graus
      tMinDia = tempAgora;                                                                                  // atualiza a temp min do dia
      hMinDia = acrescentaZero(String(now.hour(), DEC)) + ":" + acrescentaZero(String(now.minute(), DEC));  // hora que ocorreu a temp min
    }
    if ((tempAgora > tMaxDia) && ((tempAgora - tMaxDia) <= 5)) {                                            // ignora mudança brusca na temp máxima maiores que 5 graus
      tMaxDia = tempAgora;                                                                                  // atualiza a temp max do dia
      hMaxDia = acrescentaZero(String(now.hour(), DEC)) + ":" + acrescentaZero(String(now.minute(), DEC));  // hora que ocorreu a temp max
    }

  } else {
    diaAtual = diaNovo;   // atualiza o dia atual para dia novo
    tMaxDia = tempAgora;  // RESET DAS TEMP MAX E MIN DO NOVO DIA
    tMinDia = tempAgora;
    hMinDia = acrescentaZero(String(now.hour(), DEC)) + ":" + acrescentaZero(String(now.minute(), DEC));  // atualiza hora que ocorreu a temp min
    hMaxDia = acrescentaZero(String(now.hour(), DEC)) + ":" + acrescentaZero(String(now.minute(), DEC));  // atualiza hora que ocorreu a temp max

    diasConectado++;  // incrementa o contador de dias que o sistema esta conectado
    Serial.print(F("Incrementou o contador de dias Conectado: "));
    Serial.println(diasConectado);
    bipa(3, 500, 200);  // aviso sonoro da mudança de dia, deve ocorrer sempre à zero hora
  }

  Serial.println();
  Serial.println(F("Calculo das temperaturas Min e Max "));
  Serial.print(F("Dia atual: "));
  Serial.print(diaAtual);
  Serial.print(F("  Dia novo: "));
  Serial.print(diaNovo);
  Serial.print(F("  TempC: "));
  Serial.print(tempC);
  Serial.print(F("  tMinDia: "));
  Serial.print(tMinDia);
  Serial.print(F(" às "));
  Serial.print(hMinDia);
  Serial.print(F("  tMaxDia: "));
  Serial.print(tMaxDia);
  Serial.print(F(" às "));
  Serial.println(hMaxDia);
  Serial.println();
}  // ------------------------- FIM CLASSE atualizaTempMaxMin ----------------------------

void bipa(int n_vezes, int t_on, int t_off) {
  for (int i = 0; i < n_vezes; i++) {
    digitalWrite(pinBuzz, HIGH);
    delay(t_on);
    digitalWrite(pinBuzz, LOW);
    delay(t_off);
  }
}  // -------------------------- FIM CLASSE bipa ------------------------------------------

This is the BlynkSimpleEsp8266.h I'm using in this project:
/**
 * @file       BlynkSimpleEsp8266.h
 * @author     Volodymyr Shymanskyy
 * @license    This project is released under the MIT License (MIT)
 * @copyright  Copyright (c) 2015 Volodymyr Shymanskyy
 * @date       Jan 2015
 * @brief
 *
 */

#ifndef BlynkSimpleEsp8266_h
#define BlynkSimpleEsp8266_h

#ifndef ESP8266
#error This code is intended to run on the ESP8266 platform! Please check your Tools->Board setting.
#endif

#include <version.h>

#if ESP_SDK_VERSION_NUMBER < 0x020200
#error Please update your ESP8266 Arduino Core
#endif

#include <BlynkApiArduino.h>
#include <Blynk/BlynkProtocol.h>
#include <Adapters/BlynkArduinoClient.h>
#include <ESP8266WiFi.h>

class BlynkWifi
    : public BlynkProtocol<BlynkArduinoClient>
{
    typedef BlynkProtocol<BlynkArduinoClient> Base;
public:
    BlynkWifi(BlynkArduinoClient& transp)
        : Base(transp)
    {}

    void connectWiFi(const char* ssid, const char* pass)
    {
        BLYNK_LOG2(BLYNK_F("Connecting to "), ssid);
        WiFi.mode(WIFI_STA);
        if (WiFi.status() != WL_CONNECTED) {
            if (pass && strlen(pass)) {
                WiFi.begin(ssid, pass);
            } else {
                WiFi.begin(ssid);
            }
        }
        while (WiFi.status() != WL_CONNECTED) {
            BlynkDelay(500);
        }
        BLYNK_LOG1(BLYNK_F("Connected to WiFi"));

        IPAddress myip = WiFi.localIP();
        (void)myip; // Eliminate warnings about unused myip
        BLYNK_LOG_IP("IP: ", myip);
    }

    void config(const char* auth,
                const char* domain = BLYNK_DEFAULT_DOMAIN,
                uint16_t    port   = BLYNK_DEFAULT_PORT)
    {
        Base::begin(auth);
        this->conn.begin(domain, port);
    }

    void config(const char* auth,
                IPAddress   ip,
                uint16_t    port = BLYNK_DEFAULT_PORT)
    {
        Base::begin(auth);
        this->conn.begin(ip, port);
    }

    void begin(const char* auth,
               const char* ssid,
               const char* pass,
               const char* domain = BLYNK_DEFAULT_DOMAIN,
               uint16_t    port   = BLYNK_DEFAULT_PORT)
    {
        connectWiFi(ssid, pass);
        config(auth, domain, port);
        while(this->connect() != true) {}
    }

    void begin(const char* auth,
               const char* ssid,
               const char* pass,
               IPAddress   ip,
               uint16_t    port   = BLYNK_DEFAULT_PORT)
    {
        connectWiFi(ssid, pass);
        config(auth, ip, port);
        while(this->connect() != true) {}
    }

};

#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_BLYNK)
  static WiFiClient _blynkWifiClient;
  static BlynkArduinoClient _blynkTransport(_blynkWifiClient);
  BlynkWifi Blynk(_blynkTransport);
#else
  extern BlynkWifi Blynk;
#endif

#include <BlynkWidgets.h>

#endif

@AlanGiese Please edit your post, using the pencil icon at the bottom, and add triple backticks at the beginning and end of your code so that it displays correctly.
Triple backticks look like this:
```

Copy and paste these if you can’t find the correct symbol on your keyboard.

Pete.

1 Like

Hi Pete, I fixed the backticks issue and added some information you requested.

Not really.
The backticks are supposed to be at the beginning and end of your code, which tells the forum software to display it differently.
You appear to have added them at the beginning of your post, messing-up the formatting of your other text.

I’m not sure why you’ve posted the BlynkSimpleEsp8266.h code, unless you’ve modified it in some way - in which case you should explain what you’ve changed and why.

Your void loop is a mess, and probably what’s causing your disconnections.

Pete.

Sorry for the trouble but could you show me how to do it with the loop?
I did not make any changes to the BlynkEsp8266 library. I posted it because I saw it was an old version and I wasn’t sure if it was correct. I read the article but didn’t understand how to apply it in my case.

I’d suggest that you take a look at some of the Sketch Builder examples, or look at the examples included in the Blynk library. You’ll see how BlynkTimer is used to call functions on a periodic basis.

Pete.

1 Like

OK Pete,
Thanks for all.
Alan