ESP8266 Send Sensor Readings to Google Firebase Database using Arduino IDE

In this user guide, we will learn to send sensor readings to Google firebase and also on Android app through Google Firebase using ESP8266 NodeMCU and Arduino IDE. We will make our personal ESP8266 IOT app by using Google Firebase and MIT App Inventor.

ESP8266 Send Sensor Readings to Google Firebase and Build an Android app to display Data

Previously, we used the Blynk application to control ESP32’s output (Control ESP32 Outputs using Blynk App and Arduino IDE). This time we will build our ESP8266 application which will display sensor readings on our smartphone. The sensor readings could be accessed anywhere and anytime conveniently. Any appropriate sensor can be used such as DS18B20, BME680, LM35, and MPU6050 but for this article, we will use a DHT11 sensor which is used to measure temperature and humidity. We will use Arduino IDE to program our ESP8266 board which will be connected to a DHT11 sensor. Additionally, we will send the sensor readings to the Google Firebase database which we will demonstrate the sensor readings in real-time through our app which will be built in MIT App Inventor.

This article is divided into these sub-topics:

  • Introduction of DHT11 sensor and its connection with an ESP8266 board.
  • Introduction of Google Firebase and setting up Google Firebase Console
  • Setting up Arduino IDE and programming the NodeMCU
  • Building app in MIT App Inventor

We have a similar guide with ESP32:

ESP32 Send Sensor Readings to Google Firebase and Build an Android app to display Data

Project Overview

ESP8266 Google Firebase build your own app MIT Inventor 22

We will create an IoT app through Google firebase and MIT App Inventor. The heading of the app will consist of “ESP8266 and DHT11 APP” followed by first ‘Temperature’ and its reading and then ‘Humidity’ and its reading with appropriate units. We aim to build an application that will display sensor readings obtained from DHT11 connected with the ESP8266 module programmed in Arduino IDE. This transmission of data from the module to the application will occur via Google Firebase. These readings will automatically update to new values in real-time when the IoT app receives them.

We will require the following for our project:

Hardware Required:

  1. ESP8266 NodeMCU
  2. DHT11 Sensor
  3. Connecting Wires
  4. Breadboard

Software Required:

  1. Google Firebase
  2. Arduino IDE
  3. MIT App Inventor
  4. Android Smartphone with MIT AI2 Companion installed

Working Process

  1. DHT11 sensor will send temperature and humidity reading to the ESP8266 development board.
  2. The ESP8266 module will transmit the sensor data to the Google Firebase server.
  3. We will include Google Firebase’s database inside our IoT app through MIT App Inventor. Thus, we could access the temperature and humidity readings in a device that has MIT Inventor installed on it e.g., our android smartphone/tablet.
ESP8266_Google_Firebase_build your own app_working process
Working Process

Introduction to DHT11 sensor

DHT11 sensor is used to measure the temperature and humidity. It has a resistive humidity sensing component and a negative temperature coefficient (NTC). An 8-bit MCU is also connected in it which is responsible for its fast response. It is very inexpensive but it gives values of both temperature and humidity simultaneously. DHT sensors are pre-calibrated. We can directly connect them with ESP32/ESP8266 to obtain sensor output reading. They are internally composed of a humidity sensing sensor and a thermistor. These two components measure humidity and temperature.

Features of DHT11

  • Humidity range: from 20 to 90% RH
  • Temperature range: from 0 – 50 C
  • Signal transmission range: ~20 m
  • Inexpensive
  • Fast response and it is also durable

For more information regarding DHT11, you can have a look at the articles listed below:

Connecting DHT11 sensor with the ESP8266 Development board

The connection of DHT11 with the ESP8266 board is very easy. Originally, the DHT sensor consists of four pins. Where the first pin is the VCC pin, the second is the data pin which has to be connected with an additional 10k ohm resistor, the third is the un-used pin and the fourth pin the ground pin. However, on the DHT modules, only three pins are exposed to the pinout of the module and10k ohm pull-up resistor is internally connected to pin 2. We will be using the module in our project.

Connect the ground and the VCC of the DHT11 sensor module to the ground and 3.3V pin of ESP8266. Then connect the data pin of the DHT11 sensor module to any appropriate output pin of the board. We have used GPIO12 (D6) in this case.

Follow the schematic diagram below for the ESP8266 module and connect them accordingly.

ESP8266 Google Firebase build your own app schematic
Schematic diagram

Vin is connected with a 3.3V pin on the module and both the ESP board and the sensor module is commonly grounded.

Google Firebase Introduction

Recommended Reading: Google Firebase: Control ESP32 Outputs with Arduino IDE

Google Firebase is an application development software created by Google. It can be used with any android/IOS application, IoT sensors and web services to create and alter the data obtained from them. It is a helpful software for building mobile/web applications easily and interactively. Paid services include a Real-time database, firebase storage, hosting and test lab. However, you can use Analytics for advanced messaging for free although you will have to create an account before accessing it.

One of the significant attributes of this software is that it is beginner-friendly. It is very simple to connect your application to Google Firebase. You have to follow each step carefully. If you have any difficulty or want to access further information, take a look at the official Google Firebase Documentation.

Setting up Google Firebase Console

Before proceeding with the project let us understand the steps which have to be followed to successfully connect with the Google Firebase application.

Firstly, type https://firebase.google.com/ in your browser search tab and press enter.

This will open the Firebase main page. Click ‘Go to Console’ as highlighted in the red rectangular box.

Google Firebase Getting Started no1

You will be redirected to a new web page with the welcome message. Click the button ‘Create a Project’ as shown below.

Google Firebase Getting Started no2

The following page opens up.

Step 1: Write the name of your project. Remember to tick the Firebase term agreement. Now click ‘Continue’.

ESP8266 Google Firebase build your own app 1

Step 2: Now enable ‘Google analytics for this project’ by swiping the sliding button. Click ‘Continue’ to proceed further.

Google Firebase Getting Started no4

Step 3: After choosing your location and ticking the required boxes click ‘Create Project’.

Google Firebase Getting Started no5

After a few moments, your project will be created. Click ‘Continue.’

ESP8266 Google Firebase build your own app 2

Your newly created project will open.

Obtaining Authorization key and Firebase host

Go to the settings icon and click ‘Project Settings’.

ESP8266 Google Firebase build your own app 3

Now, go to ‘Service Accounts’ and click ‘Generate new private key’.

ESP8266 Google Firebase build your own app 4

Then go to ‘Database secrets.’ You will be able to view a secret key associated with your project. This is the unique authorization key that you will save and use later on in the program code. Keep it a secret and do not share it with anyone or your project security will be compromised.

ESP8266 Google Firebase build your own app 5

Next, Under the Build tab go to ‘Realtime Database.’ Then click ‘Create Database.’

ESP8266 Google Firebase build your own app 6

After setting your location, check ‘Start in Lock mode’ and then click the Enable button. Your database settings are now completed. Copy the text shown in the highlighted box below. Save it as well. This will act as your Google Firebase host which we will incorporate in our program code.

ESP8266 Google Firebase build your own app 7

Setting up Arduino IDE

We will use Arduino IDE to program our ESP8266 development board. Thus, you should have the latest version of Arduino IDE. Additionally, you also need to install the ESP8266 plugin.

If your IDE does not have the plugin installed you can visit the link below: Installing ESP8266 library in Arduino IDE

Installing Google Firebase ESP8266 Library

To use Google Firebase with our ESP8266 board, we would have to install its library in our Arduino IDE.

To download the library, click here. Click on ‘Code’ and then ‘Download Zip’.

ESP8266 Google Firebase build your own app installing ESP8266 Firebase library

You will download the library as a .zip folder which you will extract and rename as ‘FirebaseESP8266’ Then, transfer this folder to the installation library folder in your Arduino IDE.

Likewise, you can also go to Sketch > Include Library > Add .zip Library inside the IDE to add the library as well. After installation of the library, restart your IDE.

Installing DHT Library

As we are connecting the DHT11 sensor with ESP8266 so we will have to install DHT11 libraries to our module. We will require two libraries for this project:

  1. DHT sensor library
  2. Adafruit Unified Sensor library

We will use the Library Manager in our Arduino IDE to install the latest versions of the libraries. Open your Arduino IDE and go to Sketch > Include Libraries > Manage Libraries. Type each library name in the search bar and install them both.

ESP8266 Google Firebase build your own app installing DHT library
Adafruit unified sensor library install

Arduino Sketch to Send Sensor Data to Google Firebase

Open your Arduino IDE and go to File > New to open a new file. Copy the code given below in that file. You need to enter your network credentials. Additionally, you also have to provide your Authorization key and the Google Firebase Host both of which we saved previously.

#include <FirebaseESP8266.h>
#include  <ESP8266WiFi.h>
#include "DHT.h"

#define FIREBASE_HOST "esp8266-sensor-readings-app-default-rtdb.firebaseio.com"
#define WIFI_SSID "Your_SSID" // Change the name of your WIFI
#define WIFI_PASSWORD "Your_Password" // Change the password of your WIFI
#define FIREBASE_Authorization_key "Replace_with_your_secret_key"

#define DHTPIN 12    

