This tutorial covers how to connect ESP8266 to Firebase. We will explore how to use Firebase real time database with ESP8266. In other words, we want to synchronize the data on the Firebase database with ESP8266 to control the device in real time. To understand better how to connect ESP8266 to Firebase and how we can use this interaction, we will build a real example: an IoT controlled RGB LEDs (such a LED strip). This is an interesting project because through it, it is possible to explore how to use Firebase in IoT.
Briefly, Google Firebase cloud is a platform that provides several services such as Authentication, real time database, and so on. To build this IoT project we will use a real time database features. The result is shown in the video below:
https://youtu.be/I5GoRxoeSUc
To develop this Firebase IoT project, we have to follow these two steps:
- Connecting the ESP8266 to Google Firebase real-time database
- Configure the Firebase real-time database
Connecting ESP8266 to Firebase real-time database
In this first step, it is necessary to connect ESP8266 to Firebase database so that this device receives the updates from the database as soon as we modify the values. To achieve it, first, we have to connect the ESP8266 to the Wifi:
#include <ESP8266WiFi.h>
void connectWifi() {
// Let us connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(".......");
Serial.println("WiFi Connected....IP Address:");
Serial.println(WiFi.localIP());
}
Code language: PHP (php)
where connectWifi()
is called in the setup()
as we will see later and the ssid and password are the WiFi ssid and the WiFi password.
Importing Firebase library
To connect the ESP8266 to Google Firebase, we will use a Firebase library that simplifies the project. Go to Sketch->Include Library->Manage Libraries and look for Firebase library:

Select the library according to the device you are using and you’re ready! The code below shows how to connect the ESP8266 to Google Firebase:
void setup() {
Serial.begin(9600);
connectWifi();
....
Firebase.begin("firebase_url", "firebase_API_key");
}
Code language: JavaScript (javascript)
At line 6, the code sets up the connection between ESP8266 and Firebase. Two parameters are necessary:
- firebase_url
- firebase_API_Key
You will see later how to get it from Firebase console after we have configured the Firebase project.
Receiving data from Firebase database
Finally, it is necessary to receive data from the Firebase realtime database:
void loop() {
if (Firebase.getInt(firebaseData, "/red")) {
if (firebaseData.dataType() == "int") {
int val = firebaseData.intData();
if (val != redValue) {
redValue = val;
setLedColor();
}
}
}
if (Firebase.getInt(firebaseData, "/green")) {
if (firebaseData.dataType() == "int") {
int val = firebaseData.intData();
if (val != greenValue) {
greenValue = val;
setLedColor();
}
}
}
if (Firebase.getInt(firebaseData, "/blue")) {
if (firebaseData.dataType() == "int") {
int val = firebaseData.intData();
if (val != blueValue) {
blueValue = val;
setLedColor();
}
}
}
}
Code language: JavaScript (javascript)
A few things to note. First, to control RGB LEDs it is necessary to use three components (red, green, blue). Next thing to notice: the code above gets the reference to the data stored in Firebase realtime database using:
Firebase.getInt(firebaseData, "/red")
Code language: JavaScript (javascript)
then, it is necessary to verify that the value is an integer:
if (firebaseData.dataType() == "int") {
....
}
Code language: JavaScript (javascript)
and finally, the code retrieves the value:
int val = firebaseData.intData();
Arduino code to connect to Firebase real time database
The final code is shown below:
#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>
#include <Adafruit_NeoPixel.h>
#define PIN D1
#define NUM_LEDS 8
const char* ssid = "your_ssid";
const char* password = "your_wifi_passowrd";
FirebaseData firebaseData;
Adafruit_NeoPixel leds(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);
// Current color values
int redValue = 0;
int greenValue = 0;
int blueValue = 0;
void setup() {
Serial.begin(9600);
connectWifi();
leds.begin();
Firebase.begin("https://xxxx.firebaseio.com/", "wDsHB30jVN554CA********");
}
void loop() {
if (Firebase.getInt(firebaseData, "/red")) {
if (firebaseData.dataType() == "int") {
int val = firebaseData.intData();
if (val != redValue) {
redValue = val;
setLedColor();
}
}
}
if (Firebase.getInt(firebaseData, "/green")) {
if (firebaseData.dataType() == "int") {
int val = firebaseData.intData();
if (val != greenValue) {
greenValue = val;
setLedColor();
}
}
}
if (Firebase.getInt(firebaseData, "/blue")) {
if (firebaseData.dataType() == "int") {
int val = firebaseData.intData();
if (val != blueValue) {
blueValue = val;
setLedColor();
}
}
}
}
void connectWifi() {
// Let us connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(".......");
Serial.println("WiFi Connected....IP Address:");
Serial.println(WiFi.localIP());
}
void setLedColor() {
for (int i=0; i < NUM_LEDS; i++)
leds.setPixelColor(i, leds.Color(redValue, greenValue, blueValue));
leds.show();
}
Code language: C++ (cpp)
If you are interested you can discover how to integrate ESP8266 and Alexa so that you can control devices using voice commands.
Configuring the Firebase real time database
In this second step in building this ESP8266 Firebase project, we will configure the Firebase realtime database. If you don’t have an account, before starting it is necessary to create one for free. Then go to the console and start adding a new project:

