Arduino Wifi Rev2 - reconnecting to wifi after disconnected?

Hi all,
I hooked up some sensors to an Arduino Wifi Rev2 to monitor my garden, but it keeps getting disconnected for some reason. I'd like to add some code to reconnect after it gets disconnected but I've been struggling to do so. Below is the code I have so far, any suggestions would be much appreciated!

/*
  Project: Send Data to Firebase Using Arduino Uno WiFi Rev2
  Board: Arduino Uno WiFi Rev2
   
  External libraries:
  - Arduino_LSM6DS3 by Arduino V1.0.0
  - Firebase Arduino based on WiFiNINA by Mobizt V1.1.4
 */
#include "RTClib.h"
#include "DFRobot_SHT20.h"
RTC_PCF8523 rtc;

DFRobot_SHT20 sht20(&Wire, SHT20_I2C_ADDR);

#include <Arduino_LSM6DS3.h>
#include <Firebase_Arduino_WiFiNINA.h>

#define FIREBASE_HOST ""
#define FIREBASE_AUTH ""
#define WIFI_SSID ""
#define WIFI_PASSWORD ""

FirebaseData firebaseData;

String path = "/MoistureSensors_outdoor";
String jsonStr;

void setup()
{
  Serial.begin(9600);
  sht20.initSHT20();
  delay(100);
  Serial.println("Sensor init finish!");
  sht20.checkSHT20();
  #ifndef ESP8266
    while (!Serial); // wait for serial port to connect. Needed for native USB
  #endif
    if (! rtc.begin()) {
      Serial.println("Couldn't find RTC");
      Serial.flush();
      abort();
    }
    if (! rtc.initialized() || rtc.lostPower()) {
      Serial.println("RTC is NOT initialized, let's set the time!");
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    }

  delay(1000);
  Serial.println();

  Serial.print("Connecting to WiFi...");
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED) {
    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print(".");
    delay(300);
  }
  Serial.print(" IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);
}

void loop()
{
  float A0, A1, A2, mo, d, h, m, s, humd, temp;
  DateTime now = rtc.now();
  A0 = analogRead(0);
  A1 = analogRead(1);
  A2 = analogRead(2);
  mo = now.month();
  d = now.day();
  h = now.hour();
  m = now.minute();
  s = now.second();
  humd = sht20.readHumidity();
  temp = sht20.readTemperature();
    // Send data to Firebase with specific path
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A0", A0)) {
      Serial.println(firebaseData.dataPath() + " = " + A0);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A1", A1)) {
      Serial.println(firebaseData.dataPath() + " = " + A1);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A2", A2)) {
      Serial.println(firebaseData.dataPath() + " = " + A3);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/month", mo)) {
      Serial.println(firebaseData.dataPath() + " = " + mo);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/day", d)) {
      Serial.println(firebaseData.dataPath() + " = " + d);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/hour", h)) {
      Serial.println(firebaseData.dataPath() + " = " + h);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/minute", m)) {
      Serial.println(firebaseData.dataPath() + " = " + m);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/second", s)) {
      Serial.println(firebaseData.dataPath() + " = " + s);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/temp", temp)) {
      Serial.println(firebaseData.dataPath() + " = " + temp);
    }
    if (Firebase.setFloat(firebaseData, path + "/1-setFloat/humd", humd)) {
      Serial.println(firebaseData.dataPath() + " = " + humd);
    }

    // Push data using pushJSON
    jsonStr = "{\"A0\":" + String(A0,6) + ",\"A1\":" + String(A1,6) + ",\"A2\":" + String(A2,6) + ",\"month\":" + String(mo,6) +",\"day\":" + String(d,6) +",\"hour\":" + String(h,6) +",\"minute\":" + String(m,6) +",\"second\":" + String(s,6) + ",\"temp\":" + String(temp,6) + ",\"humd\":" + String(humd,6)+ "}";

    if (Firebase.pushJSON(firebaseData, path + "/2-pushJSON", jsonStr)) {
      Serial.println(firebaseData.dataPath() + " = " + firebaseData.pushName());
        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(" (");
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println(')');
    }
    else {
      Serial.println("Error: " + firebaseData.errorReason());
    }
    Serial.println();
    delay(100000);
  
}
1 Like

