I’ve been fighting a Blynk disconnect issue for some time, without a consistent disconnect timeframe. I have 2 devices running a similar methodology in the code to detect a disconnect. Following that I check for wifi and try to connect, then try to reconnect to blynk. I’m unsure if the disconnect is coming from the wifi or the blynk cloud.
Below is one of my codes. I’ve included everything in case it’s something I’ve not realized could be causing the problem. I’ve followed some of the advice from previous topics related to this issue, such as: remove delays, simplify the void loop, and the method for checking wifi and blynk connection.
Arduino Uno Wifi Rev 2 board
Mesh wifi network
/*************************************************************
Download latest Blynk library here:
https://github.com/blynkkk/blynk-library/releases/latest
Blynk is a platform with iOS and Android apps to control
Arduino, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your
projects by simply dragging and dropping widgets.
Downloads, docs, tutorials: http://www.blynk.cc
Sketch generator: http://examples.blynk.cc
Blynk community: http://community.blynk.cc
Follow us: http://www.fb.com/blynkapp
http://twitter.com/blynk_app
Blynk library is licensed under MIT license
This example code is in public domain.
*************************************************************
WARNING!
It's very tricky to get it working. Please read this article:
http://help.blynk.cc/hardware-and-libraries/arduino/esp8266-with-at-firmware
This example shows how value can be pushed from Arduino to
the Blynk App.
NOTE:
BlynkTimer provides SimpleTimer functionality:
http://playground.arduino.cc/Code/SimpleTimer
App project setup:
Value Display widget attached to Virtual Pin V5
*************************************************************/
/* Comment this out to disable prints and save space */
// pins:
//0 - none
//1 - none
//2 - water temp sensor
//3~ - cold relay HIGH
//4 -
//5~ - humidity/temp sensor
//6~ -
//7 -
//8 -
//9~ - actuator relay
//10~ - actuator relay
//11 - actuator relay
//12 - actuator relay
//13 -
//A0 -
//A1 -
//A2 -
//A3 -
//A4 -
//A5 -
#define BLYNK_PRINT Serial
#include <SPI.h>;
#include <WiFiNINA.h>;
#include <BlynkSimpleWiFiNINA.h>;
//Library for Digital Humidit Temperature sensor
#include "DHT.h"
#include <TimeLib.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <WidgetRTC.h>
#include <Dusk2Dawn.h>
#define TIMEZONE -6
#define LATITUDE 38.3970
#define LONGITUDE -90.6412
//RTC_DS3231 rtc;
Dusk2Dawn HouseSprings(LATITUDE,LONGITUDE, TIMEZONE); //true implies that daylight saving time is used, false = not used
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
//The type of DHT that is being used
#define DHTTYPE DHT11 // DHT 11
//Which pin the DHT output is connected to the Arduino
#define DHTPIN 5
DHT dht(DHTPIN, DHTTYPE);
// Data wire for the DS18B20 is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "********************************";
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "******************";
char pass[] = "*******************";
int door_status;
int DisconnectCount = 0;
int ReCnctFlag;
int ReCnctCount = 0;
int opentime = (6*3600);
int closetime = (20*3600);
int currenttime;
bool DST = false;
int in1 = 11;
int in2 = 12;
int in3 = 3;
int offsettimeapp = (30); //default for door to close 30 mins after stop time, converted to seconds
int wifi_attempt_count=0;
int max_wifi_connect_attempts=20;
int wait_between_wifi_attempts_millis=500;
BlynkTimer timer;
WidgetRTC rtc;
// Digital clock display of the time
void clockDisplay()
{
// You can call hour(), minute(), ... at any time
// Please see Time library examples for details
unsigned long actualTime = now();
if (month(actualTime) == 3)
{
if (weekday(actualTime) == 1)
{
if (day(actualTime) >= 0 && day(actualTime) <= 7)
{
DST = true;
}
}
}
if (month(actualTime) == 11)
{
if (weekday(actualTime) == 1)
{
if (day(actualTime) >= 8 && day(actualTime) <= 14)
{
DST = false;
}
}
}
int CurrentTime = hour() * 60 + minute();
int opentime = HouseSprings.sunrise(year(), month(), day(), DST);
//Serial.println();
//Serial.print("current time set: ");
//Serial.println(currenttime);
int closetime = HouseSprings.sunset(year(), month(), day(), DST);
int closetimeh = closetime / 60;
int closetimehour = closetimeh * 60;
int closetimemin = closetime - closetimehour;
String CloseTime = String(closetimeh) + ":" + (closetimemin) + ":" "00";
Blynk.virtualWrite(V5, CloseTime);
Serial.print(month(actualTime));
Serial.print("/");
Serial.print(day(actualTime));
Serial.print("/");
Serial.println(year(actualTime));
Serial.print(hour(actualTime));
Serial.print(':');
Serial.print(minute(actualTime));
Serial.print(':');
Serial.println(second(actualTime));
Serial.println(CurrentTime);
Serial.println(opentime);
Serial.println(closetime);
//Serial.println(weekday(actualTime));
String currentTime = String(hour()) + ":" + minute() + ":" + second();
currenttime = hour() * 60 + minute();
String currentDate = String(month()) + " " + day() + " " + year();
Serial.print("Current Time: ");
Serial.print(currentTime);
Serial.print(" ");
Serial.print(currentDate);
Serial.println();
Serial.print("current time: ");
Serial.println(currenttime);
Serial.println();
Serial.print("open time: ");
Serial.println(opentime);
// Send time to the App
Blynk.virtualWrite(V1, currentTime);
// Send date to the App
Blynk.virtualWrite(V2, currentDate);
//Blynk.virtualWrite(V5, closetime);
if (currenttime > opentime)
{
if (currenttime < opentime + (30 * 60))
{
door_open();
Serial.println("Door open");
}
}
if (currenttime > closetime + offsettimeapp)
{
door_close();
Serial.println("Door closed");
}
}
//Section of code that will handle getting the humidity/temp data and where to send it
void send_sensor_DHT()
{
//Set the variable h to the value for humidity
float h = dht.readHumidity();
// Read temperature as Fahrenheit (isFahrenheit = true)
//Set the variable f to the value for temp
float f = dht.readTemperature(true);
//delay(1000);
float TempF = sensors.getTempFByIndex(0);
//Perform a check if either h or f has no value
if (isnan(h) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
//These would be used to send data to the serial window
Serial.print("Hum: ");
Serial.println(h);
Serial.print("Temp: ");
Serial.println(f);
//Set the virtual pin 3 of the blynk to the outside air temperature value
Blynk.virtualWrite(V3, f);
//Set the virtual pin 4 of the blynk to the humidity value
Blynk.virtualWrite(V4, h);
//Serial.println(h);
//Set the virtual pin 8 of the blynk to the water temperature value
Blynk.virtualWrite(V8, TempF);
}
void send_sensor_TIME()
{
}
void send_sensor_ICE()
{
sensors.requestTemperatures(); // Send the command to get temperatures
float TempF = sensors.getTempFByIndex(0);
Serial.print("Temp probe: ");
Serial.print(TempF);
Serial.println(" F");
//send_sensor_DHT();
float f = dht.readTemperature(true);
Serial.print("Outdoor Temp: ");
Serial.println(f);
if (f < 34.00)
{
ice();
}
if (f > 36.00)
{
ice_done();
}
}
// This function sends Arduino's up time every second to Virtual Pin (5).
// In the app, Widget's reading frequency should be set to PUSH. This means
// that you define how often to send data to Blynk App.
void myTimerEvent()
{
// You can send any value at any time.
// Please don't send more that 10 values per second.
}
void motor_stop()
{
digitalWrite(in1,LOW);
digitalWrite(in2,LOW);
//Blynk.virtualWrite(V6,0);
//Blynk.virtualWrite(V7,0);
}
void ice()
{
digitalWrite(in3, HIGH);
Serial.println("Iced");
}
void ice_done()
{
digitalWrite(in3, LOW);
Serial.println("No Ice");
}
void door_open()
{
if (door_status == 0)
{
//int pinValue = param.asInt();
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
//if (pinValue = 1);
//{
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
Serial.println("Door is opening");
//Blynk.virtualWrite(V0,1);
//delay(35000);
door_status = 1;
//digitalWrite(in1,LOW);
timer.setTimeout(35000L, motor_stop);
//Blynk.virtualWrite(V6,0);
//motor_stop();
Serial.println("Door open");
}
}
void door_close()
{
if (door_status == 1)
{
//int pinValue = param.asInt();
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
//if (pinValue = 1);
//{
digitalWrite(in1,LOW);
digitalWrite(in2,HIGH);
Serial.println("Door is closing");
//Blynk.virtualWrite(V0,1);
//delay(35000);
door_status = 0;
//digitalWrite(in1,LOW);
timer.setTimeout(35000L, motor_stop);
//Blynk.virtualWrite(V7,0);
//motor_stop();
Serial.println("Door closed");
}
}
//}
BLYNK_WRITE(V6)
{
int pinValue = param.asInt();
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
if (pinValue = 1);
{
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
Blynk.virtualWrite(V0,1);
//delay(35000);
//digitalWrite(in1,LOW);
//Blynk.virtualWrite(V6,0);
timer.setTimeout(35000L, motor_stop);
Blynk.virtualWrite(V0,0);
Blynk.virtualWrite(V6,0);
}
}
BLYNK_WRITE(V7)
{
int pinValue = param.asInt();
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
if (pinValue = 1);
{
digitalWrite(in1,LOW);
digitalWrite(in2,HIGH);
Blynk.virtualWrite(V0,1);
//delay(35000);
//digitalWrite(in1,LOW);
//Blynk.virtualWrite(V6,0);
timer.setTimeout(35000L, motor_stop);
Blynk.virtualWrite(V0,2);
Blynk.virtualWrite(V7,0);
}
}
BLYNK_WRITE(V9)
{
offsettimeapp = param.asInt();
offsettimeapp = offsettimeapp;
}
void setup()
{
setTime(hour(),minute(),second(),day(), month(), year());
// Debug console
Serial.begin(9600);
Connect_to_WiFi();
Blynk.config(auth);
Blynk.connect();
rtc.begin();
//timer.setInterval(300000L, reconnectBlynk);
setSyncInterval(10 * 60); // Sync interval in seconds (10 minutes)
// Display digital clock every 10 seconds
timer.setInterval(10000L, clockDisplay);
pinMode(in3, OUTPUT);
// Start up the temp probe library
sensors.begin();
dht.begin();
timer.setInterval(60000L, send_sensor_DHT);
timer.setInterval(60000L, send_sensor_TIME);
timer.setInterval(60000L, send_sensor_ICE);
}
bool standalone_mode = true;
void Connect_to_WiFi()
{
Serial.println(F("Connecting to WiFi..."));
if (WiFi.status() != WL_CONNECTED)
{
WiFi.begin(ssid, pass); // connect to the network
}
while (WiFi.status() != WL_CONNECTED && wifi_attempt_count < max_wifi_connect_attempts) // Loop until we've connected, or reached the maximum number of attemps allowed
{
delay(wait_between_wifi_attempts_millis);
wifi_attempt_count++;
Serial.print(F("WiFi connection - attempt # "));
Serial.print(wifi_attempt_count);
Serial.print(F(" of "));
Serial.println(max_wifi_connect_attempts);
}
// we get to this point when either we're connected to Wi-Fi, or we've tried too many times. We need to do differnet things, depending which it is...
if (WiFi.status() == WL_CONNECTED)
{
//WiFi.mode(WIFI_STA);
Serial.println(F("WiFi CONNECTED"));
Serial.println();
}
else
{
// we get here if we tried multiple times, but can't connect to WiFi. We need to go into stand-alone mode and wait a while before re-trying...
standalone_mode = true; // We can't be in connected mode if no wifi
Serial.println();
timer.setInterval(1000*60*60,delayedWIFIconnect);
}
}
void delayedWIFIconnect()
{
if (standalone_mode = true)
{
wifi_attempt_count=0;
Connect_to_WiFi();
}
}
void loop()
{
timer.run();
if (WiFi.status() != WL_CONNECTED)
{
Connect_to_WiFi();
}
if (WiFi.status() == WL_CONNECTED)
{
if (!Blynk.connected())
{
Blynk.connect();
}
}
if (Blynk.connected())
{
Blynk.run();
}
}