and then add a new project as shown below:

If everything goes well, then the new Firebase project is created:

Then it is time to create the Firebase database. This database will contain the three components of color used to control the RGB LEDs connected to the ESP8266. Once we will connect the ESP8266 to Google Firebase, every value changes in the database will be reflecting on the ESP8266 side.

It is important you set the database in test mode:

Then when all these steps are complete, select the realtime database and start adding fields as shown below:

Now the last two steps. First, in the Rules, you have to set all the values to true and then it is necessary to retrieve the values to use in the ESP8266 code shown above.
The URL is shown in the picture above https://xxxx.firebaseio.com and the API Key is in Project settings -> Services account->Database secrets.

That’s all. You can run and test the project. The URL shown above is the URL we will use to connect the ESP8266 to Google Firebase. If you want to know more about how to build an ESP8266 Web Server instead of using Firebase, you can read my tutorial about “ESP8266 Web Server: send commands and serve HTML Page“
Schematics: Connecting ESP8266 to RGB LEDs
The circuit diagram to connect RGB LEDs to ESP8266 is shown below:

In this project, we will use Neopixels LEDs, but we can use other kinds of LEDs. The same steps can be applied even if you change the LEDs you use. ESP8266 Firebase database connection to connect to Firebase database
Summary
This tutorial has shown how to connect ESP8266 to Google Firebase’s real-time database to control RGB LEDs. This project demonstrated how to use Firebase in IoT. Another interesting option to control an ESP8266 is using a Telegram Bot. As you have seen, it is very easy and with a few lines of code, you can control remotely RGB LEDs.
After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
Thank you very much!….help me to share SwA
I am a teacher, I am very happy to be able to read your articles and this is very helpful to me, I hope this experiment can help my students in developing IoT knowledge, thks God Bless you!
A well discussed intruction along with the images great .but I have a similar kind of project which connects to firebase realtime database to control the GPIO unfortunately my esp8266 restart I have also enabled WDT and feed him once entering the loop and after the value is received from the firebase and switch the gpio but it still restarts could you please help me out .
Hi,
have you checked if it is a problem related to the power?
Greetings
First, thanks for the tutorial. Give an example here with some code without Firebase functions, and what should be added to the code to make it clearer for understanding. For example, this:
// *************** Declare included libraries *****************
#include
#include
#include
#include
#include
#include
// ************* Declara estruturas *****************
//Cria uma estrutura para informações de LED RGB
struct RGB {
byte r, g, b;
};
//Cria uma estrutura para informações de tempo
struct TIME {
byte Hour, Minute;
};
// ************* Opções editáveis ***************************
//A cor do ponteiro “12H” para dar referência visual ao topo
const RGB Twelve = { 128, 0, 128 }; //roxo forte
//A cor dos ponteiros 3H, 6H e 9H para dar referência visual
const RGB Quarters = { 64, 0, 40 }; //roxo fraco
//A cor das “divisões” 1min,2min,4min,5min,7min,8min,10min e 11min para dar referência visual
const RGB Divisions = { 32, 0, 20 }; //azul fraco
//Todos os outros pixels sem informação
const RGB Background = { 1, 3, 10 }; //azul fraco
//O ponteiro das horas
const RGB Hour = { 255, 0, 0 }; //vermelho
//O ponteiro dos minutos
const RGB Minute = { 0, 128, 0 }; //verde
//O ponteiro dos segundos
const RGB Second = { 0, 0, 255 }; //azul intenso
// Faz o relógio avançar ou retroceder (dependendo do tipo de tira de Led)
const char ClockGoBackwards = 0;
//Define o brilho por tempo para o modo noturno e diurno
const TIME WeekNight = {21, 30}; //escurecimento na semana à noite
const TIME WeekMorning = {6, 15}; //clarear pela manhã na semana
const TIME WeekendNight = {21, 30}; //escurecimento à noite nos fins de semana
const TIME WeekendMorning = {9, 30}; //clarear pela manhã nos fins de semana
const int day_brightness = 255;
const int night_brightness = 16;
//Define o seu fuso horário em horas de diferença do GMT
const int hours_Offset_From_GMT = -4;
//Define os detalhes do seu Wi-Fi para que a placa possa se conectar e obter o tempo da internet
const char *ssid = “xxxxxxx”; // seu SSID de rede (nome)
const char *password = “xxxxxxx”; // sua senha de rede
byte SetClock;
// Por padrão ‘time.nist.gov’ é usado.
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
// Pino do ESP8266 que está conectado aos NeoPixels
// #define PIN 14 // Este é o pino D5
// #define PIN2 12 // Este é o pino D6
// ************* Declara funções do usuário ******************************
void Draw_Clock(time_t t, byte Phase);
int ClockCorrect(int Pixel);
void SetBrightness(time_t t);
void SetClockFromNTP ();
bool IsDst();
// ************************** Declara NeoPixel ***************************
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(60, 14, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel pixels2 = Adafruit_NeoPixel(60, 12, NEO_GRB + NEO_KHZ800);
//************* Função Setup para Wol_Clock ******************************
void setup() {
pixels.begin(); // Inicializa a 1ª tira NeoPixel
pixels2.begin(); // Inicializa a 2ª tira NeoPixel
pixels.show(); // Atualiza todos os pixels da 1ª tira de Led
pixels2.show(); // Atualiza todos os pixels da 2ª tira de Led
Draw_Clock(0, 1); // Desenha simplesmente um relógio em branco
WiFi.begin(ssid, password); // Tenta conectar-se ao Wi-Fi
Draw_Clock(0, 2); // Desenha o fundo do relógio
while (WiFi.status() != WL_CONNECTED)
delay (500); // continua esperando até que possamos conectar com sucesso ao WiFi
Draw_Clock(0, 3); // Adiciona os indicadores de um quarto de hora
SetClockFromNTP(); // obtém a hora do servidor NTP com correção de fuso horário
}
void SetClockFromNTP ()
{
timeClient.update(); // obtém a hora do servidor NTP
setTime(timeClient.getEpochTime()); // Define a hora do sistema a partir do relógio
if (IsDst())
adjustTime((hours_Offset_From_GMT + 1) * 3600); // desloca a hora do sistema com o fuso horário definido pelo usuário (3600 segundos em uma hora)
else
adjustTime(hours_Offset_From_GMT * 3600); // desloca a hora do sistema com o fuso horário definido pelo usuário (3600 segundos em uma hora)
}
bool IsDst()
{
if (month() 10) return false;
if (month() > 3 && month() = 24;
if (month() == 10) return previousSunday < 24;
return false; // esta linha nunca vai acontecer
}
// ************* Loop do programa principal para Wol_Clock ******************************
void loop() {
time_t t = now(); // Obtém a hora atual
Draw_Clock(t, 4); // Desenha todo o mostrador do relógio com horas, minutos e segundos
if (minute(t) == 0) // no início de cada hora, atualiza a hora no servidor de tempo
{
if (SetClock == 1)
{
SetClockFromNTP(); // obtém a hora do servidor NTP com correção de fuso horário
SetClock = 0;
}
}
else
{
delay(200); // Espera somente 0,1 segundos
SetClock = 1;
}
}
// ************* Funções para desenhar o relógio ******************************
void Draw_Clock(time_t t, byte Phase)
{
if (Phase <= 0)
for (int i = 0; i = 1)
for (int i = 0; i = 2)
for (int i = 0; i = 3) {
for (int i = 0; i = 4) {
pixels2.setPixelColor(ClockCorrect(second(t)), pixels2.Color(Second.r, Second.g, Second.b)); // desenhe o ponteiro dos segundos primeiro
if (second() % 2)
pixels2.setPixelColor(ClockCorrect(minute(t)), pixels2.Color(Minute.r, Minute.g, Minute.b)); // para ajudar na identificação, o ponteiro dos minutos pisca entre a intensidade normal e meia intensidade
else
pixels2.setPixelColor(ClockCorrect(minute(t)), pixels2.Color(Minute.r, Minute.g, Minute.b)); // ponteiro dos minutos de menor intensidade
pixels.setPixelColor(ClockCorrect(((hour(t) % 12) * 5)), pixels.Color(Hour.r, Hour.g, Hour.b)); // desenhe o ponteiro das horas por último
}
SetBrightness(t); // Define o brilho do relógio de acordo com a hora
pixels.show();
pixels2.show();
pixels.clear();
pixels2.clear();
}
// ************* Função para definir o brilho do relógio ******************************
void SetBrightness(time_t t)
{
int NowHour = hour(t);
int NowMinute = minute(t);
if ((weekday() >= 2) && (weekday() WeekNight.Hour) || ((NowHour == WeekNight.Hour) && (NowMinute >= WeekNight.Minute)) || ((NowHour == WeekMorning.Hour) && (NowMinute <= WeekMorning.Minute)) || (NowHour WeekendNight.Hour) || ((NowHour == WeekendNight.Hour) && (NowMinute >= WeekendNight.Minute)) || ((NowHour == WeekendMorning.Hour) && (NowMinute <= WeekendMorning.Minute)) || (NowHour < WeekendMorning.Hour))
pixels.setBrightness(night_brightness);
else
pixels.setBrightness(day_brightness);
}
//************* Testa a função de inversão da ordem dos pixels ***************
int ClockCorrect(int Pixel)
{
if (ClockGoBackwards == 1)
return ((60 – Pixel + 30) % 60);
else
return (Pixel);
}