Arduino nano with esp32 and Firebase gets stuck

Hi to all,

I’m using Arduino nano esp32 board to collect data from an analogic sensor and update a Firebase database. The application works fine, but I noticed that after about 10 minutes, the board doesn’t send anything to Firebase. I can see the Wi-Fi module connected to the network by looking at the connected devices in the router's administration panel.

Every time, I need to physically reboot Arduino to get it to work again.

I cannot determine whether the issue is with the code or the hardware.

Can you please help me?



#include <Arduino.h>
#if defined(ESP32) || defined(ARDUINO_RASPBERRY_PI_PICO_W) || defined(ARDUINO_GIGA)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#elif __has_include(<WiFiNINA.h>) || defined(ARDUINO_NANO_RP2040_CONNECT)
#include <WiFiNINA.h>
#elif __has_include(<WiFi101.h>)
#include <WiFi101.h>
#elif __has_include(<WiFiS3.h>) || defined(ARDUINO_UNOWIFIR4)
#include <WiFiS3.h>
#elif __has_include(<WiFiC3.h>) || defined(ARDUINO_PORTENTA_C33)
#include <WiFiC3.h>
#elif __has_include(<WiFi.h>)
#include <WiFi.h>
#endif
#include <WiFiManager.h>
#include <FirebaseClient.h>


/* 1. Define the WiFi credentials */
#define WIFI_SSID "xxxxxx"
#define WIFI_PASSWORD "xxxx"

// For the following credentials, see examples/Authentications/SignInAsUser/EmailPassword/EmailPassword.ino

/* 2. Define the API Key */
#define API_KEY "zzzzzzzzzzzzzzzzz"

/* 3. Define the RTDB URL */
#define DATABASE_URL "gdfgfdgdfgdfgdfgfgdfgfgdfgdf" //<databaseName>.firebaseio.com or <databaseName>.<region>.firebasedatabase.app

/* 4. Define the user Email and password that alreadey registerd or added in your project */
#define USER_EMAIL "name_user_"
#define USER_PASSWORD "passwd"

void authHandler();

void printResult(AsyncResult &aResult);

void printError(int code, const String &msg);

DefaultNetwork network; // initilize with boolean parameter to enable/disable network reconnection

UserAuth user_auth(API_KEY, USER_EMAIL, USER_PASSWORD);

FirebaseApp app;

#if defined(ESP32) || defined(ESP8266) || defined(ARDUINO_RASPBERRY_PI_PICO_W)
#include <WiFiClientSecure.h>
WiFiClientSecure ssl_client;
#elif defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_UNOWIFIR4) || defined(ARDUINO_GIGA) || defined(ARDUINO_PORTENTA_C33) || defined(ARDUINO_NANO_RP2040_CONNECT)
#include <WiFiSSLClient.h>
WiFiSSLClient ssl_client;
#endif

using AsyncClient = AsyncClientClass;

AsyncClient aClient(ssl_client, getNetwork(network));

RealtimeDatabase Database;

AsyncResult aResult_no_callback;


unsigned long sendDataPrevMillis = 0;
String uid;
String refPath;

String manualModeJson = "{\"manualMode\":1}";
int manualValue;
int manualMode;

String jsonString = "{\"manualMode\":1}";           // Your JSON string
float pValue = 0;                                     // Variable to store the P value
float lValue = 0;                                     // Variable to store the L value
float mValue = 0;                                     // Variable to store the M value
float hValue = 0;                                     // Variable to store the H value
float tValue = 0;                                     // Variable to store the T value

byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorPin       = 2;

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;

volatile byte pulseCount;  

float flowRate;
unsigned int flowMilliLitres;
float totalMilliLitres;

unsigned long oldTime;


unsigned long previousTime1 = 0;        // Store the previous time for function1
unsigned long previousTime2 = 0;        // Store the previous time for function2
const unsigned long interval1 = 2500;   // Delay for function1 in milliseconds (10 second) #10000
const unsigned long interval2 = 21600000;  // Delay for function2 in milliseconds (6 HOURS)

unsigned long count = 0;


void setup()
{
    WiFiManager wm;
    Serial.begin(115200);
    pinMode(A7, OUTPUT);
    pinMode(D12, OUTPUT);
    pinMode(D11, OUTPUT);
    pinMode(D10, OUTPUT);
    Serial.begin(115200);

   digitalWrite(D12, HIGH); // BLUE
   delay(1000);
   digitalWrite(D12, LOW); // BLUE
   delay(2000);
   digitalWrite(D12, HIGH); // BLUE
   delay(1000);
   digitalWrite(D12, LOW); // BLUE
   delay(1500);
   digitalWrite(D11, HIGH); // BLUE
   delay(2000);
   digitalWrite(D11, LOW); // BLUE

// code for Wi-Fi network with hard-coded credentials
#if 0
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

    Serial.print("Connecting to Wi-Fi");
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(300);
    }
    Serial.println();
    Serial.print("Connected with IP: ");
    Serial.println(WiFi.localIP());
    Serial.println();
#endif
// code for Smart Wi-Fi with AP mode
    bool res;  
    // res = wm.autoConnect(); // auto generated AP name from chipid
    // res = wm.autoConnect("AutoConnectAP"); // anonymous ap
    res = wm.autoConnect("XXXXXXX AP","detecteau"); // password protected ap
    if(!res) {
        Serial.println("Failed to connect!");
        ESP.restart();
    } 
    else {
        //if you get here you have connected to the WiFi    
        Serial.println("The device is connected to the network!)");
        digitalWrite(D10, HIGH); // BLUE
    }
   

    Firebase.printf("Firebase Client v%s\n", FIREBASE_CLIENT_VERSION);

    Serial.println("Initializing app...");

#if defined(ESP32) || defined(ESP8266) || defined(PICO_RP2040)
    ssl_client.setInsecure();
#if defined(ESP8266)
    ssl_client.setBufferSizes(4096, 1024);
#endif
#endif

    initializeApp(aClient, app, getAuth(user_auth), aResult_no_callback);

    authHandler();

    // Binding the FirebaseApp for authentication handler.
    // To unbind, use Database.resetApp();
    app.getApp<RealtimeDatabase>(Database);

    Database.url(DATABASE_URL);

    // In case setting the external async result to the sync task (optional)
    // To unset, use unsetAsyncResult().
    aClient.setAsyncResult(aResult_no_callback);

   // Serial.println("Synchronous Set... ");



   // Serial.println(getAuth(user_auth));

  refPath = "/Garden Info/WF001A24";
  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;

  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(digitalPinToInterrupt(sensorPin), pulseCounter, RISING);
 
}

void loop()
{
  //  digitalWrite(D12, HIGH); // RED
  //  digitalWrite(D11, HIGH);  // GREEN
   
    if((millis() - oldTime) > 1000)    // Only process counters once per second
  { 
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(digitalPinToInterrupt(sensorPin));
        
    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
    
    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();
    
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;
    
    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;
      
    unsigned int frac;
    
    // // Print the flow rate for this second in litres / minute
    // Serial.print("Flow rate: ");
    // Serial.print((flowRate));  // Print the integer part of the variable
    // Serial.print("L/min");
    // Serial.print("\t");       // Print tab space

    // // Print the cumulative total of litres flowed since starting
    // Serial.print("Output Liquid Quantity: ");        
    // Serial.print(totalMilliLitres);
    // Serial.println("dL"); 
    // Serial.print("\t");       // Print tab space
    // Serial.print(totalMilliLitres/1000);
    // Serial.print("L");
    

    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;
    
    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(digitalPinToInterrupt(sensorPin), pulseCounter, RISING);
  }
  
  unsigned long currentTime = millis();  // Get the current time
  // Run function1 every interval1 = 10 seconds
  if (currentTime - previousTime1 >= interval1) {
  //  Serial.print("updateWeatherData: ");
  //  Serial.println(currentTime);
  //  updateWeatherData();          // Call function1
   // pushWeatherData();  
    previousTime1 = currentTime;  // Update the previous time for function1
  }

    // Serial.print("Set Water Level ");
    bool status = Database.set<float>(aClient, "/Detecteau/WF001A24/info/status/waterLevel", totalMilliLitres/1000);
     if (status)
     Serial.println("ok");
     else
     printError(aClient.lastError().code(), aClient.lastError().message());

   // Serial.print("Set Soil Moisture");
    status = Database.set<float>(aClient, "/Detecteau/WF001A24/info/status/flowRate", flowRate);
    if (status)
      Serial.println("ok");
    else
        printError(aClient.lastError().code(), aClient.lastError().message());

    // Serial.print("Set Humidity ");
     status = Database.set<float>(aClient, "/GardenInfo/WF002A24/info/weather/humidity", flowRate);
    if (status)
    Serial.println("ok");
    else
    printError(aClient.lastError().code(), aClient.lastError().message());


    // Serial.print("Set Temperature ");
     status = Database.set<float>(aClient, "/GardenInfo/WF002A24/info/weather/temperature", totalMilliLitres/1000);
     if (status)
     Serial.println("ok");
     else
     printError(aClient.lastError().code(), aClient.lastError().message());


   // Serial.print("Get Motor status "); 
    float v4 = Database.get<float>(aClient, "/Detecteau/WF001A24/info/status/motor_valve");
    // if (aClient.lastError().code() == 0)
    //   //  Serial.println(v4);
    // else
    //     printError(aClient.lastError().code(), aClient.lastError().message());

  if (v4 == 1) {
   //  Serial.println("Valve is OPEN"); // inertite su seriale 2
    digitalWrite(A7, HIGH);   // turn the LED on (HIGH is the voltage level)
  }
  else {
   // Serial.println("Valve is CLOSED"); 
   digitalWrite(A7, LOW);   // turn the LED on (HIGH is the voltage level)
  }

    authHandler();

    Database.loop();

    
}

void authHandler()
{
    // Blocking authentication handler with timeout
    unsigned long ms = millis();
    while (app.isInitialized() && !app.ready() && millis() - ms < 120 * 1000)
    {
        // The JWT token processor required for ServiceAuth and CustomAuth authentications.
        // JWT is a static object of JWTClass and it's not thread safe.
        // In multi-threaded operations (multi-FirebaseApp), you have to define JWTClass for each FirebaseApp,
        // and set it to the FirebaseApp via FirebaseApp::setJWTProcessor(<JWTClass>), before calling initializeApp.
        JWT.loop(app.getAuth());
        printResult(aResult_no_callback);
    }
}

void printResult(AsyncResult &aResult)
{
    if (aResult.isEvent())
    {
        Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.appEvent().message().c_str(), aResult.appEvent().code());
    }

    if (aResult.isDebug())
    {
        Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());
    }

    if (aResult.isError())
    {
        Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());
    }
}

void printError(int code, const String &msg)
{
    Firebase.printf("Error, msg: %s, code: %d\n", msg.c_str(), code);
}

/*
Insterrupt Service Routine
 */
ICACHE_RAM_ATTR void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

any tips? I really can’t understand why the program stops working randomly.