ESP32/ESP8266 Firebase: Send BME280 Sensor Readings to the Realtime Database
In this guide, you’ll learn how to send BME280 sensor readings to the Firebase Realtime Database using the ESP32 or ESP8266 NodeMCU boards. The ESP board will authenticate as a user with email and password, and you’ll add database security rules to secure your data. The boards will be programmed using the Arduino core.
Firebase is Google’s mobile application development platform that helps you build, improve, and grow your app. It has many services used to manage data from any android, IOS, or web application like authentication, realtime database, hosting, etc.
Project Overview
The following diagram shows a high-level overview of the project we’ll build.
The ESP32/ESP8266 authenticates as a user with email and password (that user must be set on the Firebase authentication methods);
After authentication, the ESP gets the user UID;
The database is protected with security rules. The user can only access the database nodes under the node with its user UID. After getting the user UID, the ESP can publish data to the database;
The ESP sends temperature, humidity and pressure to the database.
These are the main steps to complete this project:
You can continue with the Firebase project from this previous tutorial or create a new project. If you use the Firebase project of that previous tutorial, you can skip to section 4) Set up Realtime Database because the authentication methods are already set up.
Preparing Arduino IDE
For this tutorial, we’ll program the ESP32 and ESP8266 boards using the Arduino core. So, make sure you have the ESP32 or ESP8266 add-on installed in your Arduino IDE:
Give a name to your project, for example: ESP-Project, and click Continue.
Next, enable or disable AI assistance for your project. This is optional.
Disable the option Enable Google Analytics for this project, as it is not needed. Then, click Create project.
It will take a few seconds to set up your project. Click Continue when it’s ready.
You’ll be redirected to your Project console page.
2) Set Authentication Methods
To allow authentication with email and password, first, you need to set authentication methods for your app.
“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’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices.” To learn more about the authentication methods, you can read the documentation.
You need to set authentication methods for your app.
“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). Knowing a user’s identity allows an app to securely save user data in the cloud …” To learn more about the authentication methods, you can read the documentation.
On the left sidebar, click on Build > Authentication and then on Get started.
There are several authentication methods like email and password, Google Account, Facebook account, and others.
Select Email/Password and enable that authentication method. Then, click Save.
Then, at the top, click on the Users tab. Then, click on Add user.
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 Add user.
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.
3) Creating a Web App for Your Project (and API key)
To interface with your Firebase project using the ESP8266 and ESP32, you need to get your project API key. To get an API key for your project, you need to create a web app first. Follow the next steps.
On the left sidebar, click on Settings.
Scroll down on that page to the Your apps section. Then, click on the web icon </> to create and add a web app to your Firebase project.
Give your app a name. Then, check the box next to √ Also set up Firebase Hosting for this App. Click Register app.
Then, in the firebaseConfig object, you can find your API key. Save it because you’ll need it later. After this, you can also access the firebaseConfig object if you go to your Project settings in your Firebase console and scroll down to the Your apps section.
Click Next on the preceding steps, and finally on Continue to console.
4) Set up Realtime Database
Now, let’s create a realtime database and set up database rules for our project.
1) On the left sidebar, click on Realtime Database and then click on Create Database.
2) Select your database location. It should be the closest to your location.
3) Set up security rules for your database. You can select Start in test mode. We’ll change the database rules in just a moment.
4) Your database is now created. You need to copy and save the database URL—highlighted in the following image—because you’ll need it later in your ESP32/ESP8266 code.
5) Set up Database Security Rules
Now, let’s set up the database rules. On the Realtime Database tab, select the Rules tab at the top. Then, click on Edit rules, copy the following rules and then click Publish.
// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
"rules": {
"UsersData": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
These rules allow access only to the node that matches the authenticated user’s UID. This ensures that each user can access only their own data. In other words, a user can only read or write to the parts of the database located under their specific UID. Any data stored outside of their UID node will not be accessible to them.
For example, imagine our user UID is RjO3taAzMMXBB2Xmir2LQ. With our security rules, it can read and write data to the database under the node UsersData/RjO3taAzMMXBB2Xmir2LQ.
You’ll better understand how this works when you start working with the ESP32/ESP8266.
6) ESP32/ESP8266 Send Sensor Readings to the Realtime Database
In this section, we’ll program the ESP32 or ESP8266 boards to do the following tasks:
* you can also test the project with random values instead of sensor readings, or you can use any other sensor you’re familiar with.
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Schematic Diagram
In this tutorial, we’ll send BME280 sensor readings to the Firebase Realtime Database. So, you need to wire the BME280 sensor to your board. Follow one of the following schematic diagrams.
ESP32 with BME280
We’re going to use I2C communication with the BME280 sensor module. For that, wire the sensor to the default ESP32 SCL (GPIO 22) and SDA (GPIO 21) pins, as shown in the following schematic diagram.
We’re going to use I2C communication with the BME280 sensor module. For that, wire the sensor to the ESP8266 SDA (GPIO 4) and SCL (GPIO 5) pins, as shown in the following schematic diagram.
Follow the next instructions if you’re using VS Code with the PlatformIO or pioarduino extension.
Install the FirebaseClient Library
Click on the PIO Home icon and select the Libraries tab. Search for “FirebaseClient“. Select the Firebase Client Library by Mobitz.
If you’re using VS Code with the PlatformIO extension, click on the PIO Home icon and then select the Libraries tab. Search for “FirebaseClient“. Select the Firebase Client Library by Mobitz.
Then, click Add to Project and select the project you’re working on.
Then, click Add to Project and select the project you’re working on.
Install the BME280 Library
In the Libraries tab, search for BME280. Select the Adafruit BME280 library.
Then, click Add to Project and select the project you’re working on.
Also, change the monitor speed to 115200 by adding the following line to the platformio.ini file of your project:
This creates a FirebaseApp instance called app that refers to the Firebase application.
FirebaseApp app;
The following lines set up the asynchronous communication framework for interacting with Firebase’s Realtime Database. Basically, you create an SSL client using the WiFiClientSecure library. Then, you instantiate an Asynchronous client called aClient that enables secure HTTPS. This will allow you to handle network operations asynchronously.
WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);
The following line creates a RealtimeDatabase object called Database, which represents the Firebase Realtime Database.
RealtimeDatabase Database;
Timer and Data Variables
Then create variables to track the time. We’ll send sensor readings to the database every 10 seconds.
// Timer variables for sending data every 10 seconds
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 10000;
Create a variable to save the user UID. The uid variable will be used to save the user’s UID. We can get the user’s UID after the authentication.
// Variable to save USER UID
String uid;
Create variables to save the database path and specific database nodes. We’ll update these variables later in the code when we get the user UID.
// Variables to save database paths
String databasePath;
String tempPath;
String humPath;
String presPath;
BME280 Variables
Then, create an Adafruit_BME280 object called bme. This automatically creates a sensor object on the ESP32 or ESP8266 default I2C pins.
Adafruit_BME280 bme; // I2C
The following variables will hold the temperature, humidity, and pressure readings from the sensor.
The initBME() function will initialize the BME280 sensor. We’ll call it later in the setup().
// Initialize BME280
void initBME(){
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
Serial.print("BME280 Initialized with success");
}
setup()
In the setup(), initialize the Serial Monitor, the BME280 sensor, and connect the board to your Wi-Fi network.
void setup(){
Serial.begin(115200);
initBME();
// Connect to Wi-Fi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println();
Configure the SSL Client.
ssl_client.setInsecure();
#if defined(ESP32)
ssl_client.setConnectionTimeout(1000);
ssl_client.setHandshakeTimeout(5);
#elif defined(ESP8266)
ssl_client.setTimeout(1000); // Set connection timeout
ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes
#endif
The following line initializes the Firebase app with authentication and sets the processData() as the callback function for async results (this means that any results from the initializeApp() function will be handled on the processData() callback function).
Then, tell that you want to set the Database object defined earlier as a database for our Firebase app.
app.getApp<RealtimeDatabase>(Database);
Finally, set the database URL.
Database.url(DATABASE_URL);
loop()
The Firebase library we’re using works asynchronously and with callback functions. This means that when an event happens, the corresponding assigned callback functions will run. To keep the Firebase app running, handling authentication and asynchronous tasks, we need to add app.loop() at the start of our loop() function.
void loop(){
app.loop();
The app.ready() command checks if Firebase authentication is complete and ready, so that we can proceed with other Firebase operations (like writing to the database).
if (app.ready()){
The following lines check if 10 seconds (sendInterval) have passed. We’ll use this to send data periodically every 10 seconds.
// Periodic data sending every 10 seconds
unsigned long currentTime = millis();
if (currentTime - lastSendTime >= sendInterval){
// Update the last send time
lastSendTime = currentTime;
After a successful authentication, we’ll get the user UID and save it in the uid variable. Then, we’ll update the database path to UsersData/<USER_UID>.
// Get User UID
Firebase.printf("User UID: %s\n", app.getUid().c_str());
uid = app.getUid().c_str();
databasePath = "UsersData/" + uid;
Then, we’ll update the path for each node where the readings will be saved.
<T> refers to the data type. In the code, it’s used as Database.set<String>, Database.set<int> and Database.set<float>. You can use other data types.
AsyncClient &client: this is the asynchronous client object (aClient in the code) that manages the network connection to Firebase.
const String &path: specifies the path in the Firebase Realtime Database where the data will be written. The path is relative to the database root (defined by DATABASE_URL). For example: “test/string”.
T value: the value to be written to the specified path.
AsyncResultCallback callback: a function pointer to the callback that handles the result of the asynchronous operation. In the code, this is the processData() function. It processes the AsyncResult object to log events, errors, debug messages, or successful payloads. The callback is called when the Firebase server responds or if an error occurs during the request.
const String &uid: a unique identifier for the task, used to track the specific operation in the callback. This helps differentiate between multiple asynchronous tasks in the processData() function.
Finally, the processData() function logs the results of the asynchronous Firebase operations.
void processData(AsyncResult &aResult) {
if (!aResult.isResult())
return;
if (aResult.isEvent())
Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.eventLog().message().c_str(), aResult.eventLog().code());
if (aResult.isDebug())
Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());
if (aResult.isError())
Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());
if (aResult.available())
Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());
}
Demonstration
Upload the previous code to your board. The code is compatible with both the ESP32 and ESP8266 boards. Don’t forget to insert your network credentials, project API key, database URL, user email, and the corresponding password.
After uploading the code, press the board RST button so that it starts running the code. It should authenticate to Firebase, get the user UID, and immediately send new readings to the database.
Open the Serial Monitor at a baud rate of 115200 and check that everything is working as expected.
Aditionally, go to the Realtime Database on your Firebase project interface and check that new readings are saved. Notice that it saves the data under a node with the user UID—this is a way to restrict access to the database.
And that’s it. You’ve successfully sent sensor readings to the Firebase Realtime Database, and you protected the data using database rules.
Wrapping Up
In this tutorial, you’ve learned how to authenticate the ESP32/ESP8266 as a user with email and password, send sensor readings to the database, and set up security rules to protect your database and restrict access.
In PART 2, we’ll create a Firebase Web App with authentication (login with email and password) that displays the sensor readings saved in the database. Only an authorized logged-in user can access the data. Later, you’ll be able to modify that project to display all sorts of data and restrict or allow access to the data to specific users.
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
How to set firebase authentication dynamicly through web server or mobile app and save in memory of esp32 (EPROM) so no hard coded auth will need and easy for iot devices development
Hi.
you would need to create an access point with the ESP32 that would load a form where you would enter the user email and password.
Then, those credentials would be written permanently on the ESP32 memory (like SPIFFS, for example).
Then, to initialize Firebase, you would need to read from SPIFFS to get email and password.
You can implement something like this “Wi-Fi Manager” we implemented on the following project. But instead of SSID and password, you would insert email and password: https://randomnerdtutorials.com/esp32-status-indicator-sensor-pcb/
Regards,
Sara
Great tutorial!
It looks the sensor readings are updated every 3 minutes in the firebase database.
Is the data also logged over time in the database?
So that you log the temperature over several weeks for example and export a tab delimited text file with all the sensor readings?
Hi.
In this specific project no.
It overwrites the current values.
I’m already preparing a new tutorial that logs the data over time with timestamps.
So, you’ll have historical data saved.
Regards,
Sara
Dear Sara, I bought your books, thanks a lot.
Two simple questions:
1- Should be possible to connect to RTDB more than one device (board) ? I think so.
2- Can the different boards exchange data ?
Thanks.
Hi.
Yes. More than one board can connect to the database. Each board can be an independent user or be configured to be the same user.
Yes. The boards can exchange data because you can read and write to the database with both boards, and you can give permissions so that all boards access all data.
Regards,
Sara
Dear Sara:
thanks for your answer.
Can you please plan an example on how each board can be an independent user or be configured to be the same user and how the boards can exchange data between them ?
Regards,
Domenico
In file included from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:41:0,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Utils.h:37,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/signer/Signer.h:37,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase.h:47,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:50,
from C:\Users\lucas\Documents\IoT\ESP32 CAM\Pluviógrafo\Firebase\Pluv_fb\Pluv_fb.ino:9:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:43:1: error: expected class-name before ‘{‘ token
{
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h: In member function ‘int FB_WCS::_connect(const char*, uint16_t, long unsigned int)’:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:50:5: error: ‘_timeout’ was not declared in this scope
_timeout = timeout;
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:52:27: error: ‘connect’ was not declared in this scope
if (connect(host, port) == 0)
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:54:11: error: ‘_CA_cert’ was not declared in this scope
if (_CA_cert != NULL)
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:55:32: error: ‘sslclient’ was not declared in this scope
mbedtls_x509_crt_free(&sslclient->ca_cert);
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:55:50: error: ‘mbedtls_x509_crt_free’ was not declared in this scope
mbedtls_x509_crt_free(&sslclient->ca_cert);
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:58:5: error: ‘_connected’ was not declared in this scope
_connected = true;
^
In file included from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Utils.h:37:0,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/signer/Signer.h:37,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase.h:47,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:50,
from C:\Users\lucas\Documents\IoT\ESP32 CAM\Pluviógrafo\Firebase\Pluv_fb\Pluv_fb.ino:9:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h: At global scope:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:766:5: error: ‘mbedtls_pk_context’ does not name a type
mbedtls_pk_context *pk_ctx = nullptr;
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:767:5: error: ‘mbedtls_entropy_context’ does not name a type
mbedtls_entropy_context *entropy_ctx = nullptr;
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:768:5: error: ‘mbedtls_ctr_drbg_context’ does not name a type
mbedtls_ctr_drbg_context *ctr_drbg_ctx = nullptr;
^
In file included from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase.h:49:0,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:50,
from C:\Users\lucas\Documents\IoT\ESP32 CAM\Pluviógrafo\Firebase\Pluv_fb\Pluv_fb.ino:9:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/session/FB_Session.h:347:3: error: ‘WiFiClientSecure’ does not name a type
WiFiClientSecure *getWiFiClient();
^
Foram encontradas múltiplas bibliotecas para “SD.h”
Hi.
I never tried this library with the ESP32-CAM.
Did you try the example with a “normal” ESP32 first? Just to check if it is a problem with the library or with the board.
Regards,
Sara
Hi Sara, thank you for the great tutorial. Unfortunately the ESP32 have some troubles quite often. Can you help me resolve this problem? 🙂
The serial log is this:
Token info: type = id token, status = on request
Token info: type = id token, status = ready
Getting User UID
User UID: the user ID
FAILED
REASON: connection refused
Writing value: 25.02 on the following path: /UsersData/the user ID/humidity
PASSED
PATH: /UsersData/the user ID/humidity
TYPE: double
Writing value: 945.23 on the following path: /UsersData/the user ID/pressure
PASSED
PATH: /UsersData/the user ID/pressure
TYPE: double
Writing value: 25.97 on the following path: /UsersData/the user ID/temperature
PASSED
PATH: /UsersData/the user ID/temperature
TYPE: float
Writing value: 24.86 on the following path: /UsersData/the user ID/humidity
PASSED
PATH: /UsersData/the user ID/humidity
TYPE: float
Writing value: 945.20 on the following path: /UsersData/the user ID/pressure
PASSED
PATH: /UsersData/the user ID/pressure
TYPE: double
Writing value: 26.19 on the following path: /UsersData/the user ID/temperature
PASSED
PATH: /UsersData/the user ID/temperature
TYPE: float
FAILED
REASON: connection refused
FAILED
REASON: connection refused
FAILED
REASON: connection refused
FAILED
REASON: connection refused
Writing value: 945.23 on the following path: /UsersData/the user ID/pressure
PASSED
PATH: /UsersData/the user ID/pressure
TYPE: double
Writing value: 26.51 on the following path: /UsersData/the user ID/temperature
PASSED
PATH: /UsersData/the user ID/temperature
TYPE: float
Writing value: 24.27 on the following path: /UsersData/the user ID/humidity
PASSED
PATH: /UsersData/the user ID/humidity
TYPE: double
Writing value: 945.27 on the following path: /UsersData/the user ID/pressure
PASSED
PATH: /UsersData/the user ID/pressure
TYPE: double
FAILED
REASON: connection refused
Writing value: 24.26 on the following path: /UsersData/the user ID/humidity
PASSED
PATH: /UsersData/the user ID/humidity
TYPE: double
FAILED
REASON: connection refused
FAILED
REASON: connection refused
FAILED
REASON: connection refused
[E][ssl_client.cpp:36] _handle_error(): [start_ssl_client():216]: (-29312) SSL – The connection indicated an EOF
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -29312
FAILED
REASON: send request failed
And also sometimes:
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][ssl_client.cpp:70] start_ssl_client(): ERROR opening socket
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
Guru Meditation Error: Core 1 panic’ed (StoreProhibited). Exception was unhandled.
Core 1 register dump:
(…)
I haven’t done anything with the device or firebase and I haven’t rebooted.
Hi.
Make sure your board has a good wi-fi connection.
Did you change anything on the code?
Try to increase the delay time between each reading sent to the database and check if that solves the problem.
Regards,
Sara
Hello,
I would like control my ESP8266 from the database. So, I use
Firebase.setString(“LED”, “OFF”);
and then, with Firebase.getString () function, I am trying to control an output.
But this library has no member named setString or getString.
Could you please how can I control -let say- a LED on ESP8266 from firebase?
Thank you very much for your work. It is allways an inspiration.
Maybe you can help me to solve a problem I am fiddeling around since a couple of days and that meanwhile gave my nerves the rest.
Given is a well defined and static Firebase database (see at the end of this text).
At a random place in my code I want to update the value of a unique key. In this particular case, it is the string value of field time of sensor1 of board1.
It is assumed that the ESP32-boards do not change the database design. Without time series there is not only no necessity to do that, but furthermore also a common principle that clients must not do that.
I am using the Firebase_ESP_Client library from Suwatchai (Mobizt).
Works, the value of e.g. 1659712471132 is written to the corresponding timestamp.
But it will also work, if the initial database would not even contain the node timestamp. So it will create that node. Maybe that could be handled somehow but that does not interest me at the moment.
this will create an additional node time under the existing time. It looks like this:
},
“sensor1”: {
“sens1”: -99,
“sens2”: -99,
“sens3”: -99,
“sens4”: -99,
“sensorname”: “Sensor1”,
“time”: {
“time”: “05-08-2022-17:14:31\n”
},
“timestamp”: 1659712471132
},
“sensor2”: {
The question is, which code snippet will access a certain defined existing node to put string data in its value field.
Hello, almost everything is ready. There is an error in the monitor at the end.
Connecting to WiFi …192.168.116.190
Token info: type = id token (GITKit token), status = on request
Token info: type = id token (GITKit token), status = error
Token error: code: -4, message: connection lost
Getting User UID………
Can you help?
Dear Sara
I have followed your tutorial and added the HX711 module to my project. However, I am facing some issues and I would like to save data to the database only when the weight exceeds 100 grams. Can you guide me on how to do this? Thank you.
sous PlatforIO, avec visual studio,sur la ligne:
databasePath = “/UsersData/” + uid; une tile apparait sous le +
erreur plusieurs opérateurs “+” correspondent à ces opérandes :C/C++(350)
Comment remedier a cela?
Hi, Rui and Sara,,
nice tutorial you have here,, I already try this one: ESP32: Getting Started with Firebase (Realtime Database), and it works,, while writing this comment, I’m keep the ESP32 running and sent data to ESP32,, because I’m wondering how many counts it will store,, and I modify the delay time to 10 ms from that tutorial sketch (the original sketch you provide set the delay time 15 seconds),,
but for now, in this tutorial, I see you set the timerDelay to 3 minutes (180000 ms), it makes me wondering why we need to put that long,, will it affected something if I modify the timerDelay faster like below 1000 ms,,
Great Sara !
Thank you!
Thank you so much for such a great tutorial and effort put into it. We really appreciate your great effort.
Great!
Can I connect MQTT cloud(test.mosquitto.org) to realtime database in firebase? I tried to do so through node-red but it didn’t work.
Hi.
I don’t know.
I didn’t explore that subject. I found this that might help:
https://github.com/seblucas/mqtt2firebase
Regards,
Sara
Thanks Sara!!
what a great job bravo…
Thank you.
How to set firebase authentication dynamicly through web server or mobile app and save in memory of esp32 (EPROM) so no hard coded auth will need and easy for iot devices development
Hi.
you would need to create an access point with the ESP32 that would load a form where you would enter the user email and password.
Then, those credentials would be written permanently on the ESP32 memory (like SPIFFS, for example).
Then, to initialize Firebase, you would need to read from SPIFFS to get email and password.
You can implement something like this “Wi-Fi Manager” we implemented on the following project. But instead of SSID and password, you would insert email and password:
https://randomnerdtutorials.com/esp32-status-indicator-sensor-pcb/
Regards,
Sara
it would be helpfull if you make tutorial on that sir that how to set authentication dynamicaly. Thanx in Advance
Perfect tuturial but my program stands on “Getting User UID” following many dots.
Where have I tu put User UID in the sketch?
Thanks
Renzo
Hi.
Double-check that you’ve inserted all the credentials correctly, including project API key.
Regards,
Sara
Great example to use firebase, keep up the good work 👍
Hi Sara,
Great tutorial!
It looks the sensor readings are updated every 3 minutes in the firebase database.
Is the data also logged over time in the database?
So that you log the temperature over several weeks for example and export a tab delimited text file with all the sensor readings?
Best, Rob
Hi.
In this specific project no.
It overwrites the current values.
I’m already preparing a new tutorial that logs the data over time with timestamps.
So, you’ll have historical data saved.
Regards,
Sara
Dear Sara, I bought your books, thanks a lot.
Two simple questions:
1- Should be possible to connect to RTDB more than one device (board) ? I think so.
2- Can the different boards exchange data ?
Thanks.
Hi.
Yes. More than one board can connect to the database. Each board can be an independent user or be configured to be the same user.
Yes. The boards can exchange data because you can read and write to the database with both boards, and you can give permissions so that all boards access all data.
Regards,
Sara
Dear Sara:
thanks for your answer.
Can you please plan an example on how each board can be an independent user or be configured to be the same user and how the boards can exchange data between them ?
Regards,
Domenico
Hi.
They can be the same user if you login with each board with the same user email and password: https://randomnerdtutorials.com/esp32-esp8266-firebase-authentication/
They can be independent users if you login each board with a different user email and password, or if you set them as anonymous users.
To “exchange” data between the boards, each board will read from the database the data published by the other board. Learn more about read and write with this tutorial: https://randomnerdtutorials.com/esp32-firebase-realtime-database/
I hope this helps.
Regards,
Sara
Dear Sara,
Hi ! Great tutorial !
I’ve tried run the code on Arduino IDE but doesn’t work and show a message about wrong compilating for AI Thinker ESP32-CAM.
Why this happened ? Can I solve it ?
Best Regards,
Lucas
What is exactly the error?
Are you using an ESP32-CAM with this project?
Regards,
Sara
Hi Sara,
Thanks for answer.
Yes, I’m using an ESP32-CAM. The error is exacty the message below.
Arduino: 1.8.13 (Windows 10), Placa:”AI Thinker ESP32-CAM, 240MHz (WiFi/BT), QIO, 80MHz”
In file included from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:41:0,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Utils.h:37,from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/signer/Signer.h:37,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase.h:47,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:50,
from C:\Users\lucas\Documents\IoT\ESP32 CAM\Pluviógrafo\Firebase\Pluv_fb\Pluv_fb.ino:9:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:43:1: error: expected class-name before ‘{‘ token
{
^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h: In member function ‘int FB_WCS::_connect(const char*, uint16_t, long unsigned int)’:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:50:5: error: ‘_timeout’ was not declared in this scope
_timeout = timeout;^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:52:27: error: ‘connect’ was not declared in this scope
if (connect(host, port) == 0)^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:54:11: error: ‘_CA_cert’ was not declared in this scope
if (_CA_cert != NULL)^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:55:32: error: ‘sslclient’ was not declared in this scope
mbedtls_x509_crt_free(&sslclient->ca_cert);^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:55:50: error: ‘mbedtls_x509_crt_free’ was not declared in this scope
mbedtls_x509_crt_free(&sslclient->ca_cert);^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/wcs/esp32/FB_TCP_Client.h:58:5: error: ‘_connected’ was not declared in this scope
_connected = true;^
In file included from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Utils.h:37:0,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/signer/Signer.h:37,from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase.h:47,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:50,
from C:\Users\lucas\Documents\IoT\ESP32 CAM\Pluviógrafo\Firebase\Pluv_fb\Pluv_fb.ino:9:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h: At global scope:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:766:5: error: ‘mbedtls_pk_context’ does not name a type
mbedtls_pk_context *pk_ctx = nullptr;^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:767:5: error: ‘mbedtls_entropy_context’ does not name a type
mbedtls_entropy_context *entropy_ctx = nullptr;^
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/common.h:768:5: error: ‘mbedtls_ctr_drbg_context’ does not name a type
mbedtls_ctr_drbg_context *ctr_drbg_ctx = nullptr;^
In file included from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase.h:49:0,
from C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/Firebase_ESP_Client.h:50,from C:\Users\lucas\Documents\IoT\ESP32 CAM\Pluviógrafo\Firebase\Pluv_fb\Pluv_fb.ino:9:
C:\Users\lucas\Documents\Arduino\libraries\Firebase_Arduino_Client_Library_for_ESP8266_and_ESP32\src/session/FB_Session.h:347:3: error: ‘WiFiClientSecure’ does not name a type
WiFiClientSecure *getWiFiClient();
^
Foram encontradas múltiplas bibliotecas para “SD.h”
Usado: C:\Users\lucas\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.6\libraries\SD
Não usado: C:\Program Files (x86)\Arduino\libraries\SD
Foram encontradas múltiplas bibliotecas para “WiFi.h”
Usado: C:\Users\lucas\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.6\libraries\WiFi
Não usado: C:\Program Files (x86)\Arduino\libraries\WiFi
exit status 1
Erro compilando para a placa AI Thinker ESP32-CAM
Hi.
I never tried this library with the ESP32-CAM.
Did you try the example with a “normal” ESP32 first? Just to check if it is a problem with the library or with the board.
Regards,
Sara
Hi Sara, thank you for the great tutorial. Unfortunately the ESP32 have some troubles quite often. Can you help me resolve this problem? 🙂
The serial log is this:
Token info: type = id token, status = on request
Token info: type = id token, status = ready
Getting User UID
User UID: the user ID
FAILED
REASON: connection refused
Writing value: 25.02 on the following path: /UsersData/the user ID/humidity
PASSED
PATH: /UsersData/the user ID/humidity
TYPE: double
Writing value: 945.23 on the following path: /UsersData/the user ID/pressure
PASSED
PATH: /UsersData/the user ID/pressure
TYPE: double
Writing value: 25.97 on the following path: /UsersData/the user ID/temperature
PASSED
PATH: /UsersData/the user ID/temperature
TYPE: float
Writing value: 24.86 on the following path: /UsersData/the user ID/humidity
PASSED
PATH: /UsersData/the user ID/humidity
TYPE: float
Writing value: 945.20 on the following path: /UsersData/the user ID/pressure
PASSED
PATH: /UsersData/the user ID/pressure
TYPE: double
Writing value: 26.19 on the following path: /UsersData/the user ID/temperature
PASSED
PATH: /UsersData/the user ID/temperature
TYPE: float
FAILED
REASON: connection refused
FAILED
REASON: connection refused
FAILED
REASON: connection refused
FAILED
REASON: connection refused
Writing value: 945.23 on the following path: /UsersData/the user ID/pressure
PASSED
PATH: /UsersData/the user ID/pressure
TYPE: double
Writing value: 26.51 on the following path: /UsersData/the user ID/temperature
PASSED
PATH: /UsersData/the user ID/temperature
TYPE: float
Writing value: 24.27 on the following path: /UsersData/the user ID/humidity
PASSED
PATH: /UsersData/the user ID/humidity
TYPE: double
Writing value: 945.27 on the following path: /UsersData/the user ID/pressure
PASSED
PATH: /UsersData/the user ID/pressure
TYPE: double
FAILED
REASON: connection refused
Writing value: 24.26 on the following path: /UsersData/the user ID/humidity
PASSED
PATH: /UsersData/the user ID/humidity
TYPE: double
FAILED
REASON: connection refused
FAILED
REASON: connection refused
FAILED
REASON: connection refused
[E][ssl_client.cpp:36] _handle_error(): [start_ssl_client():216]: (-29312) SSL – The connection indicated an EOF
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -29312
FAILED
REASON: send request failed
And also sometimes:
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][WiFiGeneric.cpp:739] hostByName(): DNS Failed for securetoken.googleapis.com
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
[E][ssl_client.cpp:70] start_ssl_client(): ERROR opening socket
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -1
Token info: type = id token, status = error
Token error: code: -4, message: connection lost
Token info: type = id token, status = on request
Guru Meditation Error: Core 1 panic’ed (StoreProhibited). Exception was unhandled.
Core 1 register dump:
(…)
I haven’t done anything with the device or firebase and I haven’t rebooted.
Have a great day!
Hi.
Make sure your board has a good wi-fi connection.
Did you change anything on the code?
Try to increase the delay time between each reading sent to the database and check if that solves the problem.
Regards,
Sara
Hello,
I would like control my ESP8266 from the database. So, I use
Firebase.setString(“LED”, “OFF”);
and then, with Firebase.getString () function, I am trying to control an output.
But this library has no member named setString or getString.
Could you please how can I control -let say- a LED on ESP8266 from firebase?
Hi.
I already have that project created.
It will be published at the beginning of next month.
So, stay tuned.
Regards,
Sara
Dear Sara,
Thank you very much for your work. It is allways an inspiration.
Maybe you can help me to solve a problem I am fiddeling around since a couple of days and that meanwhile gave my nerves the rest.
Given is a well defined and static Firebase database (see at the end of this text).
At a random place in my code I want to update the value of a unique key. In this particular case, it is the string value of field time of sensor1 of board1.
It is assumed that the ESP32-boards do not change the database design. Without time series there is not only no necessity to do that, but furthermore also a common principle that clients must not do that.
I am using the Firebase_ESP_Client library from Suwatchai (Mobizt).
Code1:
#define TSTMP1 “/ESPWK1/board1/sensor1/timestamp”
Serial.printf(“Set timestamp… %s\n”, Firebase.RTDB.setTimestamp( & fbdo, TSTMP1) ? “ok” : fbdo.errorReason().c_str());
timestmp1 = fbdo.to < int > () + 7200;
Code2:
#define TIME1 “/ESPWK1/board1/sensor1/time”
char bufferarray[32] = “”;
sprintf(bufferarray,”%02d-%02d-%4d-%02d:%02d:%02d\n”, day(timestmp1), month(timestmp1), year(timestmp1), hour(timestmp1), minute(timestmp1), second(timestmp1));
json.set(“time”, bufferarray);
Serial.printf(“Set json… %s\n”, Firebase.RTDB.setJSON(&fbdo, TIME1, &json) ? “ok” : fbdo.errorReason().c_str());
The question is, which code snippet will access a certain defined existing node to put string data in its value field.
Start of project: Database definition as json object:
{
“ESPWK1”: {
“board1”: {
“boardname”: “Board1”,
“outputs”: {
“digital”: {
“do1”: 0,
“do2”: 0,
“do3”: 0,
“do4”: 0
},
“analog”: {
“ao1”: 0.000,
“ao2”: 0.000,
“ao3”: 0.000,
“ao4”: 0.000
},
“pwm1”: {
“f”: 0,
“dc”: 0
},
“pwm2”: {
“f”: 0,
“dc”: 0
}
},
“inputs”: {
“digital”: {
“di1”: 0,
“di2”: 0,
“di3”: 0,
“di4”: 0
},
“analog”: {
“ai1”: 0.000,
“ai2”: 0.000,
“ai3”: 0.000,
“ai4”: 0.000
}
},
“sensor1”: {
“sensorname”: “Sensor1”,
“timestamp”: 0,
“time”: “”,
“sens1”: -99.000,
“sens2”: -99.000,
“sens3”: -99.000,
“sens4”: -99.000
},
“sensor2”: {
“sensorname”: “Sensor2”,
“timestamp”: 0,
“time”: “”,
“sens1”: -99.000,
“sens2”: -99.000,
“sens3”: -99.000,
“sens4”: -99.000
},
“sensor3”: {
“sensorname”: “Sensor3”,
“timestamp”: 0,
“time”: “”,
“sens1”: -99.000,
“sens2”: -99.000,
“sens3”: -99.000,
“sens4”: -99.000
}
},
“board2”: {
“boardname”: “Board2”,
“outputs”: {
…
(in total there are 4 boards with identical structure)
}
End of database definition.
Hi.
I’m not sure that I understood your question.
To save a string on a specific database path:
Firebase.RTDB.setString(&fbdo, “databasepath/node”, YOUR_STRING)
Also check the documentation: https://github.com/mobizt/Firebase-ESP-Client#store-data
I hope this helps.
Regards,
Sara
Dear Sara,
thank you, I will try it today.
To do the same, how would you code it using json functions?
Best regards
Hi.
You can do it the same way you pass a string.
Just make sure your json object is converted to a string before sending it.
Or you can use the setJson function instead of setString.
Regards,
Sara
Hello. Thank you for the work. What are the codes to be used in the rules section of the database?
Hi.
Please read section 5) 5) Set up Database Security Rules
Hello, almost everything is ready. There is an error in the monitor at the end.
Connecting to WiFi …192.168.116.190
Token info: type = id token (GITKit token), status = on request
Token info: type = id token (GITKit token), status = error
Token error: code: -4, message: connection lost
Getting User UID………
Can you help?
Everything has been decided. This is a bad internet.
Hello,
I’m trying to combine this code with the GPIO control code, but it doesn’t work when combining them.
I set different FirebaseJson for reading and writing and it didn’t work either.
The reading of the sensors works, but the control of the outputs does not work.
The terminal shows me:
stream timeout, resuming…
do you know what could be the error?
Thank you very much
Dear Sara
I have followed your tutorial and added the HX711 module to my project. However, I am facing some issues and I would like to save data to the database only when the weight exceeds 100 grams. Can you guide me on how to do this? Thank you.
sous PlatforIO, avec visual studio,sur la ligne:
databasePath = “/UsersData/” + uid; une tile apparait sous le +
erreur plusieurs opérateurs “+” correspondent à ces opérandes :C/C++(350)
Comment remedier a cela?
Merci.
Hi, Rui and Sara,,
nice tutorial you have here,, I already try this one: ESP32: Getting Started with Firebase (Realtime Database), and it works,, while writing this comment, I’m keep the ESP32 running and sent data to ESP32,, because I’m wondering how many counts it will store,, and I modify the delay time to 10 ms from that tutorial sketch (the original sketch you provide set the delay time 15 seconds),,
but for now, in this tutorial, I see you set the timerDelay to 3 minutes (180000 ms), it makes me wondering why we need to put that long,, will it affected something if I modify the timerDelay faster like below 1000 ms,,