Blynk with Wemos d1 R2 V2.1 (esp8266) goes online and offline repeatedly

Hello guys,
I have a problem with the Blynk which is used on Wemos d1 R2 v2.1 board.
I have made a watering system with Blynk for two months .
My watering system has two relays , one DHT22 sensor and one push button to activate watering manually. It will run watering at my setting time and it worked fine until last week.
Recently , I found that the blynk app status often goes online for few minutes ,then goes offline for few seconds.
I used to think there is some problem with the hardware, but after changing the hardware, the problem isn’t solved.
Here is my code , thank you for your help.

#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SPI.h>
#include <DHT.h>

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

#define DHTPIN 12          // What digital pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11     // DHT 11
#define DHTTYPE DHT22   // DHT 22, AM2302, AM2321
//#define DHTTYPE DHT21   // DHT 21, AM2301

DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;

//relay
const byte relay = 13;  //relay pin 
const byte relay_2 =15 ;  //repay_2 pin
const byte button = 14;

//button
int buttonvalue;
//manully watering time(minute)
int delayminute=1;
int delaysecond;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "XXXXX";
char pass[] = "XXXXX";

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

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
  

  // Setup a function to be called every second
  timer.setInterval(60000L, sendSensor);

  pinMode(relay,OUTPUT);
  pinMode(relay_2,OUTPUT); 

  pinMode(button, INPUT);

  dht.begin();
}

void loop()
{
  Blynk.run();
  timer.run();

  // manually watering button
  buttonvalue = digitalRead(button);
  
  if (buttonvalue == 1)
    {
      delaysecond=1000*60*delayminute;
      
      digitalWrite(relay,HIGH);
      delay(delaysecond);
      digitalWrite(relay,LOW);
      delay(30000);
      digitalWrite(relay_2,HIGH);
      delay(delaysecond);
      digitalWrite(relay_2,LOW);
    }
}


void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
}

BLYNK_WRITE(V1)
{
  // You'll get HIGH/1 at startTime and LOW/0 at stopTime.
  // this method will be triggered every day
  // until you remove widget or stop project or
  // clean stop/start fields of widget
  Serial.print("Got a value: ");
  Serial.println(param.asStr());
  if (param.asInt())
  {
   digitalWrite(relay,HIGH);    
  }
  else
  {
   digitalWrite(relay,LOW);  
  }
  
}

BLYNK_WRITE(V2)
{
  // You'll get HIGH/1 at startTime and LOW/0 at stopTime.
  // this method will be triggered every day
  // until you remove widget or stop project or
  // clean stop/start fields of widget
  Serial.print("Got a value: ");
  Serial.println(param.asStr());
   if (param.asInt())
  {
   digitalWrite(relay_2,HIGH);    
  }
  else
  {
   digitalWrite(relay_2,LOW);  
  }
}

It’s all the delays in your loop() causing Blynk to disconnect (it thinks your device is offline).

READ this:

User timers to remove the code from your loop(); and use millis() in stead of delay(). (Millis() will allow the rest of your code to continue to run, and remain connected to Blynk - where delay() stops everything in it’s tracks.

Two rules for Blynk . . . No delay() . . . keep your loop() clean . . .

cul

billd

Thank you for your reply.
I thought unless the buttonvalue has been triggered , the delay() won’t run.
Does it still cause the disconnection ?
I will try to remove the delay() and hope it can improve the problem.
Thank you.

Yes, the delay() will only be triggered when buttonvalue == 1, but:

will be running continuously in the loop(), thousands of times/second.

You would be better to removal all that code from the loop(), and check for buttonvalue using a timer.

I have had a watering system running for over a year using this method and it works fine.

billd

Thank you for your help !
I will modify my code .

You have to use start timer / stop timer

I uploaded the new code yesterday.
At first one hour, the problem seems to be fine , after one hour, the problem appeared again.
But the frequency has become lower.
Here is my code and I disable the dealy() in the loop()
Is anything that I should do with the code ?

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


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SPI.h>
#include <DHT.h>

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

#define DHTPIN 12          // What digital pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11     // DHT 11
#define DHTTYPE DHT22   // DHT 22, AM2302, AM2321
//#define DHTTYPE DHT21   // DHT 21, AM2301

DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;

const byte relay = 13;  //relay pin 
const byte relay_2 =15 ;  //repay_2 pin
const byte button = 14;


//button
int buttonvalue;
/*
int delayminute=1;
int delaysecond; */

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "XXX";
char pass[] = "XXX";

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

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
  

  // Setup a function to be called every second
  timer.setInterval(60000L, sendSensor);

  pinMode(relay,OUTPUT);
  pinMode(relay_2,OUTPUT); 

  pinMode(button, INPUT);

  dht.begin();

}

void loop()
{
  Blynk.run();
  timer.run();

  /* buttonvalue = digitalRead(button);
 
  if (buttonvalue == 1)
    {
      delaysecond=1000*60*delayminute;
      
      digitalWrite(relay,HIGH);
      delay(delaysecond);
      digitalWrite(relay,LOW);
      delay(30000);
      digitalWrite(relay_2,HIGH);
      delay(delaysecond);
      digitalWrite(relay_2,LOW);
    } */
}


void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
}

