I am experiencing an error on my esp32, I apologize if I cannot express myself well, I am using a Google translator. My code is based on opening a garage door and obtaining temperature and humidity from a sensor. The error is the following:
Anyone else has happened???
Hi.
Can you provide more details?
What project exactly are you following?
Regards,
Sara
I use SPIFFS web server, for the initialization of the esp32 where I obtain the data about the Wi-Fi connection and the Firebase credentials (email and password) for using the application through Android. And then obviously Firebase to manage the username and password data. I could see that when I start the esp32 it does not get any data from Firebase until I press the button from my web or Android application to activate the relay.
#include <Arduino.h>
#include <Firebase_ESP_Client.h>
#include “addons/TokenHelper.h”
#include “addons/RTDBHelper.h”
#include <Wire.h>
#include <WiFi.h>
#include <Adafruit_AHTX0.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include “SPIFFS.h”
Adafruit_AHTX0 aht;
Adafruit_Sensor *aht_humidity, *aht_temp;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Search for parameter in HTTP POST request
const char *PARAM_INPUT_1 = “ssid”;
const char *PARAM_INPUT_2 = “pass”;
const char *PARAM_INPUT_3 = “email”;
const char *PARAM_INPUT_4 = “contrase”;
// Variables to save values from HTML form
String ssid;
String pass;
String email;
String contrase;
// File paths to save input values permanently
const char *ssidPath = “/ssid.txt”;
const char *passPath = “/pass.txt”;
const char *emailPath = “/email.txt”;
const char *contrasePath = “/contrase.txt”;
#define API_KEY “——————————————-”
#define FIREBASE_PROJECT_ID “———–”
// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL “——————————————”
#define pinled LED_BUILTIN
int rele = 23;
// Define Firebase objects
FirebaseData stream;
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
String databasePath;
String listenerPath;
String temperaturaPath;
String humedadPath;
String PortonPath; // envia la verificacion porton
// Variable to save USER UID
String uid;
bool estado;
byte intento = 0;
byte intento2 = 0;
byte intento3 = 0;
const int LED_PIN = 2; // Pin del LED interno de la ESP32
bool portonAbierto = false; // Inicialmente, el portón está cerrado
bool pulso = true;
bool estadoPorton;
// Variable para almacenar el último estado enviado
bool ultimoEstadoEnviado = false;
// Timer variables (send new readings every other minute)
unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 120000;
//*****************************
//*** SPIFFS ***
//*****************************
// Initialize SPIFFS
void initSPIFFS()
{
if (!SPIFFS.begin(true))
{
Serial.println(“An error has occurred while mounting SPIFFS”);
}
Serial.println(“SPIFFS mounted successfully”);
}
// Read File from SPIFFS
String readFile(fs::FS &fs, const char *path)
{
Serial.printf(“Reading file: %s\r\n”, path);
File file = fs.open(path);
if (!file || file.isDirectory())
{
Serial.println(“- failed to open file for reading”);
return String();
}
String fileContent;
while (file.available())
{
fileContent = file.readStringUntil(‘\n’);
break;
}
return fileContent;
}
// Write file to SPIFFS
void writeFile(fs::FS &fs, const char *path, const char *message)
{
Serial.printf(“Writing file: %s\r\n”, path);
File file = fs.open(path, FILE_WRITE);
if (!file)
{
Serial.println(“- failed to open file for writing”);
return;
}
if (file.print(message))
{
Serial.println(“- file written”);
}
else
{
Serial.println(“- write failed”);
}
}
//*****************************
//*** LOOP SEÑAL ***
//*****************************
void senal()
{
digitalWrite(rele, HIGH);
delay(500);
digitalWrite(rele, LOW);
Serial.println(“Llego señal. Pulso PORTON”);
}
//*****************************
//*** CONEXION WIFI ***
//*****************************
bool conectado;
void connectToWiFi()
{
Serial.println(“Conectando a WiFi…”);
WiFi.begin(ssid.c_str(), pass.c_str());
//WiFi.config(local_IP, gateway, subnet, dns);
int intentos = 0;
while (WiFi.status() != WL_CONNECTED && intentos < 30)
{
delay(2000);
Serial.print(“.”);
intentos++;
}
if (WiFi.status() == WL_CONNECTED)
{
Serial.println(“\nConectado a WiFi!”);
Serial.println(“Dirección IP: ” + WiFi.localIP().toString());
digitalWrite(pinled, HIGH);
conectado = true;
}
else
{
Serial.println(“\nError al conectar a WiFi. Se alcanzó el número máximo de intentos.”);
esp_restart();
}
}
void init_WiFi()
{
if (ssid == “”)
{
Serial.println(“Dirección SSID no definida. Iniciando punto de acceso.”);
conectado = false;
// Iniciar el punto de acceso
WiFi.softAP(“ESP-WIFI-MANAGER”, NULL);
IPAddress IP = WiFi.softAPIP();
Serial.print(“AP IP address: “);
Serial.println(IP);
// Web Server Root URL
server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(SPIFFS, “/wifimanager.html”, “text/html”); });
server.serveStatic(“/”, SPIFFS, “/”);
server.on(“/”, HTTP_POST, [](AsyncWebServerRequest *request)
{
int params = request->params();
for (int i = 0; i < params; i++)
{
AsyncWebParameter *p = request->getParam(i);
if (p->isPost())
{
// HTTP POST ssid value
if (p->name() == PARAM_INPUT_1)
{
ssid = p->value().c_str();
Serial.print(“SSID set to: “);
Serial.println(ssid);
// Write file to save value
writeFile(SPIFFS, ssidPath, ssid.c_str());
}
// HTTP POST pass value
if (p->name() == PARAM_INPUT_2)
{
pass = p->value().c_str();
Serial.print(“Password set to: “);
Serial.println(pass);
// Write file to save value
writeFile(SPIFFS, passPath, pass.c_str());
}
// HTTP POST email value
if (p->name() == PARAM_INPUT_3)
{
email = p->value().c_str();
Serial.print(“email: “);
Serial.println(email);
// Write file to save value
writeFile(SPIFFS, emailPath, email.c_str());
}
// HTTP POST contraseña value
if (p->name() == PARAM_INPUT_4)
{
contrase = p->value().c_str();
Serial.print(“Contraseña: “);
Serial.println(contrase);
// Write file to save value
writeFile(SPIFFS, contrasePath, contrase.c_str());
}
//Serial.printf(“POST[%s]: %s\n”, p->name().c_str(), p->value().c_str());
}
}
request->send(200, “text/plain”, “Done. ESP will restart, connect to your router and go to IP address: “);
delay(3000);
ESP.restart(); });
server.begin();
}
else
{
connectToWiFi();
}
}
//**************************************
//******* FIREBASE ENVIO DATOS *********
//**************************************
void reconnectToFirebase()
{
Serial.println(“Intentando reconectar a Firebase…”);
// Reinicia la conexión a Firebase
if (!Firebase.RTDB.beginStream(&stream, listenerPath.c_str()))
{
Serial.printf(“Error al reiniciar la conexión a Firebase: %s\n\n”, stream.errorReason().c_str());
}
else
{
Serial.println(“Reconexión exitosa a Firebase.”);
}
delay(1000); // Puedes ajustar el tiempo de espera según sea necesario
}
void sendFloat(String path, float value)
{
if (Firebase.RTDB.setFloat(&fbdo, path.c_str(), value))
{
Serial.print(“Writing value: “);
Serial.print(value);
Serial.print(” on the following path: “);
Serial.println(path);
Serial.println(“PASSED”);
Serial.println(“PATH: ” + fbdo.dataPath());
Serial.println(“TYPE: ” + fbdo.dataType());
}
else
{
Serial.println(“FAILED”);
Serial.println(“REASON: ” + fbdo.errorReason());
}
}
void streamCallback(FirebaseStream data)
{
// Imprime información detallada sobre el evento de cambio en la base de datos
Serial.printf(“stream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\n\n”,
data.streamPath().c_str(),
data.dataPath().c_str(),
data.dataType().c_str(),
data.eventType().c_str());
// Llama a la función printResult definida en addons/RTDBHelper.h
printResult(data);
Serial.println();
// Obtiene la ruta que desencadenó la función
String streamPath = String(data.dataPath());
if (data.dataTypeEnum() == fb_esp_rtdb_data_type_json)
{
// Si los datos son de tipo JSON, extrae la información específica de la ruta “/porton”
FirebaseJson *json = data.to<FirebaseJson *>();
FirebaseJsonData result;
if (json->get(result, “/porton”, false))
{
estado = result.to<int>();
Serial.println(“estado de ingreso ” + String(estado));
}
}
else if (streamPath.indexOf(“/porton”) >= 0)
{
// Si hay cambios en los valores de salida digitales, realiza acciones específicas
if (data.dataType() == “int”)
{
estado = data.intData();
senal();
Serial.print(“VALUE: “);
Serial.println(estado);
}
}
// Imprime información sobre el tamaño del payload recibido
Serial.printf(“Received stream payload size: %d (Max. %d)\n\n”, data.payloadLength(), data.maxPayloadLength());
}
void streamTimeoutCallback(bool timeout)
{
if (timeout)
Serial.println(“stream timeout, resuming…\n”);
intento3++;
Serial.println(“error timeout no conectado intentos de conexion –> ” + String(intento3));
if (intento3 == 200)
{
esp_restart();
}
if (!stream.httpConnected())
Serial.printf(“error code: %d, reason: %s\n\n”, stream.httpCode(), stream.errorReason().c_str());
intento3++;
Serial.println(“error http no conectado intentos de conexion –> ” + String(intento3));
if (intento3 == 200)
{
esp_restart();
}
}
void setup()
{
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(pinled, LOW);
pinMode(rele, OUTPUT);
initSPIFFS();
// Load values saved in SPIFFS
ssid = readFile(SPIFFS, ssidPath);
pass = readFile(SPIFFS, passPath);
email = readFile(SPIFFS, emailPath);
contrase = readFile(SPIFFS, contrasePath);
Serial.println(ssid);
Serial.println(pass);
Serial.println(email);
Serial.println(contrase);
Serial.println(“Ingreso WIFI MANAGER”);
init_WiFi();
if (conectado == true)
{
// Configurar valores en Firebase
config.api_key = API_KEY;
auth.user.email = email;
auth.user.password = contrase;
config.database_url = DATABASE_URL;
if (!aht.begin())
{
Serial.println(“Could not find AHT? Check wiring”);
delay(10);
}
Serial.println(“AHT10 or AHT20 found”);
Firebase.reconnectWiFi(true);
fbdo.setResponseSize(4096);
// Assign the callback function for the long running token generation task */
config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h
// Assign the maximum retry of token generation
config.max_token_generation_retry = 5;
// Initialize the library with the Firebase authen and config
Firebase.begin(&config, &auth);
// Getting the user UID might take a few seconds
Serial.println(“Getting User UID”);
while ((auth.token.uid) == “”)
{
Serial.println(“Error al conectar a Firebase. Detalles:”);
Serial.print(“Código de error: “);
Serial.println(fbdo.errorCode());
Serial.print(“Razón del error: “);
Serial.println(fbdo.errorReason());
if (intento2 == 10)
{
esp_restart();
Serial.println(“intentos de coneccion UID –> ” + String(intento2));
}
intento2++;
Serial.print(‘.’);
delay(1000);
}
// Print user UID
uid = auth.token.uid.c_str();
Serial.print(“User UID: “);
Serial.println(uid);
// Update database path
databasePath = “Usuarios/” + uid;
temperaturaPath = databasePath + “/temperatura”;
humedadPath = databasePath + “/humedad”;
PortonPath = databasePath + “/estadoPorton”;
// Update database path for listening
listenerPath = databasePath + “/”;
// Begin stream on a database path –> UsersData/<user_uid>/outputs
if (!Firebase.RTDB.beginStream(&stream, listenerPath.c_str()))
Serial.printf(“stream begin error, %s\n\n”, stream.errorReason().c_str());
// Assign a calback function to run when it detects changes on the database
Firebase.RTDB.setStreamCallback(&stream, streamCallback, streamTimeoutCallback);
delay(2000);
}
}
void loop()
{
if (conectado == true)
{
//////////////////// SENSOR TEMP ///////////////////////////
// Envio nuevas lecturas a la base de datos firebase
if (Firebase.ready() && (millis() – sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0))
{
// Verificar si el estado actual es diferente al último estado enviado
if (estado != ultimoEstadoEnviado)
{
// Actualizar el último estado enviado
ultimoEstadoEnviado = estado;
// Enviar el nuevo estado a Firebase
if (!estado)
{
// Si el estado es falso (cerrado), establecer el estado del portón como cerrado
estadoPorton = false;
sendFloat(PortonPath, estadoPorton);
}
else
{
// Si el estado es verdadero (abierto), establecer el estado del portón como abierto
estadoPorton = true;
sendFloat(PortonPath, estadoPorton);
}
sendDataPrevMillis = millis();
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp); // populate temp and humidity objects with fresh data
int temploop = temp.temperature;
int humloop = humidity.relative_humidity;
delay(1000);
sendFloat(temperaturaPath, temploop);
sendFloat(humedadPath, humloop);
Serial.println(“dentro de loop”);
delay(1000);
}
}
}
}