How to establish a connection with Firebase using ESP32

ESP-32 is a widely used microcontroller that has built-in Wi-Fi and Bluetooth connectivity features. ESP-32 is often combined with temperature sensors to monitor the temperature and humidity. Since ESP-32 provides Wi-Fi connectivity, we can easily establish a connection with cloud storages and store our data for later use.

Technologies used

The technologies we will be using to push our data from ESP-32 to Firebase are:

  • ESP-32 microcontroller

  • DHT-22 temperature sensors

  • Firebase

  • Arduino IDE

The temperature sensor we use here is DHT-22 because it allows us to record temperatures slightly below 0 degrees Celsius (-40o to 125o). You can use any temperature sensors that are compatible with ESP-32 and satisfy your requirements.

We use Arduino IDE because ESP-32 supports Arduino .ino sketches, which can be easily developed and tested in Arduino IDE. Arduino IDE uses a variant of C++ with some additional functions and methods.

Setting up Firebase

Here, we will use real-time database services provided by Firebase. You can set up Firebase’s real-time database by following the steps shown below:

Firebase console
Firebase console
1 of 10

Code for sketch

To begin with the code, we first import the libraries required to connect to Firebase.

#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <FirebaseESP32.h>
#include "DHT.h"
  • Lines 1–3: We import the libraries required to establish a connection with Wi-Fi.

  • Line 5: We import the built-in library in Arduino IDE, which allows us to connect and send requests to the Firebase storage services.

  • Line 6: We import the library for our temperature sensors, which allows us to read data from the temperature sensor.

After we have imported the libraries, we define the constraints for temperature sensors and Firebase connection.

#define DHTTYPE DHT22
//Paste you Realtime database url here (refer to slide 10)
#define FIREBASE_HOST "##################"
//Paste your web api key (refer to slide 9)
#define FIREBASE_AUTH "##################"
  • Line 1: We define the DHT sensors we use with our ESP-32.

  • Line 3: We define the URL of our real-time database cloud storage.

  • Line 4: We define the web API key, which allows us to push data to the cloud storage.

Now, we define the SSID (Wi-Fi network name) and password, allowing us to connect to the Wi-Fi.

//Enter your wifi details
const char *ssid = "######"; //e.g: "Office_wifi"
//Enter the password details for the wifi network
const char *password = "#######"; //e.g: "1234"
  • Line 2: We define the Wi-Fi name.

  • Line 5: We define the password for our network.

Let’s set the ESP-32 microcontroller to retrieve data from the temperature sensor and establish a connection with Firebase cloud storage.

uint8_t DHTPin = 21;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);
float Temperature;
float Humidity;
FirebaseData firebaseData;
FirebaseJson json;
  • Line 1: We define the output pin of the DHT temperature sensor.

  • Line 4: We initialize the DHT sensor based on the output pin and type of sensor.

  • Line 8: The FirebaseData object is a fundamental part of the Firebase Arduino library. It manages the connection to the Firebase Realtime Database and stores data received from or sent to the database.

  • Line 9: The FirebaseJson object is often used in conjunction with the FirebaseData object to work with JSON data. The json variable allows us to create, manipulate, and parse JSON data within our Arduino sketch.

Setup function

The primary role of the setup() function is to initialize the Arduino board and any connected peripherals or components. This is where we set up the initial conditions for our program before it enters the continuous execution loop. The setup function is executed only once.

void setup() {
Serial.begin(115200);
delay(100);
pinMode(DHTPin, INPUT);
dht.begin();
Serial.println("Establishing a connectio with ");
Serial.println(ssid); //prints the name of the network
//connect to your local wi-fi network
WiFi.begin(ssid, password);
//check wi-fi is connected to wi-fi network
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
//Set database read timeout to 1 minute (max 15 minutes)
Firebase.setReadTimeout(firebaseData, 1000 * 60);
//tiny, small, medium, large and unlimited.
//Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s).
Firebase.setwriteSizeLimit(firebaseData, "tiny");
Serial.println("Connected...");
}
  • Line 2: Serial.begin(115200) initializes the serial communication between the Arduino and ESP-32. The number 115200 represents the baud rate, which is the communication speed in bits per second.

  • Line 5: The pinMode(DHTpin,INPUT), specifies the pin of the DHT sensor that provides us with the necessary data, and INPUT specifies that the data is retrieved from the microcontroller.

  • Line 6: The dht.begin() function sets up the necessary communication protocol and configurations to interface with the DHT sensor. After calling this function, we can use other functions provided by the library to read data from the DHT sensor, such as temperature and humidity readings.

  • Line 14: The WiFi.begin(ssid,password) function tries to connect to the Wi-Fi network.

  • Lines 17–20: This loop tries to connect to the Wi-Fi network after every second until a connection is established.

  • Line 24: The Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH) function establishes the connection with Firebase cloud storage.

  • Line 25: The Firebase.reconnectWiFi(true) function attempts to reconnect to the Wi-Fi network if it’s currently disconnected.

  • Line 31: Firebase.setwriteSizeLimit(firebaseData, "tiny") function limits the size of data that can be written to the Firebase Realtime Database. The parameter tiny indicates a very small size limit for write operations.

Loop function

After the setup function is executed, the loop function is executed repeatedly. So, the operations to be executed repeatedly, like reading the data and posting it on the cloud storage, are managed here.

void loop()
{
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
char* temp_str="/temperature";
char* hum_str="/humidity";
json.set(temp_str, Temperature);
json.set(hum_str, Humidity);
Firebase.updateNode(firebaseData,"/SensorData",json);
delay(300000);
}
  • Lines 3–4: We use dht.readTemperature() and dht.readHumidity() to retrieve the temperature and humidity values from the sensor.

  • Line 8: The json.set(temp_str,Temperature) creates the JSON object with values of Temperature and key temp_str.

  • Line 9: The json.set(hum_str,Humidity) creates the JSON object with values of Humidity and key hum_str.

  • Line 11: The Firebase.updateNode(firebaseData,"/SensorData",json) function updates a specific node or path in the Firebase Realtime Database with new data. The firebaseData field manages the connection details. "/SensorData" is the Firebase path or node that we want to update. The json field is the object that contains the JSON data we want to update at the specified path.

  • Line 12: The delay(300000) adds a delay in the system. With a delay of 300000 milliseconds, we ensure that the data is uploaded to the database after every five minutes. You can increase or decrease this delay based on your needs

Complete code

#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <FirebaseESP32.h>
#include "DHT.h"
#define DHTTYPE DHT22
//Paste you Realtime database url here (refer to slide 10)
#define FIREBASE_HOST "##################"
//Paste your web api key (refer to slide 9)
#define FIREBASE_AUTH "##################"
//Enter your wifi details
const char *ssid = "######";
//Enter the password details for the wifi network
const char *password = "#######";
uint8_t DHTPin = 21;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);
float Temperature;
float Humidity;
FirebaseData firebaseData;
FirebaseJson json;
void setup() {
Serial.begin(115200);
delay(100);
pinMode(DHTPin, INPUT);
dht.begin();
Serial.println("Establishing a connectio with ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
Firebase.setReadTimeout(firebaseData, 1000 * 60);
Firebase.setwriteSizeLimit(firebaseData, "tiny");
Serial.println("Connected...");
}
void loop()
{
Temperature = dht.readTemperature();
Humidity = dht.readHumidity();
char* temp_str="/temperature";
char* hum_str="/humidity";
json.set(temp_str, Temperature);
json.set(hum_str, Humidity);
Firebase.updateNode(firebaseData,"/SensorData",json);
delay(30000);
}

Since Arduino has built-in libraries for Firebase, it is easier to establish a connection with Firebase using our ESP-32 microcontroller. We can later use the data that is stored in our real-time database in other applications.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved