• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

ESP32 – Firebase Database

Q&A Forum › Category: ESP32 › ESP32 – Firebase Database
0 Vote Up Vote Down
amal jacob asked 1 year ago

I customized the original program to suit my requirements. I added access point and added additional gpio’s. When I uploaded run the code and treid to toggle from the database I’m getting the message”

stream path, /UsersData/Aus72yqtAsYGngHWOYBLcNOJRdV2/devices/DeviceID_1/outputs/digital/
event path, /2
data type, int
event type, put"

But the devices attached to the esp32 are not working. My code is given below-
 

// iot_firebase_ap

#include <Arduino.h>
#include <Firebase_ESP_Client.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <Preferences.h>
#include <DHT.h>

Preferences preferences;

// Define the buzzer pin (D4 on ESP32 is typically GPIO2)
const int buzzerPin = 4;

const char* ssid = “ESP32-Access-Point”;
const char* password = “123456789”; // AP Mode Password

// Create an instance of the server
AsyncWebServer server(80);

#define API_KEY “AIzaSyDT25wGG0e9Kem6fxrvbdgBFhQbL_bC8V0”
#define USER_EMAIL “amaljacob@gmail.com”
#define USER_PASSWORD “Iam@mal1”
#define DATABASE_URL “https://esp-iot-app-43440-default-rtdb.asia-southeast1.firebasedatabase.app/&#8221;

FirebaseData stream;
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

// Variable to save USER UID
String uid;
String deviceID = “DeviceID_1”;

// Variables to save database paths
String databasePath;
String listenerPath;
String tempPath;
String humPath;

// DHT11 sensor
#define DHTPIN 23 // Define the pin where the DHT sensor is connected
#define DHTTYPE DHT11 // Define the DHT sensor type
DHT dht(DHTPIN, DHTTYPE);
float temperature;
float humidity;

unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 120000;

const int output1 = 2;
const int output2 = 21;
const int output3 = 23;
const int output4 = 19;
const int output5 = 22;
const int slider1 = 13;
const int slider2 = 14;

String message;

const int freq = 5000;
const int slider1Channel = 0;
const int slider2Channel = 1;
const int resolution = 8;

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); // Don’t use F() macro here
Serial.print(“PATH: “);
Serial.println(“PASSED”);
Serial.println(“PATH: ” + fbdo.dataPath());
Serial.println(“TYPE: ” + fbdo.dataType());
}else{
Serial.print(“FAILED. REASON: “);
Serial.println(fbdo.errorReason()); // Don’t use F() macro here
}
}

void streamCallback(FirebaseStream data) {
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());
Serial.println();

String streamPath = String(data.dataPath());

if(streamPath.indexOf(“/digital/”) >= 0){
int stringLen = streamPath.length();
int lastSlash = streamPath.lastIndexOf(“/”);
String gpioString = streamPath.substring(lastSlash + 1, stringLen);
int gpio = gpioString.toInt(); // Convert string to integer
Serial.print(“DIGITAL GPIO: “);
Serial.println(gpio);

if(data.dataType() == “int”){
int gpioState = data.intData();
Serial.print(“VALUE: “);
Serial.println(gpioState);

switch(gpio){ // Using switch statement for clarity
case2:
digitalWrite(output1, gpioState);
break;
case21:
digitalWrite(output2, gpioState);
break;
case23:
digitalWrite(output3, gpioState);
break;
case19:
digitalWrite(output4, gpioState);
break;
case22:
digitalWrite(output5, gpioState);
break;
default:
// Handle unexpected GPIO numbers
Serial.println(“Unexpected GPIO number”);
}
}
Serial.println();
}

/* When it first runs, it is triggered on the root (/) path and returns a JSON with all keys
and values of that path. So, we can get all values from the database and update the GPIO
states, PWM, and message on OLED */
if(data.dataTypeEnum() == fb_esp_rtdb_data_type_json){
FirebaseJson *json = data.to<FirebaseJson *>();
FirebaseJsonData result;

// Process digital outputs
for(int gpio = 2; gpio <= 22; gpio++){
String path = “/UsersData/” + uid + “/devices/” + deviceID + “/outputs/digital/” + String(gpio);
if(json->get(result, path, false)){
bool state = result.to<bool>();
digitalWrite(gpio, state);
}
}

// Process message
if(json->get(result, “/devices/” + deviceID + “/message”, false)){
String message = result.to<String>();
 
}

// Process PWM values
if(json->get(result, “/devices/” + deviceID + “/outputs/pwm/” + String(slider1), false)){
int pwmValue = result.to<int>();
analogWrite(slider1, map(pwmValue, 0, 100, 0, 255));
}
if(json->get(result, “/devices/” + deviceID + “/outputs/pwm/” + String(slider2), false)){
int pwmValue = result.to<int>();
analogWrite(slider2, map(pwmValue, 0, 100, 0, 255));
}
}
}

void streamTimeoutCallback(bool timeout) {
if(timeout){
Serial.println(“Stream timeout, resuming…\n”);
}
if(!stream.httpConnected()){
Serial.printf(“Error code: %d, reason: %s\n\n”, stream.httpCode(), stream.errorReason().c_str());
}
}

void setup() {
Serial.begin(115200);
delay(1000); // Wait for serial connection to establish
Serial.println(“Setup started”);

// Initialize Preferences
preferences.begin(“wifi”, false);

// Load saved Wi-Fi credentials
String savedSSID = preferences.getString(“ssid”, “”);
String savedPassword = preferences.getString(“password”, “”);

bool shouldStartAP = true; // Flag to determine if AP mode should be started

// Attempt to connect to saved Wi-Fi
if(savedSSID != “”){
Serial.println(“Connecting to saved Wi-Fi…”);
WiFi.begin(savedSSID.c_str(), savedPassword.c_str());

unsignedlong startTime = millis();
while(WiFi.status() != WL_CONNECTED && millis() – startTime < 15000){
delay(500);
Serial.print(“.”);
}

if(WiFi.status() == WL_CONNECTED){
Serial.println(“Connected to Wi-Fi successfully.”);
shouldStartAP = false; // Do not start AP as Wi-Fi connection is successful
}else{
Serial.println(“Failed to connect to Wi-Fi.”);
}
}

if(shouldStartAP){
// Set up ESP32 as an Access Point
WiFi.softAP(ssid, password);
Serial.println(“ESP32 is set as an Access Point”);
Serial.print(“AP IP Address: “);
Serial.println(WiFi.softAPIP());
}

// Define web server routes

server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, “text/html”, getHTML()); // Implement getHTML() to return your HTML form
});

server.on(“/setup”, HTTP_POST, [](AsyncWebServerRequest *request) {
String ssid = request->arg(“ssid”);
String pass = request->arg(“pass”);

// Save new credentials
preferences.putString(“ssid”, ssid);
preferences.putString(“password”, pass);

// Connect to Wi-Fi network with received credentials
WiFi.begin(ssid.c_str(), pass.c_str());
Serial.print(“Connecting to Wi-Fi: “);
Serial.println(ssid);

unsignedlong startTime = millis();
while(WiFi.status() != WL_CONNECTED && millis() – startTime < 15000){
delay(500);
Serial.print(“.”);
}

if(WiFi.status() != WL_CONNECTED){
Serial.println(“Failed to connect to Wi-Fi. Please check credentials.”);
request->send(200, “text/plain”, “Failed to connect to Wi-Fi.”);
}else{
Serial.println(“Connected to Wi-Fi.”);
request->send(200, “text/plain”, “Connected to Wi-Fi. ESP32 now operates in client mode.”);
// Add your Firebase initialization code here if needed
}
});

server.begin();

// GPIO Setup for Outputs
pinMode(buzzerPin, OUTPUT); // Set the buzzer pin as an output
pinMode(output1, OUTPUT);
pinMode(output2, OUTPUT);
pinMode(output3, OUTPUT);
pinMode(output4, OUTPUT);
pinMode(output5, OUTPUT);

// PWM Setup
ledcSetup(slider1Channel, freq, resolution);
ledcAttachPin(slider1, slider1Channel);
ledcSetup(slider2Channel, freq, resolution);
ledcAttachPin(slider2, slider2Channel);

// Firebase Initialization
config.api_key = API_KEY;
auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;
config.database_url = DATABASE_URL;
Firebase.reconnectWiFi(true);
fbdo.setResponseSize(4096);
Firebase.begin(&config, &auth);

// Getting the user UID might take a few seconds
Serial.println(“Getting User UID”);
while((auth.token.uid) == “”){
Serial.print(‘.’);
delay(1000);
}