#define DHTTYPE DHT11   
DHT dht(DHTPIN, DHTTYPE);

FirebaseData firebaseData;
FirebaseJson json;

void setup() {

 Serial.begin(115200);
  dht.begin();
   WiFi.begin (WIFI_SSID, WIFI_PASSWORD);
   Serial.print("Connecting...");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  Firebase.begin(FIREBASE_HOST,FIREBASE_Authorization_key);
  
}

void loop() {
 
  float hum = dht.readHumidity();
  float temp = dht.readTemperature();  
  
   if (isnan(hum) || isnan(temp)  ){
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.print("°C");
  Serial.print(" Humidity: ");
  Serial.print(hum);
  Serial.print("%");
  Serial.println();

  Firebase.setFloat(firebaseData, "/ESP8266_APP/TEMPERATURE", temp);
  Firebase.setFloat(firebaseData, "/ESP8266_APP/HUMIDITY", hum);
   delay(200);
}

How the Code Works?

Now, let us understand how each part of the code works.

Including Libraries

Firstly, we will include the relevant libraries which are necessary for this project. We are using three libraries: ESP8266WiFi.h, FirebaseESP8266.h and DHT.h
ESP8266WiFi.h library is used to connect our ESP8266 module with the local WIFI network. The other libraries are the ones that we previously installed and will be required for the Firebase and sensor functionality.

#include <FirebaseESP8266.h>
#include "DHT.h"
#include  <ESP8266WiFi.h>

Defining Firebase and Network Credentials

Secondly, we will define the network credentials. One for the SSID and the other for the password. These will be our network credentials which will be used to connect to our wireless network. Replace both of them with your credentials to ensure a successful connection.
Next, we will define the Google firebase host and authorization key which we accessed and saved previously.

#define FIREBASE_HOST "esp8266-sensor-readings-app-default-rtdb.firebaseio.com"
#define WIFI_SSID "Your_SSID" // Change the name of your WIFI
#define WIFI_PASSWORD "Your_Password" // Change the password of your WIFI
#define FIREBASE_Authorization_key "Replace_with_your_secret_key"

Defining DHT Sensor

The following lines of code will specify the type of DHT sensor and the GPIO pin of the ESP8266 board which we will connect with the data pin of the sensor.

#define DHTPIN 12    
#define DHTTYPE DHT11   
DHT dht(DHTPIN, DHTTYPE);

Creating FirebaseData Object

Define the FirebaseData object as ‘firebaseData.’ This will be used later on in the code to access the sensor readings.

FirebaseData firebaseData;

setup() function

Inside the setup() function, we will open a serial connection at a baud rate of 115200. Additionally, we will initiate the connection with the DHT sensor as well.

Serial.begin(115200);
dht.begin();

The following section of code will connect our ESP8266 board with the local network whose network credentials we already specified above. We will use the WiFi.begin() function. The arguments will be the SSID and the password which we defined earlier in the code. After the connection will be established, the IP address of the ESP board will get printed on the serial monitor.

WiFi.begin (WIFI_SSID, WIFI_PASSWORD);
   Serial.print("Connecting...");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println();

Now, we will connect our ESP8266 module with Google Firebase by using the Firebase.begin() function. It takes in two parameters. The first is the Firebase host and the second is the authorization key. Both were defined earlier on in the program code. Through correct credentials, a successful connection will be made.

  Firebase.begin(FIREBASE_HOST,FIREBASE_Authorization_key);

loop() function

Inside the loop() function we will obtain the sensor readings and handle them accordingly. Firstly, through dht.readHumidity(), the sensor reading will get saved in the variable ‘hum.’ Likewise, for temperature the sensor reading will get saved in the variable ‘temp.’

float hum = dht.readHumidity();
float temp = dht.readTemperature();  

If the connection between the module and the sensor is incorrect or the values are not being accessed properly then an error message will be printed. This will help us in debugging our circuit or a possible issue in the initialization of the sensor.

if (isnan(hum) || isnan(temp)  ){
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

Thus, we will display these temperature and humidity readings on the serial monitor. Newer readings will continuously appear on the screen.

  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.print("°C");
  Serial.print(" Humidity: ");
  Serial.print(hum);
  Serial.print("%");
  Serial.println();

Through Firebase.setFloat() we will update our app with the current temperature and humidity readings. This function will take in three parameters. The first is the FirebaseData object which we created. The second is the “project name/the name of the tag which we will set in our MIT block.” Lastly, we will specify the variable in which we were saving our updated sensor variables i.e., temp and hum respectively.

Firebase.setFloat(firebaseData, "/ESP8266_APP/TEMPERATURE", temp);
Firebase.setFloat(firebaseData, "/ESP8266_APP/HUMIDITY", hum);

Building App with MIT APP Inventor to Display Sensor Data from Google Firebase

MIT App Inventor is an incredible web application that helps users build interesting Android applications. It is a block-based programming tool through which users can create fully functional apps for Android devices such as smartphones, tablets e.tc. Often termed beginner-friendly, even people with no prior experience in programming can easily learn how to use this application efficiently. We will use this tool to build our ESP8266 sensor-based app as well.

Steps to Create Android App

Go to the following website: and click the ‘Create Apps!’ button.

ESP8266 Google Firebase build your own app MIT Inventor 1

You will be redirected to a new window where you will be asked to sign in with your email account. After signing in you will have to accept the terms as shown below.

ESP8266 Google Firebase build your own app MIT Inventor 2

You will receive a welcome message. You can visit the link to get more information on how to install the inventor on your smartphone. Press ‘Continue’ to proceed. If you want, you can have a look at the tutorials being specified. Otherwise, go to ‘Start a blank project’ to start your app invention.

ESP8266 Google Firebase build your own app MIT Inventor 3

You will be asked to specify your project name. Choose an appropriate name. Click ‘ok.’

ESP8266 Google Firebase build your own app MIT Inventor 4

The following page will open. It is known as the Designer. This is where we will design the user interface of our app. We can add text, buttons, images and various other functionalities to our app by dragging and dropping components from the palette to the viewer. Then we will set their attributes through the ‘Properties’ column.

ESP8266 Google Firebase build your own app MIT Inventor 5

Creating User Interface

Firstly, we will add a heading for our app. Go to Palette > User Interface and head over to ‘Label.’ Now click and drag the label. Drop it on the Viewer side. Now you will be able to view it in the viewer as well as in the components list.

ESP8266 Google Firebase build your own app MIT Inventor 6

Head over to the ‘Properties’ to change the text, font size and colour. The label will automatically update in the viewer. Keep in mind the viewer will show you the final look of your app which will appear on your smartphone.

ESP8266 Google Firebase build your own app MIT Inventor 7

To add a space between the heading and the next block of text we will create another label and set it with an empty text. You can change the properties of the label to incorporate your preferred spacing dimension by changing the width and height of the label. We have set the height as 5%.

Adding Temperature Readings

Next, we will add a block for the temperature readings. Go to Palette > Layout > HorizontalArrangement. Click and drag HorizontalArrangement and drop it in the Viewer.

ESP8266 Google Firebase build your own app MIT Inventor 8

Go to the ‘Properties’ and set its text as ‘Temperature’ and change the styling according to your preference. We have set the width to 50% and the height will be set automatically. Additionally, you can choose the font type, size and colour as well.

ESP8266 Google Firebase build your own app MIT Inventor 9

Now we will add another label beside Temperature which will specify the sensor reading. Again, follow the same procedure of creating a label. This time we will rename our label as ‘Tempertaure_value.’ Set it as an empty text and make its width 50% as well.

ESP8266 Google Firebase build your own app MIT Inventor 10

Adding Humidity Readings

Likewise, we will create a similar block for humidity as well. Go to Palette > Layout > HorizontalArrangement. Click and drag HorizontalArrangement and drop it in the Viewer.

Go to the ‘Properties’ and set its text as ‘Humidity’ and change the styling according to your preference. We have set the width to 50% and the height will be set automatically. Additionally, you can choose the font type, size and colour as well. Now we will add another label beside Humidity which will specify the sensor reading. This time we will rename our label as ‘Humidity_value.’ Set it as an empty text and make its width 50% as well.

ESP8266 Google Firebase build your own app MIT Inventor 11

Adding FirebaseDB to MIT App Inventor

Go to Palette > Experimental and click and drag FirebaseDB in the viewer. This is a non-visible component of our app and will let us connect it with our Firebase project.

ESP8266 Google Firebase build your own app MIT Inventor 12

Now we will add the secret key authorization key of our Google firebase project which we saved earlier. In the properties section of our FirebaseDB1, copy the key where FirebaseToken is written. The Firebase token is the same as the secret key. Also, specify the complete URL of your project in place of the Firebase URL.

ESP8266 Google Firebase build your own app MIT Inventor 13

Blocks layout

Now click on the ‘Blocks’ button. A new editor will open up. Here we will design how our app will respond. We will assemble blocks in the workspace by clicking and dragging them.

ESP8266 Google Firebase build your own app MIT Inventor 14

First, click ‘FirebaseDB1’ and a series of blocks will open. Click and drag the ‘DataChanged’ block in the workspace.

ESP8266 Google Firebase build your own app MIT Inventor 15

Then go to Built-in > Control and choose the if-then block.

ESP8266 Google Firebase build your own app MIT Inventor 16


Click and drag it in the workspace and place it as shown below:

ESP8266 Google Firebase build your own app MIT Inventor 17

The blocks fit like puzzle pieces. Now similarly follow the diagram below and arrange all the blocks. Press the word ‘tag’ to obtain the ‘get tag’ blocks. Go to Blocks > Built-in > logic to get the “=” sign block. Add ‘TEMPERATURE’ and ‘HUMIDITY’ variables by accessing the empty ‘text’ box. Go to Blocks > Built-in > HorizontalArrangement > Temperature_value and choose the appropriate block. Likewise go to Blocks > Built-in > HorizontalArrangement > Humidity_value and choose the appropriate block. The ‘join’ box will also be found in Blocks > Built-in > logic.

ESP8266 Google Firebase build your own app MIT Inventor 18

Basically, we will use ‘FirebaseDB1.DataChanged’ to obtain the updated sensor readings whenever the readings will update to newer ones in the Google Firebase database. Remember we were using the Realtime Database feature in Firebase so readings will continuously change.

For more information regarding building your app in MIT App Inventor, follow this guide: App Inventor Tutorials.

Setting up App Inventor on Smartphone

Now, as we have built our app in MIT app inventor, integrated Google Firebase with our ESP8266 board and have also written its code let’s move ahead and install the App Inventor in our smartphone. Through this, we will be able to access our app on our smartphone from anywhere around the world. Follow the steps closely.

Firstly, go to Play Store and install ‘MIT AI2 Companion.’

ESP8266 Google Firebase build your own app MIT Inventor 23

After you installed the application, open it. You will have to either scan a QR code or type a 6-character code.

ESP8266 Google Firebase build your own app MIT Inventor 20

To access these, go to MIT App Inventor main page where we initially built our app. Go to Connect > AI Companion. You will receive your unique codes.

ESP8266 Google Firebase build your own app MIT Inventor 19

Connect using either option. After a few moments, the connection will be established. On our smartphone, we will be able to view the following screen which we created.

ESP8266 Google Firebase build your own app MIT Inventor 21

Now, we will demonstrate the sensor readings.

Demonstration

Choose the correct board and COM port before uploading your code to the board. Go to Tools > Board and select ESP8266 NodeMCU.

select ESP8266 NodeMCU board

Next, go to Tools > Port and select the appropriate port through which your board is connected.

ESP8266 COM Port

Click on the upload button to upload the code to your ESP8266 development board.
After you have uploaded your code to the development board, press its RST button.

ESP8266 NodeMCU reset button

In your Arduino IDE, open up the serial monitor and you will be able to see the status of your WIFI connection and the IP address of your ESP module.
Shortly afterwards you will be able to view the temperature and humidity readings.

ESP8266 Google Firebase build your own app demo serial monitor
Serial Monitor

Open the MIT Companion app on your smartphone. The sensor readings continuously updating in real-time can be seen in the user interface which we designed.

ESP8266 Google Firebase build your own app MIT Inventor 22

You can even go to your Google Firebase Console and see the sensor readings changing in the Realtime database which we created.

ESP8266 Google Firebase build your own app demo google firebase

Conclusion

In conclusion, we were able to build our own ESP8266 sensor readings App via Google Firebase and MIT App Inventor. With this app, we can access the sensor data from anywhere in the world with the help of Google firebase database. It is very convenient and interesting to create the user interface of the app and control our ESP module’s output through Goggle Firebase.

4 thoughts on “ESP8266 Send Sensor Readings to Google Firebase Database using Arduino IDE”

  1. It is very good information about firebase google
    One can send data and visualize data on a mobile phone
    But can we control devices with some modifications in this tutorial
    It would be a great help for applications like home automation

    Reply
  2. Hello!

    Most interesting but I’m stuck. When the MIT AI2 app and MIT Inventor Connect the App responds with “FirebaseError Permission denied” and the Inventor says “Error from Companion: For a custom firebase host you must first set your authentication server before using authentication features!”. I’m not sure if it’s me having overlooked a step or not using the right key in the right place – I have a Database code and a private key in the JSON file.

    Any help gratefully received.

    Reply
    • Hi,

      It mostly occurs when you are not authorized to the database. You can try this solution and let me know if it works?
      Open firebase, select database on the left-hand side.
      Now on the right-hand side, select [Realtime database] from the dropdown and select the rules menu and change the code as follows:

      {
      "rules": {
      ".read": true,
      ".write": true
      }
      }

      Reply

Leave a Comment