Getting Started with ESP32 and Firebase (Realtime Database)

Get started quickly with ESP32 and Firebase (Realtime Database) and program with Arduino IDE. Firebase is Google's mobile application development platform that includes many services for managing data from web, iOS, and Android applications. The first step in the process is to build a Firebase project with a realtime database (RTDB). The second step is to store and read values from the database with your ESP32.

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

  • ESP32 with Firebase – Creating a Web App (SOON)

What is Firebase?

Firebase logo Realtime Database

Google's mobile application development platform, called Firebase, helps you create, improve, and grow your app. Many services are available that may be used to manage data from any web, Android, or iOS application.

Using Firebase has the following advantages, as the following paragraph clearly explains:

“The tools that Firebase provides you with cover a significant portion of the services that developers would typically be required to build themselves but don't want to since they'd rather be concentrating on the app experience itself. Firebase is a toolset to build, improve, and grow your app. The list goes on and includes elements like analytics, authentication, databases, configuration, file storage, push messaging, and so forth. The services are hosted in the cloud and scale with little to no work on the developer's part.”

This paragraph was extracted from this article, which we recommend you read if you want to learn more about Firebase and what it can do for you.

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

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

This means that two ESP32 boards may be connected to separate networks, with one board storing data and the other 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 read the ESP32 to show sensor data or control outputs from anywhere in the world.

Firebase ESP32 Project Web App Project Example

Project Overview

You'll learn how to create a Firebase project with a realtime database in this tutorial, as well as how to store and read data from the ESP32 using the project.

You need to first set up a Firebase project and create a realtime database for that project in order to follow this project. The ESP32 will then be programmed to store and read data from the database. Three sections make up this tutorial.

  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
  1. Disable the setting. Enable Google Analytics for this project if needed, and then click Create Project.
Set Up Firebase Project for ESP32 and ESP8266 Step 2
  1. To set up your project, it will take a few seconds. When it's ready, click “Continue“.
Set Up Firebase Project for ESP32 and ESP8266 Step 3
  1. 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 a user's identity. To put it another way, it takes care of logging in and identifying the users (in this example, the ESP32). Knowing a user's identity enables an app to securely save user data in the cloud and provide the same personalized experience across all of the user's devices. The documentation can be read to learn more about the authentication methods.

  1. Click “Authentication“, then click “Get Started” in the left sidebar.
Set Up Firebase Project for ESP32 and ESP8266 Authentication Methods
  1. There are several authentication methods, such as email and password, Google Account, Facebook Account, and others.
Set Up Firebase Project for ESP32 and ESP8266 Authentication Methods List
  1. We may select the “Anonymous” user for testing reasons (demand authentication without requiring users to sign in beforehand by generating temporary anonymous identities). Select that choice and click “Save“.
Set Up Firebase Project for ESP32 and ESP8266 Authentication Methods Anonymous User

3. Creating a Realtime Database

Creating a Realtime Database is the next step in your project. To create the database, follow the next steps.

  1. On the left sidebar click on Realtime Database and then, click on Create Database.
Set up realtime database firebase ESP32 ESP8266 Step1
  1. Select your database location. It should be the closest to your location.
Set up realtime database firebase ESP32 ESP8266 Select Location
  1. Set up your database's security rules. Select “Start in test mode” if you are testing. In the later tutorials, you'll learn how to secure your database using database rules.
Set up realtime database firebase ESP32 ESP8266 Set Security Rules
  1. Now you can create your database. The database URL, which is highlighted in the following figure, must be copied and saved since you'll need it later in your ESP32 code.
Set up realtime database firebase ESP32 ESP8266 Database Created

Realtime Database is ready to go. You now additionally need to get the API key for your project.

4. Get Project API Key

  1. Then, on the left side of the screen, click on “Project Settings” to see the results.
Get Firebase Project API Key
  1. Copy the API Key to a safe place because you’ll need it later.
Firebase Project API key

To interface the ESP32 with the database, you now have everything ready.

Program the ESP32 to Interface with Firebase

You'll learn how to interface the ESP32 with the database when the Firebase Realtime Database has been setup.

The Arduino IDE, VS Code with the PlatformIO extension, or other suitable software may be used to program the ESP32.

Note: We recommend using VS Code with the PlatformIO extension for Firebase projects since it has all the tools necessary to create a web application that will act as a bridge between the ESP32 and Firebase. You may use the Arduino IDE, but we won't be building the web application in this tutorial.

Install the Firebase-ESP-Client Library

For using Firebase with the ESP32, there is a library called Firebase-ESP-Client that has lots of examples. This library is compatible with the ESP32 and ESP8266 boards.

In this tutorial, we'll look at simple examples of how to store and read data from a database. You may see a variety of additional examples that the library provides here. Additionally, it provides detailed documentation explaining how to use the library.

Installation – VS Code + PlatformIO

Click on the “PIO Home” icon and then select the “Libraries tab” if you're using VS Code with the PlatformIO extension. Find “Firebase ESP Client” by searching. Select the ESelect the Firebase Arduino Client Library for ESP8266 and ESP32.

Install Firebase ESP Client Library VS Code

After that, select the project you're working on by clicking “Add to Project“.

Add Firebase ESP Client Library to Project VS Code

Additionally, change the monitor speed to 115200 by adding the following line to your project's platformio.ini file:

monitor_speed = 115200
Installation – Arduino IDE

Follow the next steps to install the library if you're using the Arduino IDE.

  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: Version 2.3.7 is what we are using. Downgrade to version 2.3.7 if you have issues compiling your code with more recent library versions.

Install Firebase Arduino Client Library for ESP8266 and ESP32 by Mobitz

You are now ready to program the ESP32 board to interact with the database.

ESP32 Store Data to Firebase Database

ESP32 Firebase store data realtime database project example

The code below should be copied into your Arduino IDE. Every 15 seconds, this sketch inserts a float number and an int number into the database.

Note: The Firebase ESP Client library that we are using is version 2.3.7. Downgrade to version 2.3.7 if you are experiencing compiling issues with more recent versions of the library.

/*
  LEDEdit PRO
  Complete project details at our blog.
    - ESP32: https://lededitpro.com/getting-started-with-esp32-and-firebase-realtime-database
    - ESP8266: https://lededitpro.com/getting-started-with-esp8266-and-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());
    }
  }
}

For the project API to function, you need to insert your network credentials, URL database, and project API key.

Based on the library's basic example, this sketch was created. You may find many more examples here.

How the Code Works

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

Include the required libraries first. The WiFi.h library is used to connect the ESP32 to the internet (or the ESP8266WiFi.h library for the ESP8266 board), and the Firebase_ESP_Client.h library is used 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;

For an anonymous user, the following lines take care of signup, You used the signUp() method, and the last two parameters 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: Every time the ESP connects, it creates a new anonymous user in the anonymous user signup..

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

signupOK = true;

The library includes examples of different authentication methods, such as signing in as a user using an email and password, using the database's legacy authentication token, and so on. All of the examples of alternative authentication methods can be found here. If you end up using different authentication methods, remember to activate them in 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: setsetIntsetFloatsetDoublesetStringsetJSONsetArraysetBlob, and setFile.

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

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

Because we'll be sending an integer number in our example, we'll need to use the setInt() function as follows:

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

The database node path is the second argument, and the value you wish to pass to that database path is the last argument. You may use any other database path. In this case, we're passing the value that was saved in the count variable.

The complete snippet prints a success or failed message and stores the value in the database.

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

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

Open the Serial Monitor with a baud rate of 115200 after uploading the code, and then press the ESP32 on-board reset button so it starts running the code.

The values ought to be stored in the database, and you should get success messages if everything works as expected.

ESP32 ESP8266 Store value firebase database Serial Monitor Success

You may see the values saved on the different node paths by visiting your project's Firebase Realtime database. It saves a new value every 15 seconds. As new values are saved, the database value blinks.

ESP32 Store value firebase database Success

Congratulations! You have successfully stored data in Firebase's realtime database using the ESP32. You'll discover how to read values from the different node paths in databases in the part after this one.

ESP32 Read From Firebase Database

ESP32 Firebase read data realtime database

This section will learn you how to read data from a database. We will read the data stored in the previous step. Remember how we saved an int value in the test/int path and a float value in the test/int path?

The following example reads the values stored in the database. Copy and paste the following code into your board. To retrieve the data posted by the previous ESP32, you may use the same ESP32 board or another board.

/*
  LEDEdit PRO
  Complete project details at our blog.
    - ESP32: https://lededitpro.com/getting-started-with-esp32-and-firebase-realtime-database
    - ESP8266: https://lededitpro.com/getting-started-with-esp8266-and-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());
    }
  }
}

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

How the Code Works

The code is quite similar to the example from the previous section, but this time it reads data from a database. Take a look at this section's relevant parts.

The following Firebase RTDB functions may be used to read data from a specific node: get, getInt, getFloat, getDouble, getBool, getString, getJSON, getArray, getBlob, and getFile.

All of the following conditions must be satisfied for these functions to return a boolean value indicating the operation's success, which will be true:

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

The database data’s payload (response) can be read or accessed through the following Firebase Data objects functions: fbdo.intDatafbdo.floatDatafbdo.doubleDatafbdo.boolDatafbdo.stringDatafbdo.jsonStringfbdo.jsonObjectfbdo.jsonObjectPtrfbdo.jsonArrayfbdo.jsonArrayPtrfbdo.jsonData (for keeping parse/get result), and fbdo.blobData.

It will return empty (string, object, or array) if you use a function that doesn't match the database's returned data type.

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

The following code snippet shows how to get an integer value stored in the test/int node. First, we use the getInt() function; next, we use fbdo.dataType() to check if the data node is an integer; and lastly, we use fdbo.intData() to get 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

your board after uploading the code. The Serial Monitor should then be open with a baud rate of 115200. The values saved in the database will be printed after a few seconds.

ESP32 Store value firebase database Serial Monitor Success

Conclusion

Congratulations! You've created a Firebase project with a Realtime Database and learned how to store and read data from the database using the ESP32 in this tutorial.

We've stored sample values in the database to make things easy. The goal is to save useful data, such as sensor readings or GPIO states.

Then, using another ESP32, you can access the database to get the data, or you can create a Firebase web app to use the data to show sensor readings or operate the ESP32 GPIOs from anywhere in the world. This article will teach you how to create a Firebase Web app from scratch.

If you like ESP32, you may also like:

We hope you find this tutorial useful. Thanks for reading.

Oh hi there It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam! Read our privacy policy for more info.

Leave a Reply

Your email address will not be published. Required fields are marked *

Developing IoT Projects with ESP32

Automate your home or business with inexpensive Wi-Fi devices