ESP32: Getting Started with Firebase (Realtime Database)

This guide will get you started quickly with Firebase using the ESP32 board. Firebase is Google’s mobile application development platform that includes many services to manage data from IOS, Android, or web applications. You’ll create a Firebase project with a realtime database (RTDB), and you’ll learn how to store and read values from the database with your ESP32.

Getting Started with ESP32 with Firebase: Realtime Database Arduino IDE

In a later tutorial, you’ll learn how to create a Firebase web app that you can access from anywhere to monitor and control your ESP32 using firebase’s realtime database:

We have a similar tutorial for the ESP8266 board: Getting Started with Firebase (Realtime Database)

What is Firebase?

Firebase logo Realtime Database

Firebase is Google’s mobile application development platform that helps you build, improve, and grow your app. It has many services used to manage data from any android, IOS, or web application.

The following paragraph clearly explains the advantages of using Firebase:

Firebase is a toolset to “build, improve, and grow your app”, and the tools it gives you cover a large portion of the services that developers would normally have to build themselves but don’t really want to build because they’d rather be focusing on the app experience itself. This includes things like analytics, authentication, databases, configuration, file storage, push messaging, and the list goes on. The services are hosted in the cloud and scale with little to no effort on the part of the developer.”

This paragraph was taken from this article, and we recommend that you read that article if you want to understand better what firebase is and what it allows you to do.

You can use the ESP32 to connect and interact with your Firebase project, and you can create applications to control the ESP32 via Firebase from anywhere in the world.

In this tutorial, we’ll create a Firebase project with a realtime database, and we’ll use the ESP32 to store and read data from the database. The ESP32 can interact with the database from anywhere in the world as long as it is connected to the internet.

This means that you can have two ESP32 boards in different networks, with one board storing data and the other board reading the most recent data, for example.

ESP32 Firebase Project Introduction realtime database

In a later tutorial, we’ll create a web app using Firebase that will control the ESP32 to display sensor readings or control outputs from anywhere in the world.

Firebase ESP32 Project Web App Project Example

Project Overview

In this tutorial, you’ll learn how to create a Firebase project with a realtime database and store and read data from the database using the ESP32.

To follow this project, first, you need to set up a Firebase project and create a realtime database for that project. Then, you’ll program the ESP32 to store and read data from the database. This tutorial is divided into three sections.

  1. Create a Firebase Project
  2. ESP32: Store data to the Firebase Realtime Database
  3. ESP32: Read data from the Firebase Realtime Database

Let’s get started!


Set Up a Firebase Account and Create a New Project

1.Create a New Project

Follow the next instructions to create a new project on Firebase.

  1. Go to Firebase and sign in using a Google Account.
  2. Click Get Started, and then Add project to create a new project.
  3. Give a name to your project, for example: ESP32 Firebase Demo.
    Set Up Firebase Project for ESP32 and ESP8266 Step 1
  4. Disable the option Enable Google Analytics for this project as it is not needed and click Create project.
    Set Up Firebase Project for ESP32 and ESP8266 Step 2
  5. It will take a few seconds setting up your project. Then, click Continue when it’s ready.
    Set Up Firebase Project for ESP32 and ESP8266 Step 3
  6. You’ll be redirected to your Project console page.
    Set Up Firebase Project for ESP32 and ESP8266 Step 4

2. Set Authentication Methods

You need to set authentication methods for your app.

“Most apps need to know the identity of a user. In other words, it takes care of logging in and identify the users (in this case, the ESP32). Knowing a user’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices.” To learn more about the authentication methods, you can read the documentation.

  1. On the left sidebar, click on Authentication and then on Get started.
    Set Up Firebase Project for ESP32 and ESP8266 Authentication Methods
  2. There are several authentication methods like email and password, Google Account, Facebook account, and others.Set Up Firebase Project for ESP32 and ESP8266 Authentication Methods List
  3. For testing purposes, we can select the Anonymous user (require authentication without requiring users to sign in first by creating temporary anonymous accounts). Enable that option and click Save.Set Up Firebase Project for ESP32 and ESP8266 Authentication Methods Anonymous User

3. Creating a Realtime Database

The next step is creating a Realtime Database for your project. Follow the next steps to create the database.

  1. On the left sidebar click on Realtime Database and then, click on Create Database.
    Set up realtime database firebase ESP32 ESP8266 Step1
  2. Select your database location. It should be the closest to your location.
    Set up realtime database firebase ESP32 ESP8266 Select Location
  3. Set up security rules for your database. For testing purposes, select Start in test mode. In later tutorials you’ll learn how to secure your database using database rules.
    Set up realtime database firebase ESP32 ESP8266 Set Security Rules
  4. Your database is now created. You need to copy and save the database URL—highlighted in the following image—because you’ll need it later in your ESP32 code.
    Set up realtime database firebase ESP32 ESP8266 Database Created

The Realtime Database is all set. Now, you also need to get your project API key.

4. Get Project API Key

  1. To get your project’s API key, on the left sidebar click on Project Settings.
    Get Firebase Project API Key
  2. Copy the API Key to a safe place because you’ll need it later.
    Firebase Project API key

Now, you have everything ready to interface the ESP32 with the database.


Program the ESP32 to Interface with Firebase

Now that the Firebase Realtime Database is created, you’ll learn how to interface the ESP32 with the database.

To program the ESP32, you can use Arduino IDE, VS Code with the PlatformIO extension, or other suitable software.

Note: for firebase projects, we recommend using VS Code with the PlatformIO extension because if you want to develop a web application to make the bridge between the ESP32 and Firebase, VS Code provides all the tools to do that. However, we won’t build the web application in this tutorial, so you can use Arduino IDE.

Install the Firebase-ESP-Client Library

There is a library with lots of examples to use Firebase with the ESP32: the Firebase-ESP-Client library. This library is compatible with both the ESP32 and ESP8266 boards.

In this tutorial, we’ll look at simple examples to store and read data from the database. The library provides many other examples that you can check here. It also provides detailed documentation explaining how to use the library.

Installation – VS Code + PlatformIO

If you’re using VS Code with the PlatformIO extension, click on the PIO Home icon and then select the Libraries tab. Search for “Firebase ESP Client“. Select the Firebase Arduino Client Library for ESP8266 and ESP32.

Install Firebase ESP Client Library VS Code

Then, click Add to Project and select the project you’re working on.

Add Firebase ESP Client Library to Project VS Code

Also, change the monitor speed to 115200 by adding the following line to the platformio.ini file of your project:

monitor_speed = 115200

Installation – Arduino IDE

If you’re using Arduino IDE, follow the next steps to install the library.

  1. Go to Sketch > Include Library > Manage Libraries
  2. Search for Firebase ESP Client and install the Firebase Arduino Client Library for ESP8266 and ESP32 by Mobitz.

