Wifi or Blynk always disconnects

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();
  }
}

What percentage of the board’s memory does this sketch use?

I see some odd things like…

and the fact that standalone_mode doesn’t appear to be getting set back to false after a successful re-connection.

Pete.

Hi Pete,

Good points. I’ll make those 3 changes and see if that corrects the issue.

I’ll have to check where I need to reset standalone_mode in the code, presumably after wifi has connected and connection to Blynk has also been re-established. Right now, I only see this check is performed in the void loop. Would you recommend I call a function to keep the void loop cleaner or add it to this section of code? I’m only using standalone_mode to check if the device should attempt to reconnect to wifi, in the event that the device could not originally connect in void Connect_to_WiFi.

if (Blynk.connected()) 
  {
    Blynk.run();
  }

I’m not sure why I have the V9 section of code written this way, perhaps it was an adjustment from a previous version of code.

In general, this is the most complex code that I’m running on the two boards. I’ll also check the memory that I’m using this evening. I have some other clean-up I could do in this code as well, if memory is an issue.

Yes, using a timer.

Pete.

Just some info so far.

The device disconnected yesterday around 5:00am. Typically it will reconnect within about 5 hours, but it has not reconnected. I’ll have to go out and reset it later today and will upload the new code with the adjustment we discussed.

For reference, this is the memory info:
Sketch uses 33811 bytes (69%) of program storage space. Maximum is 48640 bytes.
Global variables use 873 bytes (14%) of dynamic memory, leaving 5271 bytes for local variables. Maximum is 6144 bytes.

Is this device in a location where the WiFi signal could be low?

Are you able to obtain RSSI readings?

Pete.

It is located outside and this has been a thought I’ve had before as well. I’ve added another hub into my mesh network in the past few months hoping that would address the issue as well. I’ll check signal strength again this afternoon.

I somewhat suspect this isn’t the issue since my other device, with the same reconnection methodology, is in the basement and always has good signal. And this device also has the same prolonged disconnect issue.

Is there a reason why you use this type of board?

Pete.

Not specifically. I had no wifi originally with the project, and wanted this functionality. My original projects used regular Uno’s, so it seemed like a logical choice. I had issues adding an esp8266 to the Uno, mostly because I wasn’t familiar enough with them. So I made the move to the Uno Wifi rev 2.

Is there another board you would recommend that I could try?

My preference is the Wemos D1 Mini or D1 Mini Pro (which can be used with an external antenna by moving a tiny resistor, and is useful for projects where weak WiFi may be an issue).

Or, if you need more GPIOs or Analog inputs then an ESP32.
Some ESP32s are also available with an external antenna socket.

Generally they are cheaper than Uno based boars and far superior in almost every way, and smaller too.

Pete.

Ok, I do have a Wemos D1 with similar code. I had used it with a battery power supply and had a deep sleep section of code that made things more difficult to troubleshoot connectivity issues. I may write a new code for that board, removing the battery and deep sleep, just to check if the issues persists.

1 Like

Signal strength is about 60 dBm

I assume that should read -60, in which case it’s excellent.

Pete.

yes, sorry. You are correct.

1 Like