BLYNK_WRITE(V1)
{
  // You'll get HIGH/1 at startTime and LOW/0 at stopTime.
  // this method will be triggered every day
  // until you remove widget or stop project or
  // clean stop/start fields of widget
  Serial.print("Got a value: ");
  Serial.println(param.asStr());
  if (param.asInt())
  {
   digitalWrite(relay,HIGH);    
  }
  else
  {
   digitalWrite(relay,LOW);  
  }
  
}

BLYNK_WRITE(V2)
{
  // You'll get HIGH/1 at startTime and LOW/0 at stopTime.
  // this method will be triggered every day
  // until you remove widget or stop project or
  // clean stop/start fields of widget
  Serial.print("Got a value: ");
  Serial.println(param.asStr());
   if (param.asInt())
  {
   digitalWrite(relay_2,HIGH);    
  }
  else
  {
   digitalWrite(relay_2,LOW);  
  }
}

Maybe your wemos loose WiFi or server connection ?
Please activate Serial monitor and send us the issue.

I have changed the Wemos board and use another mobile phone but the problem has been solved.
What code should I add into the problem that I can see connecting result in the Serial monitor ?
Thank you !

You have to modify the loop as this

void loop() {
  timer.run();

  if (Blynk.connected()) {  // If connected run as normal
    Blynk.run();
     } else if (ReCnctFlag == 0)
        {  //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
   }
}

Thank you for you help.
I have tried the code and seen the result in serial monitor.
Here is the result

"[7032] Connecting to blynk-cloud.com:80
[7303] Ready (ping: 87ms).
[902539] Heartbeat timeout
Starting reconnection timer in 30 seconds…
Attempting reconnection #1
[932840] Connecting to blynk-cloud.com:80
[933061] Ready (ping: 94ms).
Starting reconnection timer in 30 seconds…
Attempting reconnection #2
[1208664] Connecting to blynk-cloud.com:80
[1209019] Ready (ping: 166ms).
[1642136] Heartbeat timeout
Starting reconnection timer in 30 seconds…
Attempting reconnection #3
[1672437] Connecting to blynk-cloud.com:80
[1677438] Connecting to blynk-cloud.com:80
[1677665] Ready (ping: 100ms).
[1975892] Heartbeat timeout
Starting reconnection timer in 30 seconds…
Attempting reconnection #4
[2006193] Connecting to blynk-cloud.com:80
[2011194] Connecting to blynk-cloud.com:80
[2014418] Ready (ping: 141ms).
[2116728] Heartbeat timeout
Starting reconnection timer in 30 seconds…
Attempting reconnection #5
[2147029] Connecting to blynk-cloud.com:80
[2148272] Ready (ping: 180ms).
[2187558] Heartbeat timeout
Starting reconnection timer in 30 seconds…
Attempting reconnection #6
[2217859] Connecting to blynk-cloud.com:80
[2218153] Ready (ping: 96ms).
[2656357] Heartbeat timeout
Starting reconnection timer in 30 seconds…
Attempting reconnection #7
[2686658] Connecting to blynk-cloud.com:80
[2686885] Ready (ping: 126ms).
[2874698] Heartbeat timeout
Starting reconnection timer in 30 seconds…
Attempting reconnection #8
[2905227] Connecting to blynk-cloud.com:80
[2906757] Ready (ping: 100ms).
[3092044] Heartbeat timeout
Starting reconnection timer in 30 seconds…
Attempting reconnection #9
[3122345] Connecting to blynk-cloud.com:80
[3122574] Ready (ping: 116ms).
Starting reconnection timer in 30 seconds…
Attempting reconnection #10
[4138587] Connecting to blynk-cloud.com:80
[4140909] Ready (ping: 1215ms).
"
It has connected for 10 times in one hour.

So, now you can see that your connection isn’t stable.
You also can see that the ping is high
this is mine
RĂ©ponse de 45.55.96.146 : octets=32 temps=105 ms TTL=49
RĂ©ponse de 45.55.96.146 : octets=32 temps=105 ms TTL=49
RĂ©ponse de 45.55.96.146 : octets=32 temps=104 ms TTL=49
RĂ©ponse de 45.55.96.146 : octets=32 temps=105 ms TTL=49

Your ping times seem to vary dramatically, so I guess you might be getting dropouts on your internet connection, maybe because of a contention issue?
Or, someone else in your household may be hogging the bandwidth (a bored teenager maybe?).

Have you tried rebooting your router etc?

Pete.

1 Like

Netflix :stuck_out_tongue_winking_eye:

My router reboots every day and my families hardly use the wifi .
Is it possible that the distance between the router and arduino board is too far which causes the connection problem ? or the router is broken ?

You have to get the signal strength

    Signal = WiFi.RSSI();
    Serial.print("Signal ");
    Serial.println(Signal);

I think that I had found the problem.
I used another board with the same code and put it closer to the AP.
It worked very well and keeping connecting with the server.
Then I thought that I put my original board in the metal box and it’s about 25m to the AP.
After I opened the cover of the metal box , it works very well in these two days.

I really appreciate for your help.
Thank you!!

Yes , it’s a Faraday cage :scream:

I have to change the case to plastic material. :grin: :grin:

Yes it should be better :joy: