{"id":110533,"date":"2025-05-30T08:50:00","date_gmt":"2025-05-30T08:50:00","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=110533"},"modified":"2025-05-30T14:50:28","modified_gmt":"2025-05-30T14:50:28","slug":"firebase-control-esp8266-nodemcu-gpios","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/firebase-control-esp8266-nodemcu-gpios\/","title":{"rendered":"Firebase: Control ESP8266 NodeMCU GPIOs from Anywhere"},"content":{"rendered":"\n<p>In this guide, you&#8217;ll learn how to control the ESP8266 GPIOs from anywhere using Firebase. We&#8217;ll create nodes on the Firebase Realtime Database to save the current GPIO states. Whenever there&#8217;s a change in the database nodes, the ESP8266 updates its GPIOs accordingly. You can change the GPIOs states by writing to the database yourself, or you can create a web app to do that (<a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-firebase-gauges-charts\/\">check this tutorial<\/a>).<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"576\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Control-GPIOs-from-anywhere-Firebase.jpg?resize=1024%2C576&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 Control GPIOs from anywhere using Firebase\" class=\"wp-image-170631\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Control-GPIOs-from-anywhere-Firebase.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Control-GPIOs-from-anywhere-Firebase.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Control-GPIOs-from-anywhere-Firebase.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Control-GPIOs-from-anywhere-Firebase.jpg?resize=1536%2C864&amp;quality=100&amp;strip=all&amp;ssl=1 1536w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Control-GPIOs-from-anywhere-Firebase.jpg?w=1920&amp;quality=100&amp;strip=all&amp;ssl=1 1920w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgray\"><em>Updated 30 May 2025<\/em><\/p>\n\n\n\n<p><a href=\"https:\/\/randomnerdtutorials.com\/control-esp-gpios-firebase-web-app\/\"><strong>PART 2:<\/strong> Control ESP32\/ESP8266 GPIOs from Anywhere (Firebase Web App)<\/a><\/p>\n\n\n\n<p class=\"rntbox rntclgray\">We have a similar tutorial for the ESP32 board: <a href=\"https:\/\/randomnerdtutorials.com\/firebase-control-esp32-gpios\/\">Firebase: Control ESP32 GPIOs from Anywhere<\/a>. <\/p>\n\n\n\n<p>Other Firebase Tutorials with the ESP8266 that you might be interested in:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-firebase-realtime-database\/\">ESP8266 NodeMCU: Getting Started with Firebase (Realtime Database)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-firebase-web-app\/\">ESP8266 NodeMCU with Firebase \u2013 Creating a Web App<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-firebase-authentication\/\">ESP8266 Firebase Authentication (Email and Password)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-firebase-bme280-rtdb\/\">ESP8266 Firebase: Send BME280 Sensor Readings to the Realtime Database<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-firebase-web-app-sensor\/\">ESP8266: Firebase Web App to Display Sensor Readings (with Authentication)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-data-logging-firebase-realtime-database\/\">ESP8266 NodeMCU Data Logging to Firebase Realtime Database<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-firebase-gauges-charts\/\">ESP8266: Firebase Data Logging Web App (Gauges, Charts, and Table)<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What is Firebase?<\/h2>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"196\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Firebase-Logo.png?resize=750%2C196&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Logo\" class=\"wp-image-169096\" style=\"width:375px;height:106px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Firebase-Logo.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Firebase-Logo.png?resize=300%2C78&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Firebase is Google&#8217;s mobile application development platform that helps you build, improve, and grow your app. Firebase provides <em>free <\/em>services like <strong><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-firebase-web-app\/\">hosting<\/a><\/strong>, <strong><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-firebase-authentication\/\">authentication<\/a><\/strong>, and <strong><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-firebase-realtime-database\/\">realtime database<\/a> <\/strong>that allow you to build a fully-featured web app to control and monitor the ESP32 and ESP8266 boards that would be much more difficult and laborious to build and set up on your own.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Project Overview<\/h2>\n\n\n\n<p>The following diagram shows a high-level overview of the project we&#8217;ll build.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"523\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Firebase-Control-Outputs-from-anywhere-project-overview-f.png?resize=750%2C523&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 NodeMCU Firebase Control Outputs from Anywhere Project Overview\" class=\"wp-image-170632\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Firebase-Control-Outputs-from-anywhere-project-overview-f.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Firebase-Control-Outputs-from-anywhere-project-overview-f.png?resize=300%2C209&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<ol class=\"wp-block-list\">\n<li>The ESP8266 authenticates as a user with email and password to be able to access the database (that user must be added on the Firebase authentication methods);<\/li>\n\n\n\n<li>The database is protected using database rules. We&#8217;ll add the following rule: only authenticated users can access the database;<\/li>\n\n\n\n<li>The database has several nodes that save the ESP8266 GPIO states. As an example, we&#8217;ll control three GPIOs (12, 13, and 14). You can add or remove nodes to control more or less GPIOs.<\/li>\n\n\n\n<li>The ESP8266 will listen for changes on the GPIOs database nodes. Whenever there&#8217;s a change, it will update the GPIO states accordingly.<\/li>\n\n\n\n<li>You can change the GPIO states manually on the database using the Firebase console, or you can create a web page (accessible from anywhere) with buttons to control the GPIOs and show the current GPIO states (<a href=\"https:\/\/randomnerdtutorials.com\/control-esp-gpios-firebase-web-app\/\">check PART 2<\/a>).<\/li>\n<\/ol>\n\n\n\n<p>These are the main steps to complete this project:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#create-firebase-project\">Create a Firebase Project<\/a><\/li>\n\n\n\n<li><a href=\"#Set-Authentication-Methods\">Set Authentication Methods<\/a><\/li>\n\n\n\n<li><a href=\"#firebase-project-api-key\">Get Project API Key<\/a><\/li>\n\n\n\n<li><a href=\"#Set-up-Realtime-Database\">Set up the Realtime Database<\/a><\/li>\n\n\n\n<li><a href=\"#Set-up-Database-Security-Rules\">Set up Database Security Rules<\/a><\/li>\n\n\n\n<li><a href=\"#organizing-database-nodes\">Organizing your Database Nodes<\/a><\/li>\n\n\n\n<li><a href=\"#listening-changes\">ESP8266: Listening for Database Changes (control GPIOs) <\/a><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Preparing Arduino IDE<\/h2>\n\n\n\n<p>For this tutorial, we&#8217;ll program the ESP8266 board using the Arduino core. So, make sure you have the ESP8266 add-on installed in your Arduino IDE:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-esp8266-board-arduino-ide\/\">Installing the ESP8266 NodeMCU Board in Arduino IDE (Windows, Mac OS X, Linux)<\/a><\/li>\n<\/ul>\n\n\n\n<p>If you want to program the ESP boards using VS Code with the PlatformIO extension, follow the next tutorial instead:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/vs-code-platformio-ide-esp32-esp8266-arduino\/\">Getting Started with VS Code and PlatformIO IDE for ESP32 and ESP8266<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"create-firebase-project\">1) <span style=\"font-size: inherit;\">Create a Firebase Project<\/span><\/h2>\n\n\n\n<p>Follow the next instructions to create a new project on Firebase.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Go to <a href=\"https:\/\/firebase.google.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">Firebase <\/a>and sign in using a Google Account.<\/li>\n\n\n\n<li>Go to the <a href=\"https:\/\/console.firebase.google.com\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Firebase Console<\/a> and create a new project.<\/li>\n\n\n\n<li>Give a name to your project, for example: <em>ESP-Project,<\/em> and click <strong>Continue<\/strong>.<br><figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105729\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/1-create-firebase-project.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Set Up Firebase Project for ESP32 and ESP8266 Step 1\"><\/figure><\/li>\n\n\n\n<li>Next, enable or disable AI assistance for your project. This is optional.<br><figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105729\" style=\"width: 739px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/2-create-firebase-project-ai-assistance.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Set Up Firebase Project for ESP32 and ESP8266 - Enable AI assistant\"><\/figure><\/li>\n\n\n\n<li>Disable the option <em>Enable Google Analytics<\/em> for this project, as it is not needed. Then, click <strong>Create project<\/strong>.<br><figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105730\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/3-create-firebase-project.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Disable Google Analytics for firebase project\"><\/figure><\/li>\n\n\n\n<li>It will take a few seconds to set up your project. Click <strong>Continue <\/strong>when it&#8217;s ready.<br><figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105731\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/5-Firebase-project-ready.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Project for ESP32 Ready\"><\/figure><br><\/li>\n\n\n\n<li>You&#8217;ll be redirected to your Project console page.<br><figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105732\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/6-Firebase-console-ESP-project.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase console project\"><\/figure><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"Set-Authentication-Methods\">2) Set Authentication Methods<\/h2>\n\n\n\n<p>To allow authentication with email and password, first, you need to set authentication methods for your app.<\/p>\n\n\n\n<p>&#8220;Most apps need to know the identity of a user. In other words, it takes care of logging in and identifying the users (in this case, the ESP32 or ESP8266). Knowing a user&#8217;s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user&#8217;s devices.&#8221; To learn more about the authentication methods, you can <a href=\"https:\/\/firebase.google.com\/docs\/auth\" target=\"_blank\" rel=\"noreferrer noopener\">read the documentation<\/a>.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>On the left sidebar, click on <strong>Build <\/strong>&gt; <strong>Authentication <\/strong>and then on <strong>Get started<\/strong>. <br><figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105735\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/7-set-authentication.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase project set authentication\"><\/figure><\/li>\n\n\n\n<li>There are several authentication methods like email and password, Google Account, Facebook account, and others.<figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105740\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/8-Firebase-authentication-methods.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"SFirebase authentication methods\"><\/figure><\/li>\n\n\n\n<li>Select <strong>Email\/Password<\/strong> and <strong>enable <\/strong>that authentication method. Then, click <strong>Save<\/strong>.<figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105741\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/9-enable-email-password-firebase.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Enable Email Password Sign in Firebase\"><\/figure><\/li>\n\n\n\n<li>Then, at the top, click on the <strong>Users <\/strong>tab. Then, click on <strong>Add user<\/strong>. <figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105741\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/10-add-user-email-password-firebase.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Create a new user\"><\/figure><\/li>\n\n\n\n<li>Create a new user with an email and password. The email can be your personal email. Create a password for that user (you need to remember the password later). Finally, click on <strong>Add user<\/strong>.<figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105741\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/11-add-user-email-pass.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase add user email and password\"><\/figure><\/li>\n\n\n\n<li>The User will show up on the list of users. You can see information about the user, like when it was created, the last time it signed in, and its user UID.<figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105741\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/05\/user-created-in-firebase-esp32.jpg?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase User Created\"><\/figure><\/li>\n<\/ol>\n\n\n\n<p>Firebase creates a unique UID for each registered user. The user UID allows us to identify the user and keep track of the user to provide or deny access to the project or the database. There&#8217;s also a column that registers the date of the last sign-in. At the moment, it is empty because we haven&#8217;t signed in with that user yet.<\/p>\n\n\n\n<p>Copy the User UID because you&#8217;ll need it later.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"firebase-project-api-key\">3) Get Project API Key<\/h2>\n\n\n\n<p>To interface with your Firebase project using the ESP8266 boards, you need to get your project API key. Follow the next steps to get your project API key.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>To get your project&#8217;s API key, on the left sidebar click on <strong>Project Settings<\/strong>.<br><figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105748\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/17-project-settings-firebase.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Realtime Database Project Settings\"><\/figure><\/li>\n\n\n\n<li>Copy the API Key to a safe place because you&#8217;ll need it later.<br><figure><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp-image-105749\" style=\"width: 750px;\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/18-project-api-key-firebase.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Project API Key\"><\/figure><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"Set-up-Realtime-Database\">4) Set up the Realtime Database<\/h2>\n\n\n\n<p>Now, let&#8217;s create a realtime database and set up database rules for our project.<\/p>\n\n\n\n<p><strong>1)<\/strong> On the left sidebar, click on&nbsp;<strong>Realtime Database<\/strong>&nbsp;and then click on&nbsp;<strong>Create Database<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"452\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/13-create-database-firebase.png?resize=750%2C452&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Project Create Database\" class=\"wp-image-169109\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/13-create-database-firebase.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/13-create-database-firebase.png?resize=300%2C181&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p><strong>2)<\/strong> Select your database location. It should be the closest to your location.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"743\" height=\"369\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/14-database-location-firebase.png?resize=743%2C369&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Realtime Database Set up location\" class=\"wp-image-169110\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/14-database-location-firebase.png?w=743&amp;quality=100&amp;strip=all&amp;ssl=1 743w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/14-database-location-firebase.png?resize=300%2C149&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 743px) 100vw, 743px\" \/><\/figure><\/div>\n\n\n<p><strong>3)<\/strong> Set up security rules for your database. You can select <strong>Start in test mode<\/strong>. We&#8217;ll change the database rules in just a moment.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"494\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/15-database-start-test-mode-firebase.png?resize=750%2C494&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Realtime Database Start in Test Mode\" class=\"wp-image-169111\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/15-database-start-test-mode-firebase.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/15-database-start-test-mode-firebase.png?resize=300%2C198&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p><strong>4)<\/strong> Your database is now created. You need to copy and save the database URL\u2014highlighted in the following image\u2014because you&#8217;ll need it later in your ESP32\/ESP8266 code.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"490\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/16-firebase-database-url.png?resize=750%2C490&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Real time database URL\" class=\"wp-image-169112\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/16-firebase-database-url.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/04\/16-firebase-database-url.png?resize=300%2C196&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"Set-up-Database-Security-Rules\">5) Set up Database Security Rules<\/h2>\n\n\n\n<p>Now, let&#8217;s set up the database rules. On the <strong>Realtime Database<\/strong> tab, select the <strong>Rules<\/strong> tab at the top. Then, click on <strong>Edit rules<\/strong>, and add the following rules. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"rules\": {\n    \".read\": \"auth.uid === '<strong>REPLACE_WITH_YOUR_USER_UID<\/strong>'\",\n    \".write\": \"auth.uid === '<strong>REPLACE_WITH_YOUR_USER_UID<\/strong>'\"\n  }\n}<\/code><\/pre>\n\n\n\n<p>Insert the UID of the user you created previously. Then, click <strong>Publish<\/strong>.<\/p>\n\n\n\n<p>These database rules determine that:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Only the user with that specific UID can read and write to the database (change the GPIO states).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Add More Users<\/h3>\n\n\n\n<p>To add more users, you can simply go to the <strong>Authentication <\/strong>tab and click <strong>Add user<\/strong>. Add an email and password for the new user, and finally click on <strong>Add user<\/strong> to create the user.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"698\" height=\"208\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/Firebase-Add-New-User-Email-Password-Dashboard.png?resize=698%2C208&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Add New User Email and Password Console\" class=\"wp-image-110469\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/Firebase-Add-New-User-Email-Password-Dashboard.png?w=698&amp;quality=100&amp;strip=all&amp;ssl=1 698w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/Firebase-Add-New-User-Email-Password-Dashboard.png?resize=300%2C89&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 698px) 100vw, 698px\" \/><\/figure><\/div>\n\n\n<p>Copy the user UID of that new user and add it to the database rules, as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"rules\": {\n    \".read\": \"auth.uid === 'REPLACE_WITH_YOUR_USER_UID' || auth.uid === 'REPLACE_WITH_USER_UID2'\",\n    \".write\": \"auth.uid === 'REPLACE_WITH_YOUR_USER_UID' || auth.uid === 'REPLACE_WITH_USER_UID2'\"\n  }\n}<\/code><\/pre>\n\n\n\n<p>For example. In my case, the UIDs of the users are: <strong>RjO3taAzMMXB82Xmir2LQ7XXXXXX <\/strong>and <strong>9QdDc9as5mRXGAjEsQiUJkXXXXXX<\/strong>. So, the database rules will look as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"rules\": {\n    \".read\": \"auth.uid === '<strong>RjO3taAzMMXB82Xmir2LQ7XXXXXX<\/strong>' || auth.uid === '<strong>9QdDc9as5mRXGAjEsQiUJkXXXXXX<\/strong>'\",\n    \".write\": \"auth.uid === '<strong>RjO3taAzMMXB82Xmir2LQ7XXXXXX<\/strong>' || auth.uid === '<strong>9QdDc9as5mRXGAjEsQiUJkXXXXXX<\/strong>'\"\n  }\n}<\/code><\/pre>\n\n\n\n<p>Finally, Publish your database rules.<\/p>\n\n\n\n<p>To learn more about database rules, you can check the <a href=\"https:\/\/firebase.google.com\/docs\/database\/security\" target=\"_blank\" rel=\"noreferrer noopener\">Firebase documentation<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"organizing-database-nodes\">6) Organizing Your Database Nodes<\/h2>\n\n\n\n<p>All the data stored in the Firebase Realtime Database is stored as JSON objects. So, you can think of the database as a cloud-based JSON tree. When you add data to the JSON tree, it becomes a node with an associated key in the existing JSON structure.<\/p>\n\n\n\n<p><strong>Not familiar with JSON?<\/strong> <a href=\"https:\/\/www.w3schools.com\/js\/js_json_intro.asp\" target=\"_blank\" rel=\"noreferrer noopener\">Read this quick guide<\/a>.<\/p>\n\n\n\n<p>The best way to organize your data will depend on your project features and how users access the data.<\/p>\n\n\n\n<p>We want to control the ESP8266 GPIOs. We can organize the data in a way that makes it easy to add more GPIOs and boards later on. So, we can structure the database as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>board1\n<ul class=\"wp-block-list\">\n<li>outputs:\n<ul class=\"wp-block-list\">\n<li>digital:\n<ul class=\"wp-block-list\">\n<li>12: 0<\/li>\n\n\n\n<li>13: 0<\/li>\n\n\n\n<li>14: 0<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<p>In JSON format, here&#8217;s what it would look like:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>{\n  \"board1\": {\n    \"outputs\": {\n      \"digital\": {\n        \"12\": 0,\n        \"13\": 0,\n        \"14\": 0\n      }\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Creating Database Nodes<\/h3>\n\n\n\n<p>Now let&#8217;s create the database nodes in our database. You can create the nodes manually by writing the nodes on the Firebase console, on the web app, or via the ESP8266. We&#8217;ll create them manually, so it is easier to follow the tutorial.<\/p>\n\n\n\n<p><strong>1)<\/strong> Click on the <strong>Realtime Database<\/strong> so that we start creating the nodes.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"749\" height=\"324\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Open-Firebase-RTDB.png?resize=749%2C324&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Realtime Database Menu\" class=\"wp-image-170456\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Open-Firebase-RTDB.png?w=749&amp;quality=100&amp;strip=all&amp;ssl=1 749w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Open-Firebase-RTDB.png?resize=300%2C130&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 749px) 100vw, 749px\" \/><\/figure><\/div>\n\n\n<p><strong>2)<\/strong> You can create the database nodes manually by using the (<strong>+<\/strong>) icons on the database. However, to prevent typos, we provide a JSON file that you can upload to create the same nodes as ours. Click the link below to download the JSON file.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/github.com\/RuiSantosdotme\/Firebase-ESP\/blob\/main\/ESP-Firebase-Control-GPIOs-Anywhere\/database-outputs.zip?raw=true\" target=\"_blank\" rel=\"noreferrer noopener\">Download database JSON file<\/a><\/li>\n<\/ul>\n\n\n\n<p>After downloading, unzip the folder to access the <em>.json<\/em> file.<\/p>\n\n\n\n<p><strong>3)<\/strong> Now, go back to your database on the Firebase console. Click on the three-dot icon and select <strong>Import JSON<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"748\" height=\"214\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Firebase-RTDB-Import-JSON.png?resize=748%2C214&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Realtime Database Import JSON\" class=\"wp-image-170458\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Firebase-RTDB-Import-JSON.png?w=748&amp;quality=100&amp;strip=all&amp;ssl=1 748w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Firebase-RTDB-Import-JSON.png?resize=300%2C86&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 748px) 100vw, 748px\" \/><\/figure><\/div>\n\n\n<p><strong>4)<\/strong> Select the JSON file that you&#8217;ve just downloaded.<\/p>\n\n\n\n<p><strong>5)<\/strong> Your database should look as shown below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"743\" height=\"292\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Firebase-RTDB-JSON-structure-control-ESP32-GPIOs.png?resize=743%2C292&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase realtime database structure example\" class=\"wp-image-170459\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Firebase-RTDB-JSON-structure-control-ESP32-GPIOs.png?w=743&amp;quality=100&amp;strip=all&amp;ssl=1 743w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/Firebase-RTDB-JSON-structure-control-ESP32-GPIOs.png?resize=300%2C118&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 743px) 100vw, 743px\" \/><\/figure><\/div>\n\n\n<p>All the database nodes required for this project are created. You can proceed to the next section.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">7) ESP8266: Listening for Database Changes (control GPIOs)<\/h2>\n\n\n\n<p id=\"Firebase-Authentication-ESP32-ESP8266\">In this section, we&#8217;ll program the ESP8266 boards to do the following tasks:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Authenticate as a user with email and password (<a href=\"#Set-Authentication-Methods\">the user you set up in this section<\/a>);<\/li>\n\n\n\n<li>Listening for database changes on the GPIO nodes and changing their states accordingly.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Parts Required<\/h3>\n\n\n\n<p>For this project, you need the following parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\" target=\"_blank\" rel=\"noreferrer noopener\">ESP8266 <\/a>(read <a href=\"https:\/\/makeradvisor.com\/best-esp8266-wi-fi-development-board\/\" target=\"_blank\" rel=\"noreferrer noopener\">Best ESP8266 Development Boards<\/a>);<\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noreferrer noopener\">3x LEDs<\/a>;<\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noreferrer noopener\">3x 220Ohm resistors<\/a>;<\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noreferrer noopener\">Breadboard<\/a>;<\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noreferrer noopener\">Jumper wires<\/a>.<\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Schematic Diagram<\/h3>\n\n\n\n<p>In this example, we&#8217;ll control three LEDs connected to GPIOs 12 (D6), 13 (D7), and 14 (D5). So, wire three LEDs to the ESP8266. You can follow the next schematic diagram.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/05\/ESP8266-three-LEDs-schematic-diagram.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"570\" height=\"778\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/05\/ESP8266-three-LEDs-schematic-diagram.png?resize=570%2C778&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 connected to three LEDs Schematic diagram wiring circuit\" class=\"wp-image-104232\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/05\/ESP8266-three-LEDs-schematic-diagram.png?w=570&amp;quality=100&amp;strip=all&amp;ssl=1 570w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/05\/ESP8266-three-LEDs-schematic-diagram.png?resize=220%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 220w\" sizes=\"(max-width: 570px) 100vw, 570px\" \/><\/a><\/figure><\/div>\n\n\n<p>You can use any <a href=\"https:\/\/randomnerdtutorials.com\/esp8266-pinout-reference-gpios\/\">other suitable ESP8266 GPIOs<\/a>, but you also need to change the database nodes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Installing the Firebase ESP Client Library<\/h3>\n\n\n\n<p>For this tutorial, you need to install the <a href=\"https:\/\/github.com\/mobizt\/FirebaseClient\" title=\"\">FirebaseClient Library<\/a>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Installation &#8211; Arduino IDE<\/h4>\n\n\n\n<p>Follow this section if you&#8217;re using Arduino IDE. <\/p>\n\n\n\n<p>Go to <strong>Sketch <\/strong>&gt; <strong>Include Library<\/strong> &gt; <strong>Manage Libraries<\/strong>, search for the library name, and install it.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"790\" height=\"586\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/install-Firebase-client-arduino-ide.png?resize=790%2C586&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Install Firebase Client Library Arduino IDE\" class=\"wp-image-169118\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/install-Firebase-client-arduino-ide.png?w=790&amp;quality=100&amp;strip=all&amp;ssl=1 790w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/install-Firebase-client-arduino-ide.png?resize=300%2C223&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/install-Firebase-client-arduino-ide.png?resize=768%2C570&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 790px) 100vw, 790px\" \/><\/figure><\/div>\n\n\n<p>Now, you&#8217;re all set to start programming the ESP32 and ESP8266 boards to interact with the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Installing Libraries &#8211; VS Code<\/h4>\n\n\n\n<p>Follow the next instructions if you&#8217;re using VS Code with the PlatformIO or pioarduino extension.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Install the FirebaseClient Library<\/strong><\/h5>\n\n\n\n<p>If you&#8217;re using VS Code with the PlatformIO extension, click on the <strong>PIO Home<\/strong> icon and then select the <strong>Libraries tab<\/strong>. Search for &#8220;<strong>FirebaseClient<\/strong>&#8220;. Select the <strong>Firebase Client Library<\/strong> by Mobitz.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"646\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Install-FirebsaeClient-Library-VS-Code.jpg?resize=750%2C646&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Install FirebaseClient Library VS Code\" class=\"wp-image-169174\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Install-FirebsaeClient-Library-VS-Code.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Install-FirebsaeClient-Library-VS-Code.jpg?resize=300%2C258&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Then, click <strong>Add to Project<\/strong> and select the project you&#8217;re working on.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"341\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Add-FirebaseClient-library-to-project-VS-Code.jpg?resize=750%2C341&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Add FirebaseClient Library ro project in VS Code\" class=\"wp-image-169175\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Add-FirebaseClient-library-to-project-VS-Code.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/09\/Add-FirebaseClient-library-to-project-VS-Code.jpg?resize=300%2C136&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p> Then, click <strong>Add to Project<\/strong> and select the project you&#8217;re working on.<\/p>\n\n\n\n<p>Also, change the monitor speed to 115200 by adding the following line to the <span class=\"rnthl rntliteral\">platformio.ini<\/span> file of your project:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>monitor_speed = 115200<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"listening-changes\">Listening for Database Changes (GPIO states) \u2014 Code<\/h2>\n\n\n\n<p>Copy the following code to your Arduino IDE or to the <span class=\"rnthl rntliteral\">main.cpp<\/span> file if you&#8217;re using VS Code.<\/p>\n\n\n\n<p>You need to insert the following in the code before uploading it to your board:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>your network credentials<\/li>\n\n\n\n<li>project API key<\/li>\n\n\n\n<li>database URL<\/li>\n\n\n\n<li>authorized user email and password<\/li>\n<\/ul>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*\r\n  Rui Santos &amp; Sara Santos - Random Nerd Tutorials\r\n  Complete project details at our blog.\r\n    - ESP32: https:\/\/RandomNerdTutorials.com\/firebase-control-esp32-gpios\/\r\n    - ESP8266: https:\/\/RandomNerdTutorials.com\/firebase-control-esp8266-nodemcu-gpios\/\r\n  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.\r\n  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\r\n  Based in the RTDB Basic Example by Firebase-ESP-Client library by mobizt\r\n  https:\/\/github.com\/mobizt\/Firebase-ESP-Client\/blob\/main\/examples\/RTDB\/Basic\/Basic.ino\r\n*\/\r\n\r\n#include &lt;Arduino.h&gt;\r\n#if defined(ESP32)\r\n    #include &lt;WiFi.h&gt;\r\n#elif defined(ESP8266)\r\n    #include &lt;ESP8266WiFi.h&gt;\r\n#endif\r\n#include &lt;WiFiClientSecure.h&gt;\r\n#include &lt;FirebaseClient.h&gt;\r\n#include &quot;ExampleFunctions.h&quot; \/\/ Provides the functions used in the examples.\r\n#include &lt;ArduinoJson.h&gt;\r\n\r\n\/\/ Network and Firebase credentials\r\n#define WIFI_SSID &quot;REPLACE_WITH_YOUR_SSID&quot;\r\n#define WIFI_PASSWORD &quot;REPLACE_WITH_YOUR_PASSWORD&quot;\r\n\r\n#define Web_API_KEY &quot;REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY&quot;\r\n#define DATABASE_URL &quot;REPLACE_WITH_YOUR_FIREBASE_DATABASE_URL&quot;\r\n#define USER_EMAIL &quot;REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER&quot;\r\n#define USER_PASS &quot;REPLACE_WITH_FIREBASE_PROJECT_USER_PASS&quot;\r\n\r\n\/\/ User functions\r\nvoid processData(AsyncResult &amp;aResult);\r\n\r\n\/\/ Authentication\r\nUserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);\r\n\r\nSSL_CLIENT ssl_client, stream_ssl_client;\r\n\r\n\/\/ Firebase components\r\nFirebaseApp app;\r\nusing AsyncClient = AsyncClientClass;\r\nAsyncClient aClient(ssl_client), streamClient(stream_ssl_client);\r\nRealtimeDatabase Database;\r\n\r\n\/\/ Timer variables for loop\r\nunsigned long lastSendTime = 0;\r\nconst unsigned long sendInterval = 10000; \/\/ 10 seconds in milliseconds\r\n\r\n\/\/ Database  path (where the data is)\r\nString listenerPath = &quot;board1\/outputs\/digital\/&quot;;\r\n\r\n\/\/ Declare outputs\r\nconst int output1 = 12;\r\nconst int output2 = 13;\r\nconst int output3 = 14;\r\n\r\n\/\/ Initialize WiFi\r\nvoid initWiFi() {\r\n  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);\r\n  Serial.print(&quot;Connecting to WiFi ..&quot;);\r\n  while (WiFi.status() != WL_CONNECTED) {\r\n    Serial.print('.');\r\n    delay(1000);\r\n  }\r\n  Serial.println(WiFi.localIP());\r\n  Serial.println();\r\n}\r\n\r\nvoid setup(){\r\n  Serial.begin(115200);\r\n\r\n  \/\/ Declare pins as outputs\r\n  pinMode(output1, OUTPUT);\r\n  pinMode(output2, OUTPUT);\r\n  pinMode(output3, OUTPUT);\r\n\r\n  initWiFi();\r\n\r\n  \/\/ Configure SSL client\r\n  ssl_client.setInsecure();\r\n  stream_ssl_client.setInsecure();\r\n  #if defined(ESP32)\r\n    ssl_client.setConnectionTimeout(1000);\r\n    ssl_client.setHandshakeTimeout(5);\r\n    stream_ssl_client.setConnectionTimeout(1000);\r\n    stream_ssl_client.setHandshakeTimeout(5);\r\n  #elif defined(ESP8266)\r\n    ssl_client.setTimeout(1000); \/\/ Set connection timeout\r\n    ssl_client.setBufferSizes(4096, 1024); \/\/ Set buffer sizes\r\n    stream_ssl_client.setTimeout(1000); \/\/ Set connection timeout\r\n    stream_ssl_client.setBufferSizes(4096, 1024); \/\/ Set buffer sizes\r\n  #endif\r\n\r\n  \/\/ Initialize Firebase\r\n  initializeApp(aClient, app, getAuth(user_auth), processData, &quot;\ud83d\udd10 authTask&quot;);\r\n  app.getApp&lt;RealtimeDatabase&gt;(Database);\r\n  Database.url(DATABASE_URL);\r\n\r\n  \/\/ Set a database listener\r\n  streamClient.setSSEFilters(&quot;get,put,patch,keep-alive,cancel,auth_revoked&quot;);\r\n  Database.get(streamClient, listenerPath, processData, true \/* SSE mode (HTTP Streaming) *\/, &quot;streamTask&quot;);\r\n}\r\n\r\nvoid loop(){\r\n  \/\/ Maintain authentication and async tasks\r\n  app.loop();\r\n\r\n  \/\/ Check if authentication is ready\r\n  if (app.ready()){\r\n    \/\/Do nothing - everything works with callback functions\r\n    unsigned long currentTime = millis();\r\n    if (currentTime - lastSendTime &gt;= sendInterval){\r\n      \/\/ Update the last send time\r\n      lastSendTime = currentTime;\r\n      Serial.printf(&quot;Program running for %lu\\n&quot;, currentTime);        \r\n    }\r\n  }\r\n}\r\n\r\nvoid processData(AsyncResult &amp;aResult){\r\n  \/\/ Exits when no result available when calling from the loop.\r\n  if (!aResult.isResult())\r\n    return;\r\n\r\n  if (aResult.isEvent()){\r\n    Firebase.printf(&quot;Event task: %s, msg: %s, code: %d\\n&quot;, aResult.uid().c_str(), aResult.eventLog().message().c_str(), aResult.eventLog().code());\r\n  }\r\n\r\n  if (aResult.isDebug()){\r\n    Firebase.printf(&quot;Debug task: %s, msg: %s\\n&quot;, aResult.uid().c_str(), aResult.debug().c_str());\r\n  }\r\n\r\n  if (aResult.isError()){\r\n    Firebase.printf(&quot;Error task: %s, msg: %s, code: %d\\n&quot;, aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());\r\n  }\r\n\r\n  \/\/ When it receives data from the database\r\n  if (aResult.available()){\r\n    RealtimeDatabaseResult &amp;RTDB = aResult.to&lt;RealtimeDatabaseResult&gt;();\r\n    \/\/ we received data from the streaming client\r\n    if (RTDB.isStream()) {\r\n      Serial.println(&quot;----------------------------&quot;);\r\n      Firebase.printf(&quot;task: %s\\n&quot;, aResult.uid().c_str());\r\n      Firebase.printf(&quot;event: %s\\n&quot;, RTDB.event().c_str());\r\n      Firebase.printf(&quot;path: %s\\n&quot;, RTDB.dataPath().c_str());\r\n      Firebase.printf(&quot;etag: %s\\n&quot;, RTDB.ETag().c_str());\r\n      Firebase.printf(&quot;data: %s\\n&quot;, RTDB.to&lt;const char *&gt;());\r\n      Firebase.printf(&quot;type: %d\\n&quot;, RTDB.type());\r\n\r\n      \/\/ RTDB.type = 6 means the result is a JSON : https:\/\/github.com\/mobizt\/FirebaseClient\/blob\/main\/resources\/docs\/realtime_database_result.md#--realtime_database_data_type-type\r\n      \/\/ You receive a JSON when you initialize the stream\r\n      if (RTDB.type() == 6) {\r\n        Serial.println(RTDB.to&lt;String&gt;());\r\n        \/\/ Parse JSON\r\n        DynamicJsonDocument doc(512);\r\n        DeserializationError error = deserializeJson(doc, RTDB.to&lt;String&gt;());\r\n        if (error) {\r\n          Serial.print(&quot;deserializeJson() failed: &quot;);\r\n          Serial.println(error.c_str());\r\n          return;\r\n        }\r\n        \/\/ Iterate through JSON object\r\n        for (JsonPair kv : doc.as&lt;JsonObject&gt;()) {\r\n          int gpioPin = atoi(kv.key().c_str()); \/\/ Convert key (e.g., &quot;12&quot;) to int\r\n          bool state = kv.value().as&lt;bool&gt;();\r\n          digitalWrite(gpioPin, state ? HIGH : LOW);\r\n        }\r\n      }\r\n\r\n      \/\/ RTDB.type() = 4 means the result is a boolean\r\n      \/\/ RTDB.type() = 1 means the result is an integer\r\n      \/\/ learn more here: https:\/\/github.com\/mobizt\/FirebaseClient\/blob\/main\/resources\/docs\/realtime_database_result.md#--realtime_database_data_type-type\r\n      if (RTDB.type() == 4 || RTDB.type() == 1){\r\n        \/\/ get the GPIO number\r\n        int GPIO_number = RTDB.dataPath().substring(1).toInt();\r\n        bool state = RTDB.to&lt;bool&gt;();\r\n        digitalWrite(GPIO_number, state);\r\n        Serial.println(&quot;Updating GPIO State&quot;);\r\n      }\r\n\r\n      \/\/ The stream event from RealtimeDatabaseResult can be converted to values as following.\r\n      \/*bool v1 = RTDB.to&lt;bool&gt;();\r\n      int v2 = RTDB.to&lt;int&gt;();\r\n      float v3 = RTDB.to&lt;float&gt;();\r\n      double v4 = RTDB.to&lt;double&gt;();\r\n      String v5 = RTDB.to&lt;String&gt;();\r\n      Serial.println(v5); *\/\r\n    }\r\n    else{\r\n        Serial.println(&quot;----------------------------&quot;);\r\n        Firebase.printf(&quot;task: %s, payload: %s\\n&quot;, aResult.uid().c_str(), aResult.c_str());\r\n    }\r\n  }\r\n}\r\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Firebase-ESP\/raw\/main\/ESP-Firebase-Control-GPIOs-Anywhere\/ESP-Firebase-Control-GPIOs-Anywhere.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>Continue reading to learn how the code works or skip to the <a href=\"#demonstration\">demonstration section<\/a>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Include Libraries<\/h4>\n\n\n\n<p>First, include the required libraries. This code is also compatible with the ESP32.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#include &lt;Arduino.h&gt;\n#if defined(ESP32)\n    #include &lt;WiFi.h&gt;\n#elif defined(ESP8266)\n    #include &lt;ESP8266WiFi.h&gt;\n#endif\n#include &lt;WiFiClientSecure.h&gt;\n#include &lt;FirebaseClient.h&gt;\n#include \"ExampleFunctions.h\" \/\/ Provides the functions used in the examples.\n#include &lt;ArduinoJson.h&gt;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Network Credentials<\/h4>\n\n\n\n<p>Include your network credentials in the following lines so that your boards can connect to the internet using your local network.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Network and Firebase credentials\n#define WIFI_SSID \"REPLACE_WITH_YOUR_SSID\"\n#define WIFI_PASSWORD \"REPLACE_WITH_YOUR_PASSWORD\"<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Firebase Project API Key, Firebase User, and Database URL<\/h4>\n\n\n\n<p>Insert your <a href=\"#firebase-project-api-key\">Firebase project API key<\/a>\u2014the one you&#8217;ve gotten <a href=\"#firebase-project-api-key\">in this section<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define Web_API_KEY \"REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY\"<\/code><\/pre>\n\n\n\n<p>Insert your <a href=\"#Set-up-Realtime-Database\">database URL<\/a> in the following line:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Insert RTDB URLefine the RTDB URL<br>#define DATABASE_URL \"REPLACE_WITH_YOUR_DATABASE_URL\"<\/code><\/pre>\n\n\n\n<p>Insert the <a href=\"#Set-Authentication-Methods\">authorized email and the corresponding password<\/a>\u2014these are the details of the user you&#8217;ve added <a href=\"#Set-Authentication-Methods\">in this section<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define USER_EMAIL \"REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER\"\n#define USER_PASS \"REPLACE_WITH_FIREBASE_PROJECT_USER_PASS\"<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Declaring Firebase Authentication and Components<\/h4>\n\n\n\n<p>The following line creates an authentication object using the project API key, the project user email, and password.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);<\/code><\/pre>\n\n\n\n<p>Create two SSL clients. One to handle Firebase operations and another for Database Streaming (needed to listen to database changes).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>SSL_CLIENT ssl_client, stream_ssl_client;<\/code><\/pre>\n\n\n\n<p>This creates a <span class=\"rnthl rntliteral\">FirebaseApp<\/span> instance called <span class=\"rnthl rntliteral\">app<\/span> that refers to the Firebase application.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>FirebaseApp app;<\/code><\/pre>\n\n\n\n<p>The following lines set up the asynchronous communication framework for interacting with Firebase&#8217;s Realtime Database. You need to instantiate an Asynchronous client called <span class=\"rnthl rntliteral\">aClient<\/span> that enables secure HTTPS for handling Firebase operations and another one called <span class=\"rnthl rntliteral\">streamClient<\/span> to handle database streaming (listening to database changes). This will allow you to handle network and database streaming operations asynchronously.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>FirebaseApp app;\nusing AsyncClient = AsyncClientClass;\nAsyncClient aClient(ssl_client), streamClient(stream_ssl_client);<\/code><\/pre>\n\n\n\n<p>The following line creates a <span class=\"rnthl rntliteral\">RealtimeDatabase<\/span> object called <span class=\"rnthl rntliteral\">Database<\/span>, which represents the Firebase Realtime Database.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>RealtimeDatabase Database;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Database Path<\/h4>\n\n\n\n<p>Then, create a variable that saves the database path where we&#8217;ll be listening for changes. Taking into account the database structure we created previously, the listener database path should be as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Database  path (where the data is)\nString listenerPath = \"board1\/outputs\/digital\/\";<\/code><\/pre>\n\n\n\n<p>If you want to add more boards, then you just need to change the listener path accordingly.<\/p>\n\n\n\n<p>Create variables for the outputs you&#8217;ll control. In our case, we&#8217;re controlling GPIOs 12, 13, and 14. You can control any other ESP32 GPIOs (you&#8217;ll also need to change the database nodes):<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>const int output1 = 12;\nconst int output2 = 13;\nconst int output3 = 14;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">initWifi()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">iniWifi()<\/span> function connects the ESP32 to your local network. We&#8217;ll call it later in the <span class=\"rnthl rntliteral\">setup()<\/span> to initialize Wi-Fi.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Initialize WiFi\nvoid initWiFi() {\n  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);\n  Serial.print(\"Connecting to WiFi ..\");\n  while (WiFi.status() != WL_CONNECTED) {\n    Serial.print('.');\n    delay(1000);\n  }\n  Serial.println(WiFi.localIP());\n  Serial.println();\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">setup()<\/h4>\n\n\n\n<p>Let&#8217;s now jump to the <span class=\"rnthl rntliteral\">setup()<\/span>.<\/p>\n\n\n\n<p>Initialize the Serial Monitor:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200);<\/code><\/pre>\n\n\n\n<p>Declare your GPIOs as outputs using the <span class=\"rnthl rntliteral\">pinMode()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>pinMode(output1, OUTPUT);\npinMode(output2, OUTPUT);\npinMode(output3, OUTPUT);<\/code><\/pre>\n\n\n\n<p>Call the <span class=\"rnthl rntliteral\">initiWiFi()<\/span> function we created previously, to connect your board to your local network.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>initWiFi();<\/code><\/pre>\n\n\n\n<p>Configure the SSL Client.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Configure SSL client\nssl_client.setInsecure();\nstream_ssl_client.setInsecure();\n#if defined(ESP32)\n  ssl_client.setConnectionTimeout(1000);\n  ssl_client.setHandshakeTimeout(5);\n  stream_ssl_client.setConnectionTimeout(1000);\n  stream_ssl_client.setHandshakeTimeout(5);\n#elif defined(ESP8266)\n  ssl_client.setTimeout(1000); \/\/ Set connection timeout\n  ssl_client.setBufferSizes(4096, 1024); \/\/ Set buffer sizes\n  stream_ssl_client.setTimeout(1000); \/\/ Set connection timeout\n  stream_ssl_client.setBufferSizes(4096, 1024); \/\/ Set buffer sizes\n#endif<\/code><\/pre>\n\n\n\n<p>The following line initializes the Firebase app with authentication and sets the <span class=\"rnthl rntliteral\">processData()<\/span> as the callback function for async results (this means that any results from the <span class=\"rnthl rntliteral\">initializeApp()<\/span> function will be handled on the <span class=\"rnthl rntliteral\">processData()<\/span> callback function).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>initializeApp(aClient, app, getAuth(user_auth), processData, \"\ud83d\udd10 authTask\");<\/code><\/pre>\n\n\n\n<p>Then, tell that you want to set the <span class=\"rnthl rntliteral\">Database<\/span> object defined earlier as a database for our Firebase <span class=\"rnthl rntliteral\">app<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>app.getApp&lt;RealtimeDatabase&gt;(Database);<\/code><\/pre>\n\n\n\n<p>Finally, set the database URL.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Database.url(DATABASE_URL);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Stream Database &#8211; Listening for Changes<\/h4>\n\n\n\n<p>Now, we need to set a database listener so that we receive data on the ESP32 when the database changes.<\/p>\n\n\n\n<p>The following line configures the types of Server-Sent Events (SSE) that the streamClient (will listen for when connected to the Firebase Realtime Database. In this case, we&#8217;re including all event types.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>streamClient.setSSEFilters(\"get,put,patch,keep-alive,cancel,auth_revoked\");<\/code><\/pre>\n\n\n\n<p>Finally, the following line initiates a streaming connection to the Firebase Realtime Database at the specified <span class=\"rnthl rntliteral\">listenerPath<\/span>, using the <span class=\"rnthl rntliteral\">streamClient<\/span> to listen for real-time updates. When events occur, they are processed by the <span class=\"rnthl rntliteral\">processData()<\/span> callback function (defined later in the code).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Database.get(streamClient, listenerPath, processData, true \/* SSE mode (HTTP Streaming) *\/, \"streamTask\");<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">loop()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">loop()<\/span> is empty and only prints for how long the program is running (this is optional). You just need to maintain the <span class=\"rnthl rntliteral\">app.loop()<\/span> command.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void loop(){\n  \/\/ Maintain authentication and async tasks\n  app.loop();\n\n  \/\/ Check if authentication is ready\n  if (app.ready()){\n    \/\/Do nothing - everything works with callback functions\n    unsigned long currentTime = millis();\n    if (currentTime - lastSendTime &gt;= sendInterval){\n      \/\/ Update the last send time\n      lastSendTime = currentTime;\n      Serial.printf(\"Program running for %lu\\n\", currentTime);        \n    }\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">processData Function &#8211; Handling Database Changes<\/h3>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">processData()<\/span> function will handle all events related to Firebase operations, including changes in the database data.<\/p>\n\n\n\n<p>We can check if we have new data in the database using the <span class=\"rnthl rntliteral\">aResult.available()<\/span> command.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if (aResult.available()){<\/code><\/pre>\n\n\n\n<p>Then, we convert the result to a format we can access in our code\u2014a variable of type <span class=\"rnthl rntliteral\">RealtimeDatabaseResult<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>RealtimeDatabaseResult &amp;RTDB = aResult.to&lt;RealtimeDatabaseResult&gt;();<\/code><\/pre>\n\n\n\n<p>We check if the received data is from the streaming client.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if (RTDB.isStream()) {<\/code><\/pre>\n\n\n\n<p>Then, we can print available data about the event.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Firebase.printf(\"task: %s\\n\", aResult.uid().c_str());\nFirebase.printf(\"event: %s\\n\", RTDB.event().c_str());\nFirebase.printf(\"path: %s\\n\", RTDB.dataPath().c_str());\nFirebase.printf(\"etag: %s\\n\", RTDB.ETag().c_str());\nFirebase.printf(\"data: %s\\n\", RTDB.to&lt;const char *&gt;());\nFirebase.printf(\"type: %d\\n\", RTDB.type());<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">RTDB.type()<\/span> command tells us what type of data we received from the database. The results can be:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>realtime_database_data_type_undefined or -1<\/li>\n\n\n\n<li>realtime_database_data_type_null or 0.<\/li>\n\n\n\n<li>realtime_database_data_type_integer or 1.<\/li>\n\n\n\n<li>realtime_database_data_type_float or 2.<\/li>\n\n\n\n<li>realtime_database_data_type_double or 3.<\/li>\n\n\n\n<li>realtime_database_data_type_boolean or 4.<\/li>\n\n\n\n<li>realtime_database_data_type_string or 5.<\/li>\n\n\n\n<li>realtime_database_data_type_json or 6.<\/li>\n\n\n\n<li>realtime_database_data_type_array or 7.<\/li>\n<\/ul>\n\n\n\n<p>When the ESP first connects to the database, it is triggered on the root(<span class=\"rnthl rntliteral\">\/<\/span>) path and returns a JSON object with all child nodes (<span class=\"rnthl rntliteral\">RTDB.type() = 6<\/span>). So, we can get all values from the database and update the ESP32 GPIOs when it first runs. This is also useful because if the ESP32 resets, it will always receive this JSON object first, and will be able to update all GPIOs.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"751\" height=\"450\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Streaming-Database-Initial-JSON.png?resize=751%2C450&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Streaming Database First Run\" class=\"wp-image-170474\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Streaming-Database-Initial-JSON.png?w=751&amp;quality=100&amp;strip=all&amp;ssl=1 751w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Streaming-Database-Initial-JSON.png?resize=300%2C180&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 751px) 100vw, 751px\" \/><\/figure><\/div>\n\n\n<p>As you can see from the previous screenshot, the JSON object it receives looks as follows (it might be different depending on the GPIO states):<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>{\n  \"12\": 0,\n  \"13\": 0,\n  \"14\": 0\n}<\/code><\/pre>\n\n\n\n<p>When this happens, the returned data is of type JSON. So, we can get it  and convert it to a JSON variable <span class=\"rnthl rntliteral\">doc<\/span> as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if (RTDB.type() == 6) {\n    Serial.println(RTDB.to&lt;String&gt;());\n    \/\/ Parse JSON\n    DynamicJsonDocument doc(512);\n    DeserializationError error = deserializeJson(doc, RTDB.to&lt;String&gt;());\n    if (error) {\n      Serial.print(\"deserializeJson() failed: \");\n      Serial.println(error.c_str());\n      return;\n    }<\/code><\/pre>\n\n\n\n<p>Then, we can iterate through the JSON object and get the keys (GPIOs) and corresponding values (GPIO states). In each iteration, we save the GPIO on the <span class=\"rnthl rntliteral\">gpioPin<\/span> variable and its corresponding state on the <span class=\"rnthl rntliteral\">state<\/span> variable. Then, we call the <span class=\"rnthl rntliteral\">digitalWrite()<\/span> function to update its state.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Iterate through JSON object\nfor (JsonPair kv : doc.as&lt;JsonObject&gt;()) {\n  int gpioPin = atoi(kv.key().c_str()); \/\/ Convert key (e.g., \"12\") to int\n  bool state = kv.value().as&lt;bool&gt;();\n  digitalWrite(gpioPin, state ? HIGH : LOW);\n}<\/code><\/pre>\n\n\n\n<p>This runs through all keys and values allowing us to update all GPIOs.<\/p>\n\n\n\n<p>If <span class=\"rnthl rntliteral\">RTDB.type()<\/span> is <strong>4<\/strong> or <strong>1<\/strong>, it means we inserted a boolean or an integer value in the database. In that case, we get the database path that corresponds to the GPIO number, and the inserted data that corresponds to the GPIO state.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if (RTDB.type() == 4 || RTDB.type() == 1){\n  \/\/ get the GPIO number\n  int GPIO_number = RTDB.dataPath().substring(1).toInt();\n  bool state = RTDB.to&lt;bool&gt;();<\/code><\/pre>\n\n\n\n<p>After getting that, we can update the GPIO state according to the changes in the database.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>digitalWrite(GPIO_number, state);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"demonstration\">Demonstration<\/h2>\n\n\n\n<p>After uploading, open the Serial Monitor at a baud rate of 115200 and reset the board. You should get something as shown below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"751\" height=\"450\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Streaming-Database-Initial-JSON.png?resize=751%2C450&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Streaming Database First Run\" class=\"wp-image-170474\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Streaming-Database-Initial-JSON.png?w=751&amp;quality=100&amp;strip=all&amp;ssl=1 751w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Streaming-Database-Initial-JSON.png?resize=300%2C180&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 751px) 100vw, 751px\" \/><\/figure><\/div>\n\n\n<p>As you can see, when the ESP first runs, it gets a JSON object with all GPIO states.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>{\n  \"12\": 0,\n  \"13\": 0,\n  \"14\": 0\n}<\/code><\/pre>\n\n\n\n<p>Then, go to the Firebase Realtime Database on the Firebase console. Manually change the GPIO states (either 0 or 1). After inserting a new value, press Enter.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"748\" height=\"356\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Database-Listener-Firebase-Change-GPIO-State.png?resize=748%2C356&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Realtime Database Saving ESP GPIO States\" class=\"wp-image-170477\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Database-Listener-Firebase-Change-GPIO-State.png?w=748&amp;quality=100&amp;strip=all&amp;ssl=1 748w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Database-Listener-Firebase-Change-GPIO-State.png?resize=300%2C143&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 748px) 100vw, 748px\" \/><\/figure><\/div>\n\n\n<p>Right after, you&#8217;ll see on the Serial Monitor that the ESP32 detected the changes.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"308\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Listener-Updated-GPIO-States.png?resize=750%2C308&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Streaming Database ESP Detecting Changes Serial Monitor\" class=\"wp-image-170484\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Listener-Updated-GPIO-States.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP32-Firebase-Listener-Updated-GPIO-States.png?resize=300%2C123&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>And it will update the GPIO states and light up the LEDs almost instantaneously.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"438\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/ESP8266-Three-LEDs-Breadboard.jpg?resize=750%2C438&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Control ESP8266 Outputs from Anywhere\" class=\"wp-image-110529\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/ESP8266-Three-LEDs-Breadboard.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/ESP8266-Three-LEDs-Breadboard.jpg?resize=300%2C175&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Then, if you reset your board (press the RST button or remove and apply power again), when it restarts, it will get the latest GPIO states from the database and update them right away.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Taking it Further &#8211; Add More Boards<\/h2>\n\n\n\n<p>You can take this project further and add more boards. To do that, create new database nodes for a second board. You can add ESP32 or ESP8266 boards.<\/p>\n\n\n\n<p>You can download the following JSON file and import it to your database, and it will create nodes for two boards:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/github.com\/RuiSantosdotme\/Firebase-ESP\/blob\/main\/ESP-Firebase-Control-GPIOs-Anywhere\/database-outputs-multiple-boards.zip?raw=true\" target=\"_blank\" rel=\"noreferrer noopener\">Download JSON file<\/a><\/li>\n<\/ul>\n\n\n\n<p>After uploading the JSON file, the database will look as follows:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"656\" height=\"577\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/Firebase-RTDB-Save-Multiple-Boards-GPIO-States.png?resize=656%2C577&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Firebase Realtime Database Save GPIO Sates Multiple Boards\" class=\"wp-image-110501\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/Firebase-RTDB-Save-Multiple-Boards-GPIO-States.png?w=656&amp;quality=100&amp;strip=all&amp;ssl=1 656w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/Firebase-RTDB-Save-Multiple-Boards-GPIO-States.png?resize=300%2C264&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 656px) 100vw, 656px\" \/><\/figure><\/div>\n\n\n<p>Now, you can upload the same code to the new board (it is compatible with the ESP32 and ESP8266). But <strong>don&#8217;t forget to change the listening path<\/strong>. It should be: <\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>String listenerPath = \"<strong>board2<\/strong>\/outputs\/digital\/\";<\/code><\/pre>\n\n\n\n<p>Now, you can control both boards by changing the GPIO states on the database.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/ESP32-ESP8266-Three-LEDs.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Control ESP32 and ESP8266 Outputs from Anywhere Multiple Boards\" class=\"wp-image-110530\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/ESP32-ESP8266-Three-LEDs.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/04\/ESP32-ESP8266-Three-LEDs.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>In Part 2, we&#8217;ll create a Firebase web app so that you have a nice interface to control your GPIOs from anywhere without having to use the Firebase console and change the database manually:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>PART 2<\/strong>: <a href=\"https:\/\/randomnerdtutorials.com\/control-esp-gpios-firebase-web-app\/\">Control ESP32\/ESP8266 GPIOs from Anywhere (Firebase Web App)<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you learned how to use the Firebase Realtime Database to save the ESP GPIO states. You also learned how to program the ESP8266 to listen for database changes. Whenever a change is detected, we updated the corresponding GPIO states. You can change the code so that the ESP listens for any other data saved on the database, not only GPIO states. Because you can access the Firebase Realtime Database from anywhere, you can control your boards from anywhere too. This is great for IoT projects.<\/p>\n\n\n\n<p>In Part 2, we&#8217;ll create a web app to control your GPIOs from anywhere, without the need to login manually on the Firebase console:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>PART 2<\/strong>: <a href=\"https:\/\/randomnerdtutorials.com\/control-esp-gpios-firebase-web-app\/\">Control ESP32\/ESP8266 GPIOs from Anywhere (Firebase Web App)<\/a><\/li>\n<\/ul>\n\n\n\n<p>If you like Firebase projects, please take a look at our eBook. We&#8217;re sure you&#8217;ll like it:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><a href=\"https:\/\/randomnerdtutorials.com\/firebase-esp32-esp8266-ebook\/\">Firebase Web App with ESP32 and ESP8266<\/a><\/strong><\/li>\n<\/ul>\n\n\n\n<p>Learn more about the ESP8266 with our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-esp8266\/\">Free ESP8266 Projects and Tutorials<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/home-automation-using-esp8266\/\">Home Automation using ESP8266<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/build-web-servers-esp32-esp8266-ebook\/\">Build Web Servers with ESP32 and ESP8266 eBook (2nd Edition)<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, you&#8217;ll learn how to control the ESP8266 GPIOs from anywhere using Firebase. We&#8217;ll create nodes on the Firebase Realtime Database to save the current GPIO states. Whenever &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Firebase: Control ESP8266 NodeMCU GPIOs from Anywhere\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/firebase-control-esp8266-nodemcu-gpios\/#more-110533\" aria-label=\"Read more about Firebase: Control ESP8266 NodeMCU GPIOs from Anywhere\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":170631,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[265,214,246,300,240,264],"tags":[],"class_list":["post-110533","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp8266-project","category-esp8266","category-esp8266-arduino-ide","category-0-esp8266","category-esp8266-projects","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/07\/ESP8266-Control-GPIOs-from-anywhere-Firebase.jpg?fit=1920%2C1080&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/110533","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=110533"}],"version-history":[{"count":13,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/110533\/revisions"}],"predecessor-version":[{"id":170650,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/110533\/revisions\/170650"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/170631"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=110533"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=110533"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=110533"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}