Note: We are using version 2.3.7. If you have issues compiling your code with more recent versions of the library, downgrade to version 2.3.7.

Install Firebase Arduino Client Library for ESP8266 and ESP32 by Mobitz

Now, you’re all set to start programming the ESP32 board to interact with the database.


ESP32 Store Data to Firebase Database

ESP32 Firebase store data realtime database project example

Copy the following code to your Arduino IDE. This sketch inserts an int and a float number into the database every 15 seconds. This is a simple example showing you how to connect the ESP32 to the database and store data. This is also compatible with ESP8266 boards.

Note: We are using version 2.3.7 of the Firebase ESP Client library. If you have issues compiling your code with more recent versions of the library, downgrade to version 2.3.7.

/*
  Rui Santos
  Complete project details at our blog.
    - ESP32: https://RandomNerdTutorials.com/esp32-firebase-realtime-database/
    - ESP8266: https://RandomNerdTutorials.com/esp8266-nodemcu-firebase-realtime-database/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  Based in the RTDB Basic Example by Firebase-ESP-Client library by mobizt
  https://github.com/mobizt/Firebase-ESP-Client/blob/main/examples/RTDB/Basic/Basic.ino
*/

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>

//Provide the token generation process info.
#include "addons/TokenHelper.h"
//Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Insert your network credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

// Insert Firebase project API Key
#define API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"

// Insert RTDB URLefine the RTDB URL */
#define DATABASE_URL "REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL" 

//Define Firebase Data object
FirebaseData fbdo;

FirebaseAuth auth;
FirebaseConfig config;

unsigned long sendDataPrevMillis = 0;
int count = 0;
bool signupOK = false;