// Print user UID
uid = auth.token.uid.c_str();
Serial.print(“User UID: “);
Serial.println(uid);

// Firebase Database Path
String digitalOutputsPath = “/UsersData/” + uid + “/devices/” + deviceID + “/outputs/digital/”;

 
// Define database path for sensor readings
tempPath = “/UsersData/” + uid + “/devices/” + deviceID + “/sensor/temperature”;
humPath = “/UsersData/” + uid + “/devices/” + deviceID + “/sensor/humidity”;

// Set the listener path to match the new structure
listenerPath = “/UsersData/” + uid + “/devices/” + deviceID + “/outputs/digital/”;
// Initialize the stream for this device
if(!Firebase.RTDB.beginStream(&stream, listenerPath.c_str())){
Serial.printf(“stream begin error, %s\n\n”, stream.errorReason().c_str());
}
Firebase.RTDB.setStreamCallback(&stream, streamCallback, streamTimeoutCallback);
delay(2000);

}

void updateDigitalOutput(int gpioNumber, int value) {
String path = “/UsersData/” + uid + “/devices/” + deviceID + “/outputs/digital/” + String(gpioNumber);
Firebase.RTDB.setInt(&fbdo, path.c_str(), value);
}

void loop() {
if(WiFi.status() != WL_CONNECTED){
// Switch to AP mode
// Your code to initialize AP mode…
}

if(Firebase.ready() && (millis() – sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
sendDataPrevMillis = millis();

// Get latest sensor readings from DHT sensor
temperature = dht.readTemperature();
humidity = dht.readHumidity();

// Send readings to the database:
sendFloat(tempPath, temperature);
sendFloat(humPath, humidity);
}
}

// Implement getHTML() to return the HTML code for your Wi-Fi setup page
String getHTML() {
String savedSSID = preferences.getString(“ssid”, “”);
String savedPassword = preferences.getString(“password”, “”);

String html = “<html><body>”
“<h1>Setup Wi-Fi</h1>”
“<form action=’/setup’ method=’post’>”
“SSID: <input type=’text’ name=’ssid’ value='” + savedSSID + “‘><br>”
“Password: <input type=’password’ name=’pass’ value='” + savedPassword + “‘><br>”
“<input type=’submit’ value=’Connect’>”
“</form>”
“</body></html>”;
return html;
}

void beepBuzzer() {
Serial.println(“Beeping Buzzer”);
digitalWrite(buzzerPin, HIGH); // Turn buzzer on
delay(100); // Beep duration in milliseconds
digitalWrite(buzzerPin, LOW); // Turn buzzer off
}

The databse strucurure (Iam using mutiple ESP for different room’s under same UID)

{
  “UsersData”: {
    “Aus72yqtAsYGngHWOYBLcNOJRdV2”: {
      “devices”: {
        “DeviceID_1”: {
          “outputs”: {
            “digital”: { “2”: 0, “19”: 0, “21”: 0, “22”: 0, “23”: 0 },
            “pwm”: { “13”: 20, “14”: 80 }
          },
          “sensor”: { “humidity”: 52.50, “temperature”: 25.00 },
          “message”: “I love this app”
        },
        “DeviceID_2”: {
          “outputs”: {
            “digital”: { “2”: 0, “19”: 0, “21”: 0, “22”: 0, “23”: 0 },
            “pwm”: { “13”: 50, “14”: 60 }
          },
          “sensor”: { “humidity”: 60.00, “temperature”: 22.00 },
          “message”: “Welcome to Device 2”
        },
        
        “DeviceID_15”: {
          “outputs”: {
            “digital”: { “2”: 0, “19”: 0, “21”: 0, “22”: 0, “23”: 0 },
            “pwm”: { “13”: 30, “14”: 70 }
          },
          “sensor”: { “humidity”: 55.00, “temperature”: 24.00 },
          “message”: “Device 15 message”
        }
      }
    }
  }
}
I can’t troubleshoot what is the real issue. Hopefully, you can solve my problem.
Thanking you.

 

Question Tags: ESP32 FIREBASE
1 Answers
0 Vote Up Vote Down
Sara Santos Staff answered 1 year ago

Hi.
 
Can you please share the code using Pastebin or Github?
It will be easier to look at.
It’s very difficult to troubleshoot code in the current format.
 
Thanks
Regards,
Sara

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.