You already have it
Consider breaking this off into a function and checking it regularly

1 Like

Thanks! Such is the downside of copying code from someone else without understanding what it does I guess.

If it's already trying to reconnect once it gets disconnected, do you have any ideas as to why it might keep going offline and not reconnecting, or any troubleshooting steps you'd recommend? I compile the script while its plugged into my laptop via USB, unplug it, and then plug it in to a 9V power supply. It usually gets disconnected shortly after that happens and doesn't find its way back onto the network.

Antenna, distance to router, power?

Besides these factors, I believe in loop()

can possibly cause some issues to WiFi, etc.

Try this modified untested code from yours to see if it's any better

  1. Remove delay(100000) in loop
  2. check_status() function to call FireBase_Task() every 100s
  3. Auto reconnect to WiFi it lost
/*
  Project: Send Data to Firebase Using Arduino Uno WiFi Rev2
  Board: Arduino Uno WiFi Rev2

  External libraries:
  - Arduino_LSM6DS3 by Arduino V1.0.0
  - Firebase Arduino based on WiFiNINA by Mobizt V1.1.4
*/
#include "RTClib.h"
#include "DFRobot_SHT20.h"
RTC_PCF8523 rtc;

DFRobot_SHT20 sht20(&Wire, SHT20_I2C_ADDR);

#include <Arduino_LSM6DS3.h>
#include <Firebase_Arduino_WiFiNINA.h>

#define FIREBASE_HOST ""
#define FIREBASE_AUTH ""
#define WIFI_SSID ""
#define WIFI_PASSWORD ""

FirebaseData firebaseData;

String path = "/MoistureSensors_outdoor";
String jsonStr;

void connectWiFi()
{
  int status = WL_IDLE_STATUS;
  
  while (status != WL_CONNECTED)
  {
    status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print(".");
    delay(300);
  }

  Serial.print(" IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

void check_WiFi()
{
  if ( (WiFi.status() != WL_CONNECTED) )
  {
    Serial.println(F("\nWiFi lost. Call connectMultiWiFi in loop"));
    connectWiFi();
  }
}

void setup()
{
  Serial.begin(9600);
  sht20.initSHT20();
  delay(100);
  Serial.println("Sensor init finish!");
  sht20.checkSHT20();

#ifndef ESP8266
  while (!Serial); // wait for serial port to connect. Needed for native USB
#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }
  if (! rtc.initialized() || rtc.lostPower()) {
    Serial.println("RTC is NOT initialized, let's set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  delay(1000);
  Serial.println();

  Serial.print("Connecting to WiFi...");
  
  connectWiFi();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, WIFI_SSID, WIFI_PASSWORD);
  Firebase.reconnectWiFi(true);
}

void FireBase_Task()
{
  float A0, A1, A2, mo, d, h, m, s, humd, temp;
  DateTime now = rtc.now();
  A0 = analogRead(0);
  A1 = analogRead(1);
  A2 = analogRead(2);
  mo = now.month();
  d = now.day();
  h = now.hour();
  m = now.minute();
  s = now.second();

  humd = sht20.readHumidity();
  temp = sht20.readTemperature();
  // Send data to Firebase with specific path
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A0", A0)) {
    Serial.println(firebaseData.dataPath() + " = " + A0);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A1", A1)) {
    Serial.println(firebaseData.dataPath() + " = " + A1);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A2", A2)) {
    Serial.println(firebaseData.dataPath() + " = " + A3);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/month", mo)) {
    Serial.println(firebaseData.dataPath() + " = " + mo);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/day", d)) {
    Serial.println(firebaseData.dataPath() + " = " + d);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/hour", h)) {
    Serial.println(firebaseData.dataPath() + " = " + h);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/minute", m)) {
    Serial.println(firebaseData.dataPath() + " = " + m);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/second", s)) {
    Serial.println(firebaseData.dataPath() + " = " + s);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/temp", temp)) {
    Serial.println(firebaseData.dataPath() + " = " + temp);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/humd", humd)) {
    Serial.println(firebaseData.dataPath() + " = " + humd);
  }

  // Push data using pushJSON
  jsonStr = "{\"A0\":" + String(A0, 6) + ",\"A1\":" + String(A1, 6) + ",\"A2\":" + String(A2, 6) + ",\"month\":" + String(mo, 6) + ",\"day\":" + String(d, 6) + ",\"hour\":" + String(h, 6) + ",\"minute\":" + String(m, 6) + ",\"second\":" + String(s, 6) + ",\"temp\":" + String(temp, 6) + ",\"humd\":" + String(humd, 6) + "}";

  if (Firebase.pushJSON(firebaseData, path + "/2-pushJSON", jsonStr)) {
    Serial.println(firebaseData.dataPath() + " = " + firebaseData.pushName());
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println(')');
  }
  else {
    Serial.println("Error: " + firebaseData.errorReason());
  }

  Serial.println();

  // Bad long delay, especially in loop()
  //delay(100000);
}

void check_status()
{
  static uint32_t checkwifi_timeout = 0;
  static uint32_t fbtask_timeout    = 0;

  static uint32_t current_millis;

#define WIFICHECK_INTERVAL    1000L
#define FBTASK_INTERVAL       100000L

  current_millis = millis();

  // Check WiFi every WIFICHECK_INTERVAL (1) seconds.
  if ((current_millis > checkwifi_timeout) || (checkwifi_timeout == 0))
  {
    check_WiFi();
    checkwifi_timeout = current_millis + WIFICHECK_INTERVAL;
  }

  // Run FBTask every FBTASK_INTERVAL (100) seconds.
  if ((current_millis > fbtask_timeout) || (fbtask_timeout == 0))
  {
    FireBase_Task();
    fbtask_timeout = current_millis + FBTASK_INTERVAL;
  }
}

void loop()
{
  check_status();
}
1 Like

Amazing! this seems to be working. Thanks so much to both of you for taking the time to help me out, I really appreciate it!

I'm very new to Arduino and wasn't entirely sure how functions worked, but now that I see the code you wrote I understand.

Glad to know it's working for you. Please mark this as solved to help to other users.

I spoke too soon and it's still doing it, unfortunately. I brought Arduino/sensor rig inside near the router and left it plugged into my computer, but it still dropped off the network and didn't reconnect. It also stopped writing the sensor readings to the serial monitor, so it looks like it just stopped running the program entirely. Any ideas why that might happen?

In case it's relevant, I get this message when I run the code:
"avrdude: WARNING: invalid value for unused bits in fuse "fuse5", should be set to 1 according to datasheet
This behaviour is deprecated and will result in an error in future version
You probably want to use 0xcd instead of 0xc9 (double check with your datasheet first)."

Sorry to know it's still causing problem for you.

You'd better start from scratch, to isolate the issue: either hardware, core, firmware, libraries or

Try to use the simplest code, such as WiFiWebClientRepeating example from WiFiNINA library, after update to the latest versions of core, libraries, etc, and removing all unnecessary hardware (sensors, etc.).

If OK, then continue, using baby-steps, to add hardware, sensors, libraries, etc.

I'm afraid only you can figure out the issue by yourself.


I suggest you post question in ArduinoCore-megaavr issues or separate thread, with many more information, such as core version, board, etc.

Good Luck,

I got it working again! Thanks again for your guidance. Below is the code that I used that functions now. The change that made the difference was the addition of "#include <WiFiNINA.h>" I was under the impression that "#include <Firebase_Arduino_WiFiNINA.h>" would have been sufficient, but it seems like it wasn't.

/*
  Project: Send Data to Firebase Using Arduino Uno WiFi Rev2
  Board: Arduino Uno WiFi Rev2

  External libraries:
  - Arduino_LSM6DS3 by Arduino V1.0.0
  - Firebase Arduino based on WiFiNINA by Mobizt V1.1.4
*/
#include "RTClib.h"
#include "DFRobot_SHT20.h"
#include <Arduino_LSM6DS3.h>
#include <Firebase_Arduino_WiFiNINA.h>
#include <SPI.h>
#include <WiFiNINA.h>

#define FIREBASE_HOST ""
#define FIREBASE_AUTH ""

RTC_PCF8523 rtc;
DFRobot_SHT20 sht20(&Wire, SHT20_I2C_ADDR);

char ssid[] = "";        // your network SSID (name)
char pass[] = "";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;

// Initialize the WiFi client library
WiFiClient client;

FirebaseData firebaseData;

String path = "/MoistureSensors_outdoor_2";
String jsonStr;

void connectWiFi()
{
  
  while (status != WL_CONNECTED)
  {
    status = WiFi.begin(ssid, pass);
    Serial.print(".");
    delay(300);
  }
  
}

void check_WiFi()
{
  if ( (WiFi.status() != WL_CONNECTED) )
  {
    Serial.println(F("\nWiFi lost. Call connectMultiWiFi in loop"));
    connectWiFi();
  }
}

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  sht20.initSHT20();
  delay(100);
  Serial.println("Sensor init finish!");
  sht20.checkSHT20();

#ifndef ESP8266
  while (!Serial); // wait for serial port to connect. Needed for native USB
#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }
  if (! rtc.initialized() || rtc.lostPower()) {
    Serial.println("RTC is NOT initialized, let's set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  delay(1000);
  Serial.println();

  Serial.print("Connecting to WiFi...");
  
  connectWiFi();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH, ssid, pass);
  Firebase.reconnectWiFi(true);
}

void FireBase_Task()
{
  float A0, A1, A2, mo, d, h, m, s, humd, temp;
  DateTime now = rtc.now();
  A0 = analogRead(0);
  A1 = analogRead(1);
  A2 = analogRead(2);
  mo = now.month();
  d = now.day();
  h = now.hour();
  m = now.minute();
  s = now.second();
  humd = sht20.readHumidity();
  temp = sht20.readTemperature();
  // Send data to Firebase with specific path
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A0", A0)) {
    Serial.println(firebaseData.dataPath() + " = " + A0);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A1", A1)) {
    Serial.println(firebaseData.dataPath() + " = " + A1);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/A2", A2)) {
    Serial.println(firebaseData.dataPath() + " = " + A3);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/month", mo)) {
    Serial.println(firebaseData.dataPath() + " = " + mo);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/day", d)) {
    Serial.println(firebaseData.dataPath() + " = " + d);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/hour", h)) {
    Serial.println(firebaseData.dataPath() + " = " + h);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/minute", m)) {
    Serial.println(firebaseData.dataPath() + " = " + m);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/second", s)) {
    Serial.println(firebaseData.dataPath() + " = " + s);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/temp", temp)) {
    Serial.println(firebaseData.dataPath() + " = " + temp);
  }
  if (Firebase.setFloat(firebaseData, path + "/1-setFloat/humd", humd)) {
    Serial.println(firebaseData.dataPath() + " = " + humd);
  }

  // Push data using pushJSON
  jsonStr = "{\"A0\":" + String(A0, 6) + ",\"A1\":" + String(A1, 6) + ",\"A2\":" + String(A2, 6) + ",\"month\":" + String(mo, 6) + ",\"day\":" + String(d, 6) + ",\"hour\":" + String(h, 6) + ",\"minute\":" + String(m, 6) + ",\"second\":" + String(s, 6) + ",\"temp\":" + String(temp, 6) + ",\"humd\":" + String(humd, 6) + "}";

  if (Firebase.pushJSON(firebaseData, path + "/2-pushJSON", jsonStr)) {
    Serial.println(firebaseData.dataPath() + " = " + firebaseData.pushName());
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println(')');
  }
  else {
    Serial.println("Error: " + firebaseData.errorReason());
  }

  Serial.println();
}

void check_status()
{
  static uint32_t checkwifi_timeout = 0;
  static uint32_t fbtask_timeout    = 0;
  static uint32_t current_millis;

#define WIFICHECK_INTERVAL    1000L
#define FBTASK_INTERVAL       100000L

  current_millis = millis();

  // Check WiFi every WIFICHECK_INTERVAL (1) seconds.
  if ((current_millis > checkwifi_timeout) || (checkwifi_timeout == 0))
  {
    check_WiFi();
    checkwifi_timeout = current_millis + WIFICHECK_INTERVAL;
  }

  // Run FBTask every FBTASK_INTERVAL (100) seconds.
  if ((current_millis > fbtask_timeout) || (fbtask_timeout == 0))
  {
    FireBase_Task();
    fbtask_timeout = current_millis + FBTASK_INTERVAL;
  }
}

void loop()
{
  check_status();
}
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.