void setup(){
  Serial.begin(115200);
  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();

  /* Assign the api key (required) */
  config.api_key = API_KEY;

  /* Assign the RTDB URL (required) */
  config.database_url = DATABASE_URL;

  /* Sign up */
  if (Firebase.signUp(&config, &auth, "", "")){
    Serial.println("ok");
    signupOK = true;
  }
  else{
    Serial.printf("%s\n", config.signer.signupError.message.c_str());
  }

  /* Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h
  
  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop(){
  if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)){
    sendDataPrevMillis = millis();
    // Write an Int number on the database path test/int
    if (Firebase.RTDB.setInt(&fbdo, "test/int", count)){
      Serial.println("PASSED");
      Serial.println("PATH: " + fbdo.dataPath());
      Serial.println("TYPE: " + fbdo.dataType());
    }
    else {
      Serial.println("FAILED");
      Serial.println("REASON: " + fbdo.errorReason());
    }
    count++;
    
    // Write an Float number on the database path test/float
    if (Firebase.RTDB.setFloat(&fbdo, "test/float", 0.01 + random(0,100))){
      Serial.println("PASSED");
      Serial.println("PATH: " + fbdo.dataPath());
      Serial.println("TYPE: " + fbdo.dataType());
    }
    else {
      Serial.println("FAILED");
      Serial.println("REASON: " + fbdo.errorReason());
    }
  }
}

View raw code

You need to insert your network credentials, URL database, and project API key for the project to work.

This sketch was based on the basic example provided by the library. You can find more examples here.

How the Code Works

Continue reading to learn how the code works, or skip to the demonstration section.

First, include the required libraries. The WiFi.h library to connect the ESP32 to the internet (or the ESP8266WiFi.h in case of the ESP8266 board) and the Firebase_ESP_Client.h library to interface the boards with Firebase.

#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>

You also need to include the following for the Firebase library to work.

//Provide the token generation process info.
#include "addons/TokenHelper.h"
//Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

Include your network credentials in the following lines.

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

Insert your firebase project API key—the one you’ve gotten in section 4.1.

#define API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"

Insert your database URL—see section 3.4.

#define DATABASE_URL "REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL"

setup()

In the setup(), connect your board to your network.

Serial.begin(115200);
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();

Assign the API key and the database URL to the Firebase configuration.

/* Assign the api key (required) */
config.api_key = API_KEY;

/* Assign the RTDB URL (required) */
config.database_url = DATABASE_URL;

The following lines take care of the signup for an anonymous user. Notice that you use the signUp() method, and the last two arguments are empty (anonymous user).

/* Sign up */
if (Firebase.signUp(&config, &auth, "", "")){
  Serial.println("ok");
  signupOK = true;
}
else{
  Serial.printf("%s\n", config.signer.signupError.message.c_str());
}

Note: in the anonymous user signup, every time the ESP connects, it creates a new anonymous user.

If the sign-in is successful, the signupOK variable changes to true.

signupOK = true;

The library provides examples for other authentication methods like signing in as a user with email and password, using the database legacy auth token, etc. You can check all the examples for other authentication methods here. If you end up using other authentication methods, don’t forget that you need to enable them on your firebase project (Build > Authentication > Sign-in method).

loop()

In the loop(), we’ll send data to the database periodically (if the signup is successful and everything is set up).

if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)){

Send Data to the Database

As mentioned in the library documentation, to store data at a specific node in the Firebase RTDB (realtime database), use the following functions: set, setInt, setFloat, setDouble, setString, setJSON, setArray, setBlob, and setFile.

These functions return a boolean value indicating the success of the operation, which will be true if all of the following conditions are met:

  • Server returns HTTP status code 200.
  • The data types matched between request and response.Only setBlob and setFile functions that make a silent request to Firebase server, thus no payload response returned.

In our example, we’ll send an integer number, so we need to use the setInt() function as follows:

Firebase.RTDB.setInt(&fbdo, "test/int", count)

The second argument is the database node path, and the last argument is the value you want to pass to that database path—you can choose any other database path. In this case, we’re passing the value saved in the count variable.

Here’s the complete snippet that stores the value in the database and prints a success or failed message.

if (Firebase.RTDB.setInt(&fbdo, "test/int", count)) {
  Serial.println("PASSED");
  Serial.println("PATH: " + fbdo.dataPath());
  Serial.println("TYPE: " + fbdo.dataType());
}
else {
  Serial.println("FAILED");
  Serial.println("REASON: " + fbdo.errorReason());
}

We proceed in a similar way to store a float value. We’re storing a random float value on the test/float path.

// Write an Float number on the database path test/float
if (Firebase.RTDB.setFloat(&fbdo, "test/float", 0.01 + random(0, 100))) {
  Serial.println("PASSED");
  Serial.println("PATH: " + fbdo.dataPath());
  Serial.println("TYPE: " + fbdo.dataType());
}
else {
  Serial.println("FAILED");
  Serial.println("REASON: " + fbdo.errorReason());
}

Demonstration

Upload the code to your ESP32 board. Don’t forget to insert your network credentials, database URL path, and the project API key.

After uploading the code, open the Serial Monitor at a baud rate of 115200 and press the ESP32 on-board reset button so it starts running the code.

If everything works as expected, the values should be stored in the database, and you should get success messages.

ESP32 ESP8266 Store value firebase database Serial Monitor Success

Go to your project’s Firebase Realtime database, and you’ll see the values saved on the different node paths. Every 15 seconds, it saves a new value. The database blinks when new values are saved.

ESP32 Store value firebase database Success

Congratulations! You’ve successfully stored data in Firebase’s realtime database using the ESP32. In the next section, you’ll learn to read values from the different database’s node paths.


ESP32 Read From Firebase Database

ESP32 Firebase read data realtime database

In this section, you’ll learn how to read data from the database. We’ll read the data stored in the previous section. Remember that we saved an int value in the test/int path and a float value in the test/float path.

The following example reads the values stored in the database. Upload the following code to your board. You can use the same ESP32 board or another board to get the data posted by the previous ESP32.

Note: We are using version 2.3.7 of the Firebase ESP Client library. If you have issues compiling your code with more recent versions of the library, downgrade to version 2.3.7.

/*
  Rui Santos
  Complete project details at our blog.
    - ESP32: https://RandomNerdTutorials.com/esp32-firebase-realtime-database/
    - ESP8266: https://RandomNerdTutorials.com/esp8266-nodemcu-firebase-realtime-database/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  Based in the RTDB Basic Example by Firebase-ESP-Client library by mobizt
  https://github.com/mobizt/Firebase-ESP-Client/blob/main/examples/RTDB/Basic/Basic.ino
*/

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>

//Provide the token generation process info.
#include "addons/TokenHelper.h"
//Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Insert your network credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

// Insert Firebase project API Key
#define API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"

// Insert RTDB URLefine the RTDB URL */
#define DATABASE_URL "REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL" 

//Define Firebase Data object
FirebaseData fbdo;

FirebaseAuth auth;
FirebaseConfig config;

unsigned long sendDataPrevMillis = 0;
int intValue;
float floatValue;
bool signupOK = false;

void setup() {
  Serial.begin(115200);
  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();

  /* Assign the api key (required) */
  config.api_key = API_KEY;

  /* Assign the RTDB URL (required) */
  config.database_url = DATABASE_URL;

  /* Sign up */
  if (Firebase.signUp(&config, &auth, "", "")) {
    Serial.println("ok");
    signupOK = true;
  }
  else {
    Serial.printf("%s\n", config.signer.signupError.message.c_str());
  }

  /* Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop() {
  if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) {
    sendDataPrevMillis = millis();
    if (Firebase.RTDB.getInt(&fbdo, "/test/int")) {
      if (fbdo.dataType() == "int") {
        intValue = fbdo.intData();
        Serial.println(intValue);
      }
    }
    else {
      Serial.println(fbdo.errorReason());
    }
    
    if (Firebase.RTDB.getFloat(&fbdo, "/test/float")) {
      if (fbdo.dataType() == "float") {
        floatValue = fbdo.floatData();
        Serial.println(floatValue);
      }
    }
    else {
      Serial.println(fbdo.errorReason());
    }
  }
}

View raw code

Don’t forget to insert your network credentials, database URL, and API key.

How the Code Works

The code is very similar to the previous section’s example, but it reads data from the database. Let’s take a look at the relevant parts for this section.

Data at a specific node in Firebase RTDB can be read through the following functions: get, getInt, getFloat, getDouble, getBool, getString, getJSON, getArray, getBlob, getFile.

These functions return a boolean value indicating the success of the operation, which will be true if all of the following conditions were met:

  • Server returns HTTP status code 200
  • The data types matched between request and response.

The database data’s payload (response) can be read or access through the following Firebase Data object’s functions: fbdo.intData, fbdo.floatData, fbdo.doubleData, fbdo.boolData, fbdo.stringData, fbdo.jsonString, fbdo.jsonObject, fbdo.jsonObjectPtr, fbdo.jsonArray, fbdo.jsonArrayPtr, fbdo.jsonData (for keeping parse/get result), and fbdo.blobData.

If you use a function that doesn’t match the returned data type in the database, it will return empty (string, object, or array).

The data type of the returning payload can be determined by fbdo.getDataType.

The following snippet shows how to get an integer value stored in the test/int node. First, we use the getInt() function; then, we check if the data type is an integer with fbdo.dataType(), and finally, the fdbo.intData() gets the value stored in that node.

if (Firebase.RTDB.getInt(&fbdo, "/test/int")) {
  if (fbdo.dataType() == "int") {
    intValue = fbdo.intData();
    Serial.println(intValue);
  }
}
else {
  Serial.println(fbdo.errorReason());
}

We use a similar snippet to get the float value.

 if (Firebase.RTDB.getFloat(&fbdo, "/test/float")) {
  if (fbdo.dataType() == "float") {
    floatValue = fbdo.floatData();
    Serial.println(floatValue);
  }
}
else {
  Serial.println(fbdo.errorReason());
}

Demonstration

Upload the code to your board. Then, open the Serial Monitor at a baud rate of 115200. After a few seconds, it will print the values saved on the database.

ESP32 Store value firebase database Serial Monitor Success

Wrapping Up

Congratulations! In this tutorial, you’ve created a Firebase project with a Realtime Database and learned how to store and read data from the database using the ESP32.

To keep things simple, we’ve stored sample values on the database. The idea is to save useful data like sensor readings or GPIO states.

Then, you can access the database with another ESP32 to get the data or create a Firebase web app to use that data to display sensor readings or control the ESP32 GPIOs from anywhere in the world. We cover the basics of how to create a Firebase Web App in this tutorial.

We hope you find this tutorial useful. If you want to learn more about Firebase with the ESP32 and ESP8266 boards, check out our new eBook:

If you want to learn more about the ESP32, check our courses:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

155 thoughts on “ESP32: Getting Started with Firebase (Realtime Database)”

          • i’m having the same trouble of kashif, i’m using arduino ide and esp32, i built a simple web application with javascript, html and css, communicating with firebase, esp need to read only the commands of my web program, it was all working correctly, the communication between the web program and firebase (that still work without problems), the communication between esp32 and firebase, infact when i update the variables on my program, i could se on my serial monitor the exact value i updated …. this the first 3 minutes (maybe less). at a certain it looks like the esp32 blocks completely, despite i’m updating the values ​​from my web program, without any reason, the serial monitor remain blocked without updating, even my bullshits println i use for investigations in case the communication stop, without giving me any type of errors on the terminal, it look like the loop function stop completely. Thanks for the attention, always reliable, information heroes for esp32.

      • Hi Sara,
        Thanks for the equivalent library for micropython. I tried. It works in the first connection but after that it provides problems with memory and stops. I found on the web some hints, so it is necessary to close a given variable after every connection. I rewrote the code using the base of the urequests commands.

        A suggestion for a code follows bellow. It is a base for code to put and read data from Real time database. It has a few lines and works properly.

        I used a ESP32 board (wroom-32), “esp32-idf4-20210202-v1.14.bin” firmware and the Thonny editor.
        Uploaded to the board the “boot.py” to connect the board in the internet,

        try:
        import usocket as socket
        except:
        import socket

        import network
        import esp
        esp.osdebug(None)

        import gc
        gc.collect()

        ssid = ‘xxx’
        password = ‘xxx’

        station = network.WLAN(network.STA_IF)

        station.active(True)
        station.connect(ssid, password)

        while station.isconnected() == False:
        pass

        print(‘Connection successful’)
        print(station.ifconfig())

        Upload “urequests” by upip. After to run boot.py to cennect the board in the net, write in the shell area,

        import upip
        upip.install(“urequests”)

        To finish, upload the main.py,

        import urequests as requests
        import ujson as json
        import time

        URL = “https://xxx-xxx-xxx-rtdb.firebaseio.com/.json”
        (xxx is found in the data tab in the Real time databse)

        remove and write a new data

        def put(URL,msg):
        to_post = json.dumps(msg)
        res = requests.put(url=URL, headers = {‘content-type’: ‘application/json’}, data=to_post)
        time.sleep(2)
        requests.Response.close(res) # otherwise memory problems come out

        make append

        def post(URL,msg):
        to_post = json.dumps(msg)
        res = requests.post(url=URL, headers = {‘content-type’: ‘application/json’}, data=to_post)
        time.sleep(2)
        requests.Response.close(res) # otherwise memory problems come out

        make update, do the same as put

        def patch(URL,msg):
        to_post = json.dumps(msg)
        res = requests.patch(url=URL, headers = {‘content-type’: ‘application/json’}, data=to_post)
        time.sleep(2)
        requests.Response.close(res) # otherwise memory problems come out

        msg={ ‘account’: ‘dudu30’, ‘password’: ‘dudu31’}
        put(URL,msg)

        msg2={ ‘account’: ‘dudu40’, ‘password’: ‘dudu51’}
        post(URL,msg2)

        res2 = requests.get(url=URL)
        print(res2.json())

        Reply
        • Hi Luiz,
          I am also trying to build my application from ESP32 using Micropython.
          I saw your example – thanks for sharing!

          I noticed that those are only “write” actions – do you have an example of a “read” action as well?
          How much is it different than connecting Python application (say running on Windows)?
          Thanks,
          Eyal Rozenblat

          Reply
  1. Well done Guys! You really nail it when choosing new topics to cover. I look forward to following this series & learning more about Firebase related applications.

    Reply
  2. You are genius! Thanks for sharing so much know-how with the community, that’s unique!!!! I’m more than excited to wait for much more articles from your side, I’m addicted to your stories.

    Reply
  3. Thank you, clear article. Sadly The database does not receive a single item, though the output in the serial monitor is OK and i did insert the database url and API.
    I will try and see what the problem could be but any advice is appreciated

    Reply
  4. Sorry for yet another comment on my faultfinding (just frustrated) and also apologising for a mistake I made in the URL in my previous message (mistake was only in mu message, not in the code).
    the url “https://esp32Demo/database/esp32Demo-default-rtdb/data/” does get me connected, I get the ‘ok’ in the serial port, and I can see anonymous users popping up in the firebase console…but I get no output of the values in the serial terminal. and nothing in my database. The “Firebaseready condition” is met in the main loop. It seems though the program hangs at “if (Firebase.RTDB.setInt(&fbdo, “test/int”, count))” and after a while I get “Failed, reason LOST CONNECTION”
    So I guess for some reason that if (Firebase.RTDB.setInt(&fbdo, “test/int”, count)) condition is never met

    Reply
  5. OK, succes. for some odd reason the database url I got was wrong, apparently I had to add the location of the server, so it should be “https://esp32Demo-default-rtdb.europe-west1.firebasedatabase.app/”
    and not “https://esp32Demo/database/esp32Demo-default-rtdb/data/”
    no idea why that first link I got was wrong
    Sorry for the confusion

    Reply
  6. Hello Sara and Rui.

    This demonstrations open many possibilites to do great projects…You are awesome!!!

    Beste regards,

    Rodrigo from Brasil

    Reply
      • Merci pour votre précision et votre concision dans vos explications. Continuer comme ça. Je travaille actuellement sur flutter et j’aimerais créer une application flutter au lieu d’une application web qui permettra de gérer un projet de domotique avec un ESP 32. Vois pourriez faire un tutoriel la dessus s’il vous plaît ??😀😁
        Cordialement Sanou Axel du Burkina Faso.

        Reply
  7. Opens a lot of opportunities! Very nice and clear instructions!
    Is it possible to create a dashboard to display the logged data? Any future tutorials coming up for the same?
    Thank you!

    Reply
  8. HI Sara,

    Struggling here with this project.
    Setting it up in platformio when I build I get this
    compilation terminated.
    *** [.pio\build\esp32doit-devkit-v1\lib6b4\Firebase Arduino Client Library for ESP8266 and ESP32\Firebase.cpp.o] Error 1
    I also tried settting up directly in Arduino, same failure.
    Have I missed something simple?

    Cheers Mark

    Reply
    • Hi.
      Did you insert the following line in the platformio.ini file of your project to include the library?
      lib_deps = mobizt/Firebase Arduino Client Library for ESP8266 and ESP32 @ ^2.3.7
      Do you get any other information in the serial monitor?
      Regards,
      Sara

      Reply
      • Hi Sara,

        Yes I did insert into lib defs.
        here is the error code
        Compiling .pio\build\esp32doit-devkit-v1\lib6b4\Firebase Arduino Client Library for ESP8266 and ESP32\bearssl\rsa_i62_oaep_encrypt.c.o
        In file included from .pio\libdeps\esp32doit-devkit-v1\Firebase Arduino Client Library for ESP8266 and ESP32\src/Utils.h:37:0,
        from .pio\libdeps\esp32doit-devkit-v1\Firebase Arduino Client Library for ESP8266 and ESP32\src\signer/Signer.h:37,
        from .pio\libdeps\esp32doit-devkit-v1\Firebase Arduino Client Library for ESP8266 and ESP32\src\Firebase.h:45,
        from .pio\libdeps\esp32doit-devkit-v1\Firebase Arduino Client Library for ESP8266 and ESP32\src\Firebase.cpp:33:
        .pio\libdeps\esp32doit-devkit-v1\Firebase Arduino Client Library for ESP8266 and ESP32\src/common.h:39:18: fatal error: WiFi.h: No such file or directory

        Reply
      • Hi Again,

        I just removed the ifndef code the ensure it was looking for wifi.h
        then I get
        Compiling .pio\build\esp32doit-devkit-v1\lib6b4\Firebase Arduino Client Library for ESP8266 and ESP32\bearssl\rsa_oaep_unpad.c.o

        Cheers

        Mark

        Reply
  9. Thank you, this article came just in time to me. Is it possible that an ESP32 gets a trigger, when data changes? Let’s say, some app writes data into Firebase, and the ESP32 gets to know about it, instead of polling. For me this would be a great information in one of the following tutorials.

    Again, thank you for this wonderful work!

    Reply
  10. Hi Sara,
    wel descrived issue an I think it could be useful for me in the future.
    I connected by “https://meteo-f3511-default-rtdb.europe-west1.firebasedatabase.app/”
    but in the serial monitor I get only; ADMIN_ONLY_OPERATION.
    Something is wrong in my config, but what?
    Please help.
    Renzo Giurini

    Reply
  11. Hello there. Really nice tutorial. I like yours very much, because they are so elaborate. I also purchased your “Learn ESP32…” and I learned a lot from it. I also did this example and it works nice. The only problem is, that it takes about 80% of available FLASH for programming. Can this be reduced in some simple way?

    Thanks for all your effort and looking forward to your next example.

    Best regards, Srecko (Lucky)

    Reply
  12. Thanks Sara, great tutorial.

    One note of caution about the library Firebase Arduino Client Library for ESP8266 and ESP32 by Mobitz

    I already had this installed as I’ve played with Firebase before. When I checked it was still there, I updated to the latest version. However, when I tried to compile for ESP32 it crashed, pointing to this library as the source of the problem. Compiled OK for ESP8266.

    I looked back through the tutorial and noticed from your screenshot that you were using an older version of the library v2.3.7. I rolled back to this version and it compiles fine; I have data flowing into the Firebase rtdb

    Looks like something got broken in the later version(s) of the library, at least for ESP32 (though ESP8266 still looks OK). If your readers have the same problem, this might save them a bit of time.

    Looking forward to building the web app next. Keep up the good work!

    Philip.

    Reply
  13. It’s Great tutorial , wish for u good luck
    i need ur help if that possible
    i have Arduino mega and esp 32 need to connect the mega to Firebas and mobile app
    for example i have LED on mega i want to control it locally from arduino and from the mob app
    my big problem is synchronising the data between Mega and ESP
    if u can help with quick ideas i appreciate that
    thanks in advance

    Reply
    • Hi.
      Do you really need to use the Arduino Mega?
      You can control an LED with the ESP32 without using an Arduino.
      But, if you really need the Arduino, you can establish a serial communication between the two boards.
      We don’t have any tutorial about serial communication at the moment.
      You can search for “ESP32 serial communication with Arduino”.
      Regards,
      Sara

      Reply
  14. Another great tutorial Sara!!!
    Random Nerds Tutorials teach all ages how to program micro devices. I’ve followed you for several years now, and have learned so much. Quite a difference from the 70’s, 80’s, & 90’s when programmers were very protective of their precious code and not willing to share with beginners. I love your attitude of sharing, because it helps us all contribute to create amazing software.
    Thanks for teaching, sharing, and contributing to the software community for the ESP32 and ESP8266!
    Joel

    Reply
  15. So I am clearly doing something wrong as it working for you all !
    I am connecting to the FireBase ok but it fails on begin

    Connecting to Wi-Fi……..
    Connected with IP: 192.168.1.150

    Sign up – ok
    Firebase.begin
    Token info: type = id token, status = on request
    Token info: type = id token, status = error
    Token error: code: 400, message: bad request

    I made sure the database was set as Autonomous and nothing else….

    Any pointers would be appreciated !

    Reply
  16. Sara,

    Thanks for the quick response. I double checked and still failed. I then deleted the project and recreated it with different name and API key but the same thing. If I put an illegal URL or API key, it gets through the Firebase.begin and hangs on the FirebaseReconnectWiFi which is understandable.
    Anonymous is enabled and looking on the database connection is registered that anonymous has made a connection.

    Reply
    • I have the same problem with you, with

      Token info: type = id token, status = on request
      Token info: type = id token, status = error
      Token error: code: 400, message: bad request

      that kind of error, it made some anonymous users, but still nothing in the Realtime Database and the Serial Monitor

      Reply
      • Hi.
        Check the project API key, and database URL.
        If it still doesn’t work, try downgrading the ESP Firebase Client library to version 2.3.7
        Regards,
        Sara

        Reply
    • Hi,
      Please downgrade your ESP Firebase Client library to version 2.3.7.
      Go to Sketch > Library > Manage Libraries, search for ESP Firebase Client library and downgrade to version 2.3.7.
      Let me know if this solves the issue.
      Regards,
      Sara

      Reply
  17. Hi Sara,

    I rebuild your project and every works out well 🙂
    I adapted it quite a little so that I don’t print a text specific to a firebase data value, but control an LED. Also I power my ESP32 with extern power.
    All works well. But when I disconnect my PC connection from ESP32 it doesn’t work anymore. When I reconnect it, it works and the LED reacts to the changes in the database.

    Do you have any idea how the Serial.monitor could affect the working code??
    Greatful for every hint

    Reply
    • Hi.
      After power it with an external power supply, press the RST button so that it starts running the code.
      Also, make sure it is still in the range of your wi-fi router to be able to connect to the internet.
      Regards,
      Sara

      Reply
      • thanks a lot Sara for this astonishing fast reply! Your hint with the power gave me the right point for solving the problem. As I figured out it seems that I exaggerated the quality of my external power supply. I checked it via oscilloscope and I noticed some spikes. Quite surprised that my usb port delievers more stable voltage.

        Reply
  18. Hi Sara, I had the same error that was driving me crazy.
    Token info: type = id token, status = on request
    Token info: type = id token, status = error

    As you mentioned, I downgraded ESP Firebase to 2.3.7, it worked. thanks

    Reply
  19. The firebase series is innovative and shows easy approach to web hosting, it would be great to combine the peripherals control and indication with other topics; such as web authentication allowing certain google accounts to login and monitor data for example, and ota section to update esp board firmware. Keep up the good work.

    Reply
  20. hi
    I followed your guide and now cant upload to my esp32
    I get the error “the selected serial port Failed to execute script esptool
    does not exist or your board is not connected” or port is busy

    Reply
    • Hi.
      Double-check your board is not opened in another Arduino IDE window and make sure the serial monitor is closed when trying to upload the code.
      Also, make sure you’re using a good USB cable with data wires.
      Regards,
      Sara

      Reply
  21. Hi Sara,

    I need help. How can I input path from variable:
    Your example:
    if (Firebase.RTDB.setInt(&fbdo, “test/int”, count)){

    My problem:
    String path1 = “20210001”;
    String path2 = “/test”;
    I want to get like this:
    if (Firebase.RTDB.setInt(&fbdo, path1+path2, count)){
    to have path like:
    if (Firebase.RTDB.setInt(&fbdo, “20210001/test”, count)){

    Please help Sara,

    Thank you.

    Reply
    • Hi.

      You need to convert the path to a char.
      You can create another variable with the concatenation of the two paths:
      String path1 = “20210001”;
      String path2 = “/test”;
      String finalPath = path1 + path2;

      Then, use finalPath as follows:
      if (Firebase.RTDB.setInt(&fbdo, finalPath.c_str(), count)){

      I hope this helps.
      Regards,
      Sara

      Reply
  22. Hi Sara,
    Thank you for supporting us with this project
    I used your code, it’s perfect and everything is working normally, but after 1 hour it stops sending data to Realtime firebase and shows this message

    Token error: code: 400, message: INVALID_EMAIL
    Token info: type = id token, status = on request
    Token info: type = id token, status = error
    Token error: code: 400, message: INVALID_EMAIL

    thanks if support me

    Reply
  23. Hi, I really liked this implementation. I bought the entire course and I am really progressing. I implemented the ESP32 based firebase real database. However, the issue is that everytime it updates the data on the firebase, the old values are flush out, only new values are seen on the firebase console. Can you suggest what to do to save the previous values on the firebase?

    Thank you in advanced.

    Reply
  24. Hi Sara; I like your Firebase examples and tutorial. This is exactly what I have been looking for, to enable an on-going project. Thanks!

    As a started I tried your example. I am using VS Code. Everything is compiling, and I appear to get connection to the Firebase database (it returns “OK” and I can see the anonymous user connection on Firebase). The problem is I am getting various errors depending on what version of the Firebase ESP Client I use.
    As installed the version is 3.1.0, and causes a “path not exist” error.

    If I change it to use the suggested version (2.3.7) then I get a “data type mismatch” error.

    And if I use the version you say you are using (in the comments above), I get the following error:

    Token info: type = id token, status = on request
    Token info: type = id token, status = error
    Token error: code: 400, message: bad request

    any chance you could shed some light on what is going on?

    Thanks!

    Reply
    • Hi.
      Make sure you’re installing the “Firebase Library for ESP32 and ESP8266”.
      Make sure you’re inserting the right project API key and database URL. Additionally, double-check your database rules.
      Regards,
      Sara

      Reply
  25. Thanks Sara;
    I am installing “Firebase Arduino Client Library for ESP8266 and ESP32 Version 3.1.0” I have checked and triple checked both the API key and Database URL. They appear to be correct.

    I set the rules per you “ESP32 Data Logging to Firebase Realtime Database” article. I double checked them, and they appear to be correct

    I am seeing the connection in the “Authentication” window, and I get a message indicating that the initial connection is has happened. The problem is when I try to post data to the database, I get a failure. Been reading some of the documentation on Firebase, but I’m not sure what to look for and have not come across anything to solve my problem.

    Robert Holt

    Reply
    • Hi.
      The database rules should be the default for this project. The other project database rules won’t work for this one.
      Or alternatively, use the following:
      {
      “rules”: {
      “.read”: true,
      “.write”: true
      }
      }

      Reply
  26. Sara;
    I have tried both demos, with both sets of rules, and can’t seem to get it to work. I suspect there is a setup problem or a version problem, with my computer. Just can’t figure it out. I have gone to the Firebase documentation, and VS Code documentation with no success.

    Reply
  27. Hi, i am getting
    “API key not valid. Please pass a valid API key.”
    I have copied the same API as shown in the tutorial can any one please help?

    Reply
  28. Hi Sara,

    Even tough everything is same as described above, I receive this problem with authentication:

    Token info: type = id token, status = on request
    Token info: type = id token, status = error
    Token error: code: 400, message: INVALID_EMAIL
    Token info: type = id token, status = error

    I try to connect anonymously, why would I get an invalid email fault?

    Thank you.

    Best regards,
    İrem

    Reply
    • Hi.
      Check that you have anonymous authentication enabled on your Firebase project.
      On your Firebase project console, go to Authentication > Users and check that you have anonymous user enabled.
      Also, check that the database rules allow writing/reading for any user.
      Regards,
      Sara

      Reply
  29. Hi Sara, probably mine is a nonsense question, but I try.
    It is possible to connect ESP32 to Firebase though a smartphon and use it as a router?
    Thanks
    Renzo

    Reply
      • Oh no, use smartphone as a router instead of normal route, wire connected.
        I.E. using phone number or ID number of phone.

        Renzo

        Reply
        • Hi.
          You can connect the ESP32 to the internet by connecting it to your smartphone if it is set as a hotspot.
          I hope this answers your question.
          Regards,
          Sara

          Reply
          • Thank Sara,
            I connected to my Android, in the sketch I substituite SSID with AndoidAD8865 and PSW. I get on the Serial monitor an address 192.168.43.15 but if I put this address on the browser I don’t get anything.
            My project is this.
            I have a battery powered weather station and I monitor data in a display ST7789,
            Data of course are Temp, Press and I calculate min and max temp of the day and the hour that I get by Internet with NTP service,
            Before going to sleep I save this data on the EEPROM.
            I want to save this data on Firebase, as well when I am out of range my router, so i think to use the Cellphone.
            I noticed that Firebase doesn’t accept float data bigger than 127.0( half byte), is it correct?
            I know that your answer could be a new lesson, so I ask if in your e-book may I find the reply?
            Thank
            Renzo

          • Hi Renzo.
            What project are you currently running?
            If you don’t have any web server code on your ESP, it won’t show anything when you access its IP address.
            If you’re using Firebase, the data should be published to Firebase when it is connected to your smartphone, as it would if it was connected to a “regular router”.
            So, check the Firebase database to see if it is publishing the data.
            Regards,
            Sara

          • Hi Sara,
            I use your Firebase sketch with data read by a BME280.
            All runs well when I connect with the router but I don’t know how use a Smartphone instead.
            In any case Firebase accecpt temperature(i.e. 22.7= bme.readTemperature()) but not pressure(i.e, 1015.5 =bme.readPressure()).
            Bye
            Renzo

  30. Hello
    I have a rain sensor connected to an esp 8266

    Here is the code :
    #include <SoftwareSerial.h>
    #include <ArduinoJson.h>

    const int capteur_D = 4;
    const int capteur_A = A0;

    int val_analogique;
    SoftwareSerial nodemcu(5, 6);
    #define rainfall A0
    #define pin A0

    void setup()
    {
    Serial.begin(115200);
    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
    }

    pinMode(capteur_D, INPUT);
    pinMode(capteur_A, INPUT);
    Serial.begin(115200);
    nodemcu.begin(115200);
    delay(1000);
    }

    void loop()

    {
    StaticJsonBuffer jsonBuffer;
    JsonObject& data = jsonBuffer.createObject();

    delay(2000);

    if(digitalRead(capteur_D) == LOW)
    {
    Serial.println(“Digital value : It is raining. Take neccessary precautions”);
    delay(1000);
    }
    else
    {
    Serial.println(“Digital value : It is dry”);
    delay(1000);
    }

    data.printTo(nodemcu);
    jsonBuffer.clear();

    if (Serial.available()) {
    Serial.write(Serial.read());
    }
    data[“capteur_D”]= capteur_D;
    data[“capteur_A”] = capteur_A;

    val_analogique=analogRead(capteur_A);
    Serial.print(“Analog value : “);
    Serial.println(val_analogique);
    Serial.println(“”);
    delay(1000);
    }

    How can I send the data to firebase please ?

    Reply
    • Hello, i had the same issue and found the solution : in Realtime Database => Rules
      use the following :
      “rules”: {
      “.read”: “true”,
      “.write”: “true”,
      }

      Reply
  31. Hi Sara,
    in your original sketch I change your database path test/init, test/float with new names i.e, test/temp,test/press etc,
    In the smathphone I see these new paths and values, but remain also the old paths.
    How may I delete them.
    Thank

    Reply
  32. hi Sara

    in this example every value overwrites the other in the node right? I was reading firebase document and its saying that “set” method will store the value in the node but “push” method creates a unique key and moves the node values inside that key ,
    how can I do that in esp32 library ?

    Reply
  33. Hi Sara,

    I am using ESP32 -WROOM-32 board. Used the above code while compiling I am getting following error.

    I am selecting DO IT ESP32 DEVKIT V1.

    In file included from C:\Users\Admin\AppData\Local\Arduino15\libraries\SD\src/utility/Sd2Card.h:26:0,
    from C:\Users\Admin\AppData\Local\Arduino15\libraries\SD\src/utility/SdFat.h:29,
    from C:\Users\Admin\AppData\Local\Arduino15\libraries\SD\src/SD.h:20,
    from c:\Users\Admin\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/FirebaseFS.h:64,
    from c:\Users\Admin\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase.h:34,
    from c:\Users\Admin\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:43,
    from D:\ESP32_Developments\Firebase080223\sketch_feb8a\sketch_feb8a.ino:9:
    C:\Users\Admin\AppData\Local\Arduino15\libraries\SD\src/utility/Sd2PinMap.h:524:2: error: #error Architecture or board not supported.
    #error Architecture or board not supported.
    ^
    Multiple libraries were found for “SD.h”
    Used: C:\Users\Admin\AppData\Local\Arduino15\libraries\SD
    Not used: C:\Users\Admin\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.6\libraries\SD
    exit status 1

    Compilation error: exit status 1

    Reply
  34. please I need help! I want to upload .txt file to firebase using esp32, I was able to send and receive String and Int successfully.

    Reply
  35. Hi Sara, can I ask you for your help? I’m using ESP32 to build a dripping project for a garden. While trying to store data to the firebase, I noticed that my code ran perfectly on Arduino (the serial monitor showed the result) but the data weren’t shown in my firebase :((( Here’s my code:
    #include <ArduinoJson.h>
    #include <Firebase_ESP_Client.h>
    #include <WiFi.h>
    #include “TimeLib.h” // for update/display of time
    #include <NTPClient.h>
    #include “WiFiUdp.h”

    WiFiUDP ntpUDP;
    NTPClient timeClient(ntpUDP, “pool.ntp.org”);

    //Provide the token generation process info.
    #include “addons/TokenHelper.h”
    //Provide the RTDB payload printing info and other helper functions.
    #include “addons/RTDBHelper.h”

    #define WIFI_SSID “”
    #define WIFI_PASSWORD “”

    #define FIREBASE_HOST “”
    #define FIREBASE_AUTH “”

    //Define a FirebaseAuth object needed for authentication
    FirebaseAuth auth;
    //Define a FirebaseConfig object required for configuration data
    FirebaseConfig config;
    //Define FirebaseData object
    FirebaseData firebaseData;
    bool signupOK = false;

    String timeNow;

    void connectWifi() {
    Serial.printf(“Connecting to %s \n”, WIFI_SSID);
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

    while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(“.”);
    }
    Serial.println();
    Serial.print(“Connected, IP address: “);
    Serial.println(WiFi.localIP());
    }

    void connectFirebase() {
    Serial.printf(“Start connecting Firebase: “);
    /* Assign the api key (required) /
    config.api_key = FIREBASE_AUTH;
    /
    Assign the RTDB URL (required) /
    config.database_url = FIREBASE_HOST;
    //check signup status
    if (Firebase.signUp(&config, &auth, “”, “”)){
    Serial.println(“ok”);
    signupOK = true;
    }
    else{
    Serial.printf(“%s\n”, config.signer.signupError.message.c_str());
    }
    /
    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;

    Firebase.begin(&config, &auth);
    Firebase.reconnectWiFi(true);
    Serial.println(“Connect Firebase success”);
    Serial.println();
    }
    void setDataField(String fieldName, float air_humidity, float radiation, float soil_humidity30, float soil_humidity60, float temperature){
    Serial.println(“Start setDataField ” + fieldName);
    String measured_data = fieldName + “/measured_data/” + timeNow;
    Firebase.RTDB.setFloat(&firebaseData, measured_data + “/air_humidity”, air_humidity);
    Serial.println(measured_data + “/air_humidity : ” + air_humidity);
    Firebase.RTDB.setFloat(&firebaseData, measured_data + “/radiation”, radiation);
    Serial.println(measured_data + “/radiation : ” + radiation);
    Firebase.RTDB.setFloat(&firebaseData, measured_data + “/soil_humidity30”, soil_humidity30);
    Serial.println(measured_data + “/soil_humidity30 : ” + soil_humidity30);
    Firebase.RTDB.setFloat(&firebaseData, measured_data + “/soil_humidity60”, soil_humidity60);
    Serial.println(measured_data + “/soil_humidity60 : ” + soil_humidity60);
    Firebase.RTDB.setFloat(&firebaseData, measured_data + “/temperature”, temperature);
    Serial.println(measured_data + “temperature : ” + temperature);

    Serial.println(“End setDataField ” + fieldName);
    }

    void setTimeDay() {
    timeClient.begin();
    // Set offset time in seconds to adjust for your timezone, for example:
    timeClient.setTimeOffset(25200);// GMT +7
    timeClient.update();
    time_t epochTime = timeClient.getEpochTime();
    Serial.print(“Epoch Time: “);
    Serial.println(epochTime);

    String formattedTime = timeClient.getFormattedTime();
    Serial.print(“Formatted Time: “);
    Serial.println(formattedTime);

    //Get a time structure
    struct tm *ptm = gmtime ((time_t *)&epochTime);

    int monthDay = ptm->tm_mday;
    int currentMonth = ptm->tm_mon + 1;
    int currentYear = ptm->tm_year + 1900;

    //Print complete date:
    String currentDate = String(currentYear) + “-” + String(currentMonth) + “-” + String(monthDay);
    Serial.print(“Current date: “);
    Serial.println(currentDate);

    timeNow = currentDate + “/” + formattedTime;
    Serial.print(“timeNow: “);
    Serial.println(timeNow);
    delay(5000);
    }

    void setup() {
    Serial.begin(115200);
    connectWifi();
    connectFirebase();
    setTimeDay();
    setDataField(“testUser/field1”, 8.14, 2.5, 30.5, 14.5, 31.0);
    }

    I already checked: i allowed read/write for database rules and my API key are correct. It also showed this message
    Token error: code: 400, message: bad request
    What happened?

    Reply
  36. Hi,

    Following, 2. Set Authentication Methods to enable Anonymous as described in paragraph 3, however, I’m getting “Error updating Anonymous”.

    Can you help please.

    Reply
  37. Hi everybody,

    I use the FB to store some values like temperature, time, variables,…
    When i use on few sensors like temperature the FB works perfectly, but i added some idea and now it’s impossible to be connected with my Internet box in my home, but if i use the my phone for intenet access it works correctly. i have remove some parts of my code to keep only temperature sensors, the code works again. I don’t understand what’s happen.
    #include <Arduino.h>
    //#include <Wire.h>
    #include<RTClib.h>
    RTC_DS3231 rtc;
    #include <FastLED_NeoPixel.h>
    #include <DallasTemperature.h>
    #include <OneWire.h>
    #include <WiFi.h>
    #include <Firebase_ESP_Client.h>

    I type the libraries used for my projet.
    Could you help me?

    Jerome

    Reply
  38. Hi Sara I have a problem and I would appreciate it if you can give me any pointers on where the issue might be.
    I used your brilliant code with my esp32 and its about soil moisture sensor nothing else
    so previously I had a problem with firebase’s token since it wasnt refreshing and I couldnt even refresh it manually so I just downgraded my firebase client library to 2.3.7 and the error disappeared but im stuck with a new error and this appears in my serial monitor

    Connected with IP: 192.168.255.000
    Guru Meditation Error: Core 1 panic'ed (LoadStoreError). Exception was unhandled.

    here is the code

    #include <Arduino.h>
    #include <WiFi.h>

    #include <Firebase_ESP_Client.h>

    //Provide the token generation process info.
    #include "addons/TokenHelper.h"
    //Provide the RTDB payload printing info and other helper functions.
    #include "addons/RTDBHelper.h"
    // The pin connected to the sensor
    #define AOUT_PIN 33

    // Insert your network credentials
    #define WIFI_SSID ""
    #define WIFI_PASSWORD ""

    // Insert Firebase project API Key
    #define API_KEY " "

    // Insert RTDB URLefine the RTDB URL */
    #define DATABASE_URL ""

    //Define Firebase Data object
    FirebaseData fbdo;

    FirebaseAuth auth;
    FirebaseConfig config;

    unsigned long sendDataPrevMillis = 0;
    bool signupOK = false;

    void setup(){
    Serial.begin(115200);
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("Connecting to Wi-Fi");
    while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(1000);
    }
    Serial.println();
    Serial.print("Connected with IP: ");
    Serial.println(WiFi.localIP());
    Serial.println();

    /* Assign the api key (required) */
    config.api_key = API_KEY;

    /* Assign the RTDB URL (required) */
    config.database_url = DATABASE_URL;

    /* Sign up */
    if (Firebase.signUp(&config, &auth, "", "")){
    Serial.println("ok");
    signupOK = true;
    }
    else{
    Serial.printf("%s\n", config.signer.signupError.message.c_str());
    }

    /* Assign the callback function for the long running token generation task */
    config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

    Firebase.begin(&config, &auth);
    Firebase.reconnectWiFi(true);
    }

    void loop(){
    int value = analogRead(AOUT_PIN); // read the analog value from sensor
    int moisture = map(value,0,4095,100,0);
    if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)){
    sendDataPrevMillis = millis();
    // Write an Int number on the database path test/int
    if (Firebase.RTDB.setInt(&fbdo, "test/int", moisture)){
    Serial.println("PASSED");
    Serial.println("PATH: " + fbdo.dataPath());
    Serial.println("TYPE: " + fbdo.dataType());
    }
    else {
    Serial.println("FAILED");
    Serial.println("REASON: " + fbdo.errorReason());
    }

    }
    }

    Reply
    • Hi.
      That issue may be caused by a lot of different reasons.
      I would suggest you try using a different analog pin.
      Regards,
      Sara

      Reply
  39. Is there a way to just update data each time insted of saving a new entry each time ?I need to use the data in an android studio aplication and dont need the data to show each entry made.

    Reply
  40. Hi Sara,
    It may be worth mentioning that signup will create a new record into Firebase authentication for every time the app runs. I may say perhaps advise discourage to signup. I was banging my head trying to work out why the app stopped working for no reason and it was due to me reaching the max number of users allowed as I had so many autonomous users added.

    Reply
      • Thanks a lot Sara,
        I wonder if you can suggest to me how to convert data coming from ble comms transferred to RTDB , I thought using the string should be ideal but I am struggling to convert the received data arriving to callback. Thanks in advance.
        static void notifyCallback(
        BLERemoteCharacteristic *pBLERemoteCharacteristic,
        uint8_t *pData,
        size_t length,
        bool isNotify)
        {
        Serial.print(“Notify callback for characteristic “);
        Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
        Serial.print(” of data length “);
        Serial.println(length);
        Serial.print(“data: “);
        Serial.write(pData, length);
        Serial.println();
        ???????(?,?,?)
        }

        Reply
  41. Moi j’ai un problème de compilation lorsque j’utilise ESP 32 il m’écrit chaque fois une erreur de compilation pour esp32 alors que j’ai respecte tout les règles du tutoriel

    Reply
  42. Here’s the translated sentence:

    “Hello, and thank you for this article. I’m receiving data on Firebase and would like to control the relay via Firebase, but I’m stuck on the code. Could you help me? Thank you.”

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.