ESP32 Firebase

Hello readers, I hope you all are doing great. In this tutorial, we will learn how to access Firebase (a real-time database) to store and read values or data with ESP32.

It is Google’s mobile application development platform that can be used to can access, monitor and control ESP32 from anywhere in the world with its (firebase) real-time database.

Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

What is Firebase?

Firebase real-time database is a development platform provided by Google which included multiple services to manage and authenticate data.

Firebase is basically a mobile and web app development platform I as works great with Android APIs) that includes features like firebase cloud, real-time data and Firebase authentication etc.

As per Firebase’s official documentation (https://firebase.google.com/docs/database), whenever a user creates a cross-platform application like with Android, or Apple, JavaScript SDKs, all the clients share a single.

Fig. 1 Firebase Real-time database and ESP32

The main features of the Firebase Real-time database are:

  • Firebase applications remain responsive even in offline mode. If any changes are missed during the offline mode, then after the connectivity is reestablished those changes will be automatically synchronized.
  • Firebase Real-time database makes it easier to access the database from a web browser or a mobile device.
  • Unlike hypertext transfer protocol requests, Firebase RTDB uses data synchronization which makes it possible to update the changes in the database within milliseconds.

Role of Firebase Realtime Database in IoT

The IoT or Internet of Things is the interconnection of physical objects or devices with sensors and software accessing capabilities to communicate data or information over the internet.

To build an IoT network, we need an interface medium that can fetch, control, and communicate data between sender and receiver electronics devices or servers.

Firebase real-time database provides a platform to store data collected from sensors at the level device. Firebase works great with Android APIs.

Firebase is particularly useful in data-intensive Internet of things (IoT) applications to store from sensors and synch that data between users in real-time. For simplicity or better understanding we can say that it is a cloud service provided by Google for real-time collaborative apps.

Project Overview

  • In this tutorial we are going to create a Firebase project with real-time database to read and store data with ESP32. Steps included to achieve the target are; creating a firebase project, storing data from ESP32 to firebase real-time Database, Reading data from firebase real-time database with ESP32.

Prerequisites

  • ESP32 development board
  • Arduino IDE
  • Necessary Library (Firebase ESP Client)
  • A Google account to access Firebase
 

Getting Started with Firebase

  • Create a project

The steps involved in creating a Firebase project are:

Fig. 2 Get started

  • Click on Create a project.

Fig. 3 Create a project

  • Assign a name to your project and accept the terms and conditions then click on the continue

Fig. 4 project name

  • Disable the “Enable Google Analytics” option and click on real-time.

Fig. 5 Enabling Google Analytics

  • Now your project is ready click the

Fig. 6 Project Created successfully

Authentication

    • Next we need to set the authentication methods for the app.

As per the official firebase documentation at: https://firebase.google.com/docs/auth , the identity of a user is required by most online services or mobile applications or we can say , it handles authentication process and logging in (in this tutorial, the ESP32). Getting to know the identity of a user enables an application to save user data securely in the cloud and provide a consistent personalized service across all of the customer's devices (android phones, computers, applications etc).

  • Click on

Fig. 7 Authentication

  • You will be redirected to a new page, click on ‘get started.
  • There are multiple methods available to authenticate you account, as shown below.
  • Select any of the authentication method.

Fig. 8 Select authentication method

Next thing is creating a real-time database for the project.

  • Creating a Real-time Database
    • Click on the Real-time database given at the left sidebar.

Fig. 9 Real-time database

  • Then, click on Create Database.

Fig. 10 Creating database

  • Select your nearest location.

Fig. 11

  • Select the Start in test mode option and click on enable

Fig. 12 select location

  • Now your database is successfully created. You will be redirected to a new page containing the database URL.
  • Copy the URL and paste in your ESP32 code.
  • Now the next requirement is getting the API key.

Project API

    • Go to left sidebar and click on Project Overview and then project setting.

Fig. 13 Accessing project API key

  • Copy the web API key and paste in your ESP32 code.
  • That’s all about creating a Firebase account, project, and verification. Now, we are ready to interface the database and ESP32 module.

Programming with Arduino IDE

We are using Arduino IDE to compile and upload code into the ESP32 module. You must have the ESP32 board manager installed on your Arduino IDE to program the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:

https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html

Steps to add the necessary libraries in Arduino IDE:

  • Go to Tools >> Manage Libraries.

Fig. 14 manage libraries

  • Search for the Firebase ESP Client library in Library Manager and click Install.
  • We are attaching an image, where we are installing the Firebase ESP-Client (2.3.7 version) library.

Fig. 15 Install Firebase ESP Client Library

Arduino IDE Code ( To store data from ESP32 to Firebase Database)

//--add necessary header files

#include <WiFi.h>

#include <Firebase_ESP_Client.h>

#include "addons/TokenHelper.h" //Provide the token generation process info.

#include "addons/RTDBHelper.h" //Provide the real-time database payload printing info and other helper functions.

// Insert your network credentials

#define WIFI_SSID "replace this with your netwrok SSID"

#define WIFI_PASSWORD "replace this with your wi-fi password"

// Insert Firebase project API Key

#define API_KEY "replace this with your API key"

// ----Insert real-time database URL

#define DATABASE_URL "replace this with your project URL"

//----Define Firebase Data object

FirebaseData fbdo;

FirebaseAuth auth;

FirebaseConfig config;

int value = 10;

bool signupSuccess = false;

unsigned long sendDataPrevMillis = 0;

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(100);

}

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 status

if (Firebase.signUp(&config, &auth, "", ""))

{

Serial.println("ok");

signupSuccess = 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() && signupSuccess && (millis() - sendDataPrevMillis >

10000 || sendDataPrevMillis == 0))

{

sendDataPrevMillis = millis();

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

{

Serial.println("PASSED");

Serial.println("PATH: " + fbdo.dataPath());

Serial.println("TYPE: " + fbdo.dataType());

}

else

{

Serial.println("FAILED");

Serial.println("REASON: " + fbdo.errorReason());

}

value++;

}

}

Before uploading the code in ESP32 board there are some changes you need to make which includes:

  • Adding network credentials
  • Inserting API key
  • Inserting Firebase project URL
  • Installing necessary library files

Code Description

  • The libraries we are using are:
    • The first one is h, which is used to enable the Wi-Fi module and hence wireless network connectivity.
    • Another library we are using is the h which is responsible for interfacing ESP32 and Firebase Real-time Database.

Fig. 16 Header files

  • We also need to add two helper libraries (required by the Firebase library).
  • The TokenHelper library is responsible for managing the token generation process.
  • On the other hand, the RTDBHelper library is responsible for providing helper functions to print data coming from the Firebase database.

Fig. 17 Helper libraries

  • Next, we need to insert the project API key obtained from the Firebase project setting page.

Fig. 18 Insert API key

  • Similarly, insert the RTDB (real-time database) URL.

Fig. 19 RTDB URL

  • Next, we are defining three firebase data objects, responsible for linking App to Firebase.

Fig. 20 Firebase Data Objects

  • Enter the network credentials in place of SSID and PASSWORD.

Fig. 21 Enter Network credentials

  • Next, we are defining some variables to store integer value, status of sign up to firebase account, and delay element etc.

Fig. 22 variable declaration

 

Setup

  • Initialize the serial monitor at 115200 baud rate for debugging purpose.
    • begin() function is used to initialize the Wi-Fi module with Wi-Fi credentials used as arguments.
    • The While loop will continuously run until the ESP32 is connected to Wi-Fi network.

Fig. 23 Initialize wifi module

  • If the device is connected to local Wi-Fi network then print the details on serial monitor.
  • localIP() function is used to fetch the IP address.
  • Print the IP address on serial monitor using println() function.

Fig. 24 Fetch/obtain the IP address

  • Here, we are assigning the API key to the firebase configuration.

Fig. 25 configuring API key

  • Similarly, the database URL is also assigned to the firebase configuration

Fig. 26 configuring database URL

  • Next, we are checking or verifying the Firebase sign-up status.
  • In the signup() function the last two arguments are empty, indicating the anonymous user.
  • If you have enabled different signup methods during the Firebase authentication method like Google account, Facebook etc then you need to add the respective credentials as argument.
  • The respective results of signup status will be printed on the serial monitor.

Fig. 27 sign up status

  • Next, you need to assign the callback function for token generation.

Fig. 28

Loop()

  • If, the sign up status is true (or Successful), then we are ready to send the data from ESP32 to Firebase Real-time database.
  • For demonstration purpose, we are sending integer value to the Firebase database. You can also send a string, float, array, sensor reading etc. as per your requirements.
  • senInt() command is used to send integer values. This command is passing three arguments first on is the firebase database object, the second argument is the database node path and the third one is the ‘value’ we are communicating to Firebase real-tie database.
  • Similarly, we can share string, float, or array etc.

Fig. 29 Loop() function

Testing

  • Open your Arduino IDE and paste the above code.
  • Change the network credentials, that is the SSID and PASSWORD as per you network setup.
  • Compile and upload the code into ESP32 development board.
  • Before uploading the code make sure that you have selected the correct development board and COM port.

Fig. 30 Select development board and COM port

  • Once the code is uploaded successfully, open the Serial monitor and select the 1115200 baud rate (as per your code instructions).
  • Make sure Wi-Fi to which your ESP device is supposed to connect is ON.
  • Go to https://console.firebase.google.com.
  • Select the project you have created.
  • Click on left sidebar and then click on Real-time Database.
  • A new page will open, containing the data uploaded from the ESP32.
  • We have attached an image below for your reference.
  • An integer value will be uploaded to the Firebase Real-time database in every 10 seconds.
  • In the image attached below, you can see three different values displaying. But only the integer value (in yellow color) is active and rest of the data is inactive.

Fig. 31 Result 1

  • The integer value is increasing by 1 in every 10 second.

Fig. 32 Result 2

  • Similarly, we can interface and upload sensor reading to the Firebase database.

This concludes the tutorial. I hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir