2021年11月28日 星期日

ESP32 Firebase: Send BMP280 Sensor Readings to the Realtime Database

ESP32  Firebase: Send BMP280 Sensor Readings to the Realtime Database 






























#include <Arduino.h>
//defined(ESP32)
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include < #include <Arduino.h>
// Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>
#define BMP280_I2C_ADDRESS  0x76
// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"
// Insert your network credentials
#define WIFI_SSID "TOTOLINK_A3002MU"
#define WIFI_PASSWORD "260631173"
// Insert Firebase project API Key
#define API_KEY "AIzaSyAWFC5NEz416YntHGDF7_iLCMY18EyTxmo"
// Insert Authorized Email and Corresponding Password
#define USER_EMAIL "alex9ufo@gmail.com"
#define USER_PASSWORD " 9981"
// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL "https://esp-firebase-demo-7fef8-default-rtdb.firebaseio.com"
// Define Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
// Variable to save USER UID
String uid;
// Variables to save database paths
String databasePath;
String tempPath;
String altPath;
String prePath;
// BMP280 sensor
Adafruit_BMP280 bme; // I2C
float temperature;
float pressure;
float altitude;
// Timer variables (send new readings every three minutes)
unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 180000;
// Initialize BMP280
void initBMP(){
  if (!bme.begin(BMP280_I2C_ADDRESS)) {
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
    while (1);
  }
}
// Initialize WiFi
void initWiFi() {
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
  Serial.println();
}
// Write float values to the database
void sendFloat(String path, float value){
  if (Firebase.RTDB.setFloat(&fbdo, path.c_str(), value)){
    Serial.print("Writing value: ");
    Serial.print (value);
    Serial.print(" on the following path: ");
    Serial.println(path);
    Serial.println("PASSED");
    Serial.println("PATH: " + fbdo.dataPath());
    Serial.println("TYPE: " + fbdo.dataType());
  }
  else {
    Serial.println("FAILED");
    Serial.println("REASON: " + fbdo.errorReason());
  }
}
void setup(){
  Serial.begin(115200);
  Serial.println("ESP32 Firebase: Send BMP280 Sensor Readings to the Realtime Database");
  // Initialize BMP280 sensor
  initBMP();
  initWiFi();
  // Assign the api key (required)
  config.api_key = API_KEY;
  // Assign the user sign in credentials
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;
  // Assign the RTDB URL (required)
  config.database_url = DATABASE_URL;
  Firebase.reconnectWiFi(true);
  fbdo.setResponseSize(4096);
  // Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h
  // Assign the maximum retry of token generation
  config.max_token_generation_retry = 5;
  // Initialize the library with the Firebase authen and config
  Firebase.begin(&config, &auth);
  // Getting the user UID might take a few seconds
  Serial.println("Getting User UID");
  while ((auth.token.uid) == "") {
    Serial.print('.');
    delay(1000);
  }
  // Print user UID
  uid = auth.token.uid.c_str();
  Serial.print("User UID: ");
  Serial.println(uid);
  // Update database path
  databasePath = "/UsersData/" + uid;
  // Update database path for sensor readings
  tempPath = databasePath + "/temperature"; // --> UsersData/<user_uid>/temperature
  prePath = databasePath + "/Pressure"; // --> UsersData/<user_uid>/Pressure
  altPath = databasePath + "/Altitude"; // --> UsersData/<user_uid>/altitude
}
void loop(){
  // Send new readings to database
  if (Firebase.ready() && (millis() - sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
    sendDataPrevMillis = millis();
    // Get latest sensor readings
    temperature = bme.readTemperature(); // get temperature
    pressure = bme.readPressure();     // get pressure
    altitude = bme.readAltitude(1013.25); // get altitude (this should be adjusted to your local forecast)
    //1013.15需修正
    //該1013.25值應為數百Pa處的海平面局部壓力。
    //如果要顯示高於地面的高度,則需要知道該位置,並編寫代碼以計算高度偏移。
    //海平面:泛指我們所處的高度,即1大氣壓(1atm或1013.25hPa 或 1013.25mb)
    //That 1013.25 value should be the local pressure at sea level in hundreds of Pa. 
    // Send readings to database:
    
    sendFloat(tempPath, temperature);
    sendFloat(prePath, pressure);
    sendFloat(altPath, altitude);
  }
  
}



參考來源

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.

ESP32 ESP8266 NodeMCU Firebase Send BME280 Sensor Readings to the Realtime Database

Other Firebase Tutorials with the ESP32/ESP8266 that you might be interested in:

What is Firebase?

Firebase logo

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 authenticationrealtime databasehosting, etc.

Project Overview

The following diagram shows a high-level overview of the project we’ll build.

Firebase ESP32 ESP8266 NodeMCU Project Overview
  1. The ESP32/ESP8266 authenticates as a user with email and password (that user must be set on the Firebase authentication methods);
  2. After authentication, the ESP gets the user UID;
  3. 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;
  4. The ESP sends temperature, humidity and pressure to the database.

These are the main steps to complete this project:

  1. Create Firebase Project
  2. Set Authentication Methods
  3. Get Project API Key
  4. Set up Realtime Database
  5. Set up Database Security Rules
  6. ESP32/ESP8266 Send Sensor Readings to the Realtime Database

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:

If you want to program the ESP boards using VS Code with the PlatformIO extension, follow the following tutorial instead:

1) Create Firebase Project

1) Go to Firebase and sign in using a Google Account.

2) Click Get Started and then Add project to create a new project.

3) Give a name to your project, for example ESP Firebase Demo.

Create Firebase Project name

4) Disable the option Enable Google Analytics for this project as it is not needed and click Create project.

Set Up Firebase Project for ESP32 and ESP8266 Step 2

5) It will take a few seconds to set up your project. Then, click Continue when it’s ready.

6) 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.

1) On the left sidebar, click on Authentication and then on Get started.

Firebase Project Authentication

2) Select the Option Email/Password.

Selecting Firebase Authentication with Email/Password

3) Enable that authentication method and click Save.

Enable Email/password authentication Firebase

4) The authentication with email and password should now be enabled.

Firebase Authentication with Email/Password enabled

5) Now, you need to add a user. On the Authentication tab, select the Users tab at the top. Then, click on Add User.

Firebase Authentication Add New User

6) Add an email address for the authorized user. It can be your google account email or any other email. You can also create an email for this specific project. Add a password that will allow you to sign in to your app and access the database. Don’t forget to save the password in a safe place because you’ll need it later. When you’re done, click Add user.

Firebase Authentication Add User with Email and Password

7) A new user was successfully created and added to the Users table.

Firebase Users Table

Notice that 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’s also a column that registers the date of the last sign-in. At the moment, it is empty because we haven’t signed in with that user yet.

3) Get Project API Key

To interface with your Firebase project using the ESP32 or ESP8266 boards, you need to get your project API key. Follow the next steps to get your project API key.

1) On the left sidebar, click on Project Settings.

Firebase Project Settings

2) Copy the Web API Key to a safe place because you’ll need it later.

Firebase Project Settings Web API Key

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.

Firebase Project Create Realtime Database

2) Select your database location. It should be the closest to your location.

Set up realtime database firebase ESP32 ESP8266 Select 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.

Set up realtime database firebase ESP32 ESP8266 Set Security Rules

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.

Firebase Project Database URL

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"
      }
    }
  }
}
Realtime Database creating rules

These rules grant access to a node matching the authenticated user’s UID. This grants that each authenticated user can only access its own data. This means the user can only access the nodes that are under a node with its corresponding user UID. If there are other data published on the database, not under a node with the users’ UID, that user can’t access that data.

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:

  1. Authenticate as a user with email and password (the user you set up in this section);
  2. Send sensor readings to the realtime database as an authorized user.

Parts Required

For this project, you need the following parts*:

* 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.

ESP32 BME280 Sensor Temperature Humidity Pressure Wiring Diagram Circuit

Not familiar with the BME280 with the ESP32? Read this tutorial: ESP32 with BME280 Sensor using Arduino IDE (Pressure, Temperature, Humidity).

ESP8266 with BME280

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.

ESP8266 NodeMCU BME280 Sensor Temperature Humidity Pressure Wiring Diagram Circuit

Not familiar with the BME280 with the ESP8266? Read this tutorial: ESP8266 with BME280 using Arduino IDE (Pressure, Temperature, Humidity).

Installing Libraries

For this project, you need to install the following libraries:

Installing Libraries – VS Code

Follow the next instructions if you’re using VS Code with the PlatformIO extension.

Install the Firebase-ESP-Client Library

There is a library with lots of examples to use Firebase with the ESP32: the Firebase-ESP-Client library. This library is compatible with both the ESP32 and ESP8266 boards.

Click on the PIO Home icon and select the Libraries tab. Search for “Firebase ESP Client“. Select the Firebase Arduino Client Library for ESP8266 and ESP32.

Install Firebase ESP Client Library VS Code

Then, click Add to Project and select the project you’re working on.

Add Firebase ESP Client Library to Project VS Code

Install the BME280 Library

In the Libraries tab, search for BME280. Select the Adafruit BME280 library.

PlatformIO VS Code Search for BME280 Library

Then, click Add to Project and select the project you’re working on.

PlatformIO with VS Code Add Library to Project

Also, change the monitor speed to 115200 by adding the following line to the platformio.ini file of your project:

monitor_speed = 115200

Installation – Arduino IDE

Follow this section if you’re using Arduino IDE.

You need to install the following libraries:

Go to Sketch Include Library > Manage Libraries, search for the libraries’ names and install the libraries.

For the Firebase Client library, select the Firebase Arduino Client Library for ESP8266 and ESP32.

Install Firebase Arduino Client Library for ESP8266 and ESP32 by Mobitz

Now, you’re all set to start programming the ESP32 and ESP8266 boards to interact with the database.

Send Sensor Readings to the Realtime Database Code

Copy the following code to your Arduino IDE or to the main.cpp file if you’re using VS Code.

You need to insert your network credentials, project API key, database URL, and the authorized user email and password.

/*
  Rui Santos
  Complete project details at our blog: https://RandomNerdTutorials.com/esp32-esp8266-firebase-bme280-rtdb/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Insert your network credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

// Insert Firebase project API Key
#define API_KEY "REPLACE_WITH_YOUR_PROJECT_API_KEY"

// Insert Authorized Email and Corresponding Password
#define USER_EMAIL "REPLACE_WITH_THE_USER_EMAIL"
#define USER_PASSWORD "REPLACE_WITH_THE_USER_PASSWORD"

// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL "REPLACE_WITH_YOUR_DATABASE_URL"

// Define Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

// Variable to save USER UID
String uid;

// Variables to save database paths
String databasePath;
String tempPath;
String humPath;
String presPath;

// BME280 sensor
Adafruit_BME280 bme; // I2C
float temperature;
float humidity;
float pressure;

// Timer variables (send new readings every three minutes)
unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 180000;

// Initialize BME280
void initBME(){
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
}

// Initialize WiFi
void initWiFi() {
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
  Serial.println();
}

// Write float values to the database
void sendFloat(String path, float value){
  if (Firebase.RTDB.setFloat(&fbdo, path.c_str(), value)){
    Serial.print("Writing value: ");
    Serial.print (value);
    Serial.print(" on the following path: ");
    Serial.println(path);
    Serial.println("PASSED");
    Serial.println("PATH: " + fbdo.dataPath());
    Serial.println("TYPE: " + fbdo.dataType());
  }
  else {
    Serial.println("FAILED");
    Serial.println("REASON: " + fbdo.errorReason());
  }
}

void setup(){
  Serial.begin(115200);

  // Initialize BME280 sensor
  initBME();
  initWiFi();

  // Assign the api key (required)
  config.api_key = API_KEY;

  // Assign the user sign in credentials
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  // Assign the RTDB URL (required)
  config.database_url = DATABASE_URL;

  Firebase.reconnectWiFi(true);
  fbdo.setResponseSize(4096);

  // Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

  // Assign the maximum retry of token generation
  config.max_token_generation_retry = 5;

  // Initialize the library with the Firebase authen and config
  Firebase.begin(&config, &auth);

  // Getting the user UID might take a few seconds
  Serial.println("Getting User UID");
  while ((auth.token.uid) == "") {
    Serial.print('.');
    delay(1000);
  }
  // Print user UID
  uid = auth.token.uid.c_str();
  Serial.print("User UID: ");
  Serial.println(uid);

  // Update database path
  databasePath = "/UsersData/" + uid;

  // Update database path for sensor readings
  tempPath = databasePath + "/temperature"; // --> UsersData/<user_uid>/temperature
  humPath = databasePath + "/humidity"; // --> UsersData/<user_uid>/humidity
  presPath = databasePath + "/pressure"; // --> UsersData/<user_uid>/pressure
}

void loop(){
  // Send new readings to database
  if (Firebase.ready() && (millis() - sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
    sendDataPrevMillis = millis();

    // Get latest sensor readings
    temperature = bme.readTemperature();
    humidity = bme.readHumidity();
    pressure = bme.readPressure()/100.0F;

    // Send readings to database:
    sendFloat(tempPath, temperature);
    sendFloat(humPath, humidity);
    sendFloat(presPath, pressure);
  }
}

View raw code

How the Code Works

Continue reading to learn how the code works or skip to the demonstration section.

Include Libraries

First, include the required libraries. The WiFi.h library to connect the ESP32 to the internet (or the ESP8266WiFi.h library for the ESP8266 board), the Firebase_ESP_Client.h  library to interface the boards with Firebase, and the WireAdafruit_Sensor, and Adafruit_BME280 to interface with the BME280 sensor.

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

You also need to include the following for the Firebase library to work.

// Provide the token generation process info.
#include "addons/TokenHelper.h"
// Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

Network Credentials

Include your network credentials in the following lines so that your boards can connect to the internet using your local network.

// Insert your network credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

Firebase Project API Key, Firebase User, and Database URL

Insert your Firebase project API key—the one you’ve gotten in this section.

#define API_KEY "REPLACE_WITH_YOUR_PROJECT_API_KEY"

Insert the authorized email and the corresponding password—these are the details of the user you’ve added in this section.

// Insert Authorized Email and Corresponding Password
#define USER_EMAIL "REPLACE_WITH_THE_USER_EMAIL"
#define USER_PASSWORD "REPLACE_WITH_THE_USER_PASSWORD"

Insert your database URL in the following line:

// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL "REPLACE_WITH_YOUR_DATABASE_URL"

Firebase Objects and Other Variables

The following line defines a FirebaseData object.

FirebaseData fbdo;

The next line defines a FirebaseAuth object needed for authentication.

FirebaseAuth auth;

Finally, the following line defines a FirebaseConfig object required for configuration data.

FirebaseConfig config;

The uid variable will be used to save the user’s UID. We can get the user’s UID after the authentication.

String uid;

The following variables will be used to save the nodes to where we’ll send the sensor readings. 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;

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.

float temperature;
float humidity;
float pressure;

Delay Time

The sendDataPrevMillis and timerDelay variables are used to check the delay time between each send. In this example, we’re setting the delay time to 3 minutes (18000 milliseconds). Once you test this project and check that everything is working as expected, we recommend increasing the delay.

// Timer variables (send new readings every three minutes)
unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 180000;

initBME()

The initBME() function initializes the BME280 library using the bme object created previously. Then, you should call this library in the setup().

void initBME(){
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
}

initWiFi()

The initWiFi() function connects your ESP to the internet using the network credentials provided. You must call this function later in the setup() to initialize WiFi.

// Initialize WiFi
void initWiFi() {
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
  Serial.println();
}

Send Data to the Database

To store data at a specific node in the Firebase Realtime Database, you can use the following functions: setsetIntsetFloatsetDoublesetStringsetJSONsetArraysetBlob, and setFile.

These functions return a boolean value indicating the success of the operation, which will be true if all of the following conditions are met:

  • The server returns HTTP status code 200
  • The data types matched between request and response

Only setBlob and setFile functions that make a silent request to Firebase server, thus no payload response returned.

Learn more: ESP32: Getting Started with Firebase (Realtime Database)

In our example, we’ll send float variables, so we need to use the setFloat() function as follows.

Firebase.RTDB.setFloat(&fbdo, "DATABASE_NODE", VALUE)

The second argument refers to the database node (char variable) to which we want to send the data. The third argument is the data we want to send (float variable).

As we’ll need to send three float values, we created a function—the sendFloat() function that accepts the node path and the value as arguments.

// Write float values to the database
void sendFloat(String path, float value){
  if (Firebase.RTDB.setFloat(&fbdo, path.c_str(), value)){
    Serial.print("Writing value: ");
    Serial.print (value);
    Serial.print(" on the following path: ");
    Serial.println(path);
    Serial.println("PASSED");
    Serial.println("PATH: " + fbdo.dataPath());
    Serial.println("TYPE: " + fbdo.dataType());
  }
  else {
    Serial.println("FAILED");
    Serial.println("REASON: " + fbdo.errorReason());
  }
}

Later, we’ll call that function in the loop() to send sensor readings.

setup()

In setup(), initialize the Serial Monitor for debugging purposes at a baud rate of 115200.

Serial.begin(115200);

Call the initBME() function to initialize the BME280 sensor.

initBME();

Call the initWiFi() function to initialize WiFi.

initWiFi();

Assign the API key to the Firebase configuration.

config.api_key = API_KEY;

The following lines assign the email and password to the Firebase authentication object.

auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;

Assign the database URL to the Firebase configuration object.

config.database_url = DATABASE_URL;

Add the following to the configuration object.

// Assign the callback function for the long running token generation task
config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

// Assign the maximum retry of token generation
config.max_token_generation_retry = 5;

Initialize the Firebase library (authenticate) with the configuration and authentication settings we defined earlier.

// Initialize the library with the Firebase authen and config
Firebase.begin(&config, &auth);

After initializing the library, we can get the user UID by calling auth.token.uid. Getting the user’s UID might take some time, so we add a while loop that waits until we get it.

// Getting the user UID might take a few seconds
Serial.println("Getting User UID");
while ((auth.token.uid) == "") {
  Serial.print('.');
  delay(1000);
}

Finally, we save the user’s UID in the uid variable and print it in the Serial Monitor.

uid = auth.token.uid.c_str();
Serial.print("User UID: ");
Serial.print(uid);

After getting the user UID, we can update the database node paths to include the user UID. That’s what we do in the following lines.

// Update database path for sensor readings
tempPath = databasePath + "/temperature"; // --> UsersData/<user_uid>/temperature
humPath = databasePath + "/humidity"; // --> UsersData/<user_uid>/humidity
presPath = databasePath + "/pressure"; // --> UsersData/<user_uid>/pressure

loop()

In the loop(), check if it is time to send new readings:

if (Firebase.ready() && (millis() - sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
  sendDataPrevMillis = millis();

If it is, get the latest sensor readings from the BME280 sensor and save them on the temperaturehumidity, and pressure variables.

// Get latest sensor readings
temperature = bme.readTemperature();
humidity = bme.readHumidity();
pressure = bme.readPressure()/100.0F;

Finally, call the sendFloat() function to send the new readings to the database. Pass as arguments the node path and the value.

// Send readings to database:
sendFloat(tempPath, temperature);
sendFloat(humPath, humidity);
sendFloat(presPath, pressure);

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.

Arduino IDE Serial Monitor Demonstration

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 own user UID—this is a way to restrict access to the database.

Arduino IDE Serial Monitor Demonstration

And that’s it. You’ve successfully sent sensor readings to the Firebase Realtime Database, and you protected the data using database rules.

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...