▷ Practice 24: Firebase

 ⭐⭐⭐⭐⭐ Practice 24: Firebase

General objective:

  • Sense data and upload it to Firebase Realtime Database.

Materials:

  • Firebase
  • TSC-Lab


Introduction:

Firebase is a platform for the development of web and mobile applications, launched in 2011 and acquired by Google in 2014. It is a cloud-based platform, integrated with Google Cloud Platform, which utilizes a set of tools for the creation and synchronization of projects aimed at delivering high-quality applications. This enables the growth of the user base and also facilitates greater monetization.

In this current project, the aim is to utilize the Realtime Database, a cloud-hosted NoSQL database that allows you to store and synchronize data among your users in real-time. To achieve this, temperature data will be sensed and uploaded along with the PWM (pulse-width modulation) of the heater. These data points will be sorted by date and time.

Steps:

Note: You must be logged in to your Google account. It is assumed that you have installed the libraries from previous practices, and additionally, you need to install the Firebase Arduino Client for ESP8266 and ESP32 library, version 2.3.7 (this version is recommended to avoid potential issues).


The steps to carry out this practical are the following:
  1. Go to Firebase (google.com) and at the top right select Go to console.

  2. If this is the first time you are using Firebase, a screen like the following will appear, and you must select "Create a project." 

  3. Give the project a name, accept the conditions, confirm the use of Firebase and click "Continue".

  4. Enable Google Analytics and click "Continue".

  5. Configure Google Analytics, select Ecuador as the location, accept the conditions and click "Create project".

  6. The project will be created and a screen like the one shown below will appear and click "Continue".

  7. On the left side of the screen, click on Compilation, several options will be displayed and click on "Realtime Database". 

  8. Click on "Create a database".

  9. Choose United States as location and click "Next".

  10. For this occasion select "Start in test mode" and click "Enable".

  11. Create an authentication method.

  12. Click "start".

  13. Select "Anonymous".

  14. Habilitar el switch y guardar.

  15. Copy the following code to the Arduino IDE, but do not upload it to TSC-Lab yet.  
#include <WiFi.h>
#include <Firebase_ESP_Client.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 "your_ssid"
#define WIFI_PASSWORD "your_password"
// Insert Firebase project API Key
#define API_KEY "your_apikey"
// Insert RTDB URLefine the RTDB URL */
#define DATABASE_URL "your_rtdb_url"
//Define Firebase Data object
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
unsigned long sendDataPrevMillis = 0;
int count = 0;
bool signupOK = false;
String path = "TSC-Lab";
String temp_fb;
String pwm_fb;
//temperatura sensor
#include <OneWire.h>
#include <DallasTemperature.h>
//GPIO pin 4 is set as OneWire bus
OneWire ourWire1(4);
//A variable or object is declared for our sensor 1
DallasTemperature sensors1(&ourWire1);
//pins of transistor
int trans1 = 17;
//temperature var
float temp1;
int dutyCycle1 = 255;
// Setting PWM properties
const int freq = 30000;
const int pwmChannell = 0;
const int resolution = 8;
//time and date
#include "time.h"
const char* ntpServer = "pool.ntp.org";
unsigned long epochTime;
struct tm timeinfo;
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
//Hora
configTime(-18000, 0, ntpServer);
//Debe configurarse por primera vez la hora para empezar
if(!getLocalTime(&timeinfo)){
Serial.print("No hay acceso a Internet en la red: ");
Serial.println(WIFI_SSID);
Serial.println("No se puede obtener la hora actual. Revise el WiFi");
while(!getLocalTime(&timeinfo));
}
/* Assign the api key (required) */
config.api_key = API_KEY;
/* Assign the RTDB URL (required) */
config.database_url = DATABASE_URL;
/* Sign up */
if (Firebase.signUp(&config, &auth, "", "")) {
Serial.println("ok");
signupOK = true;
}
else {
Serial.printf("%s\n", config.signer.signupError.message.c_str());
}
/* Assign the callback function for the long running token generation task */
config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h
Firebase.begin(&config, &auth);
Firebase.reconnectWiFi(true);
//sensor
sensors1.begin(); //Sensor 1 starts
// configure LED PWM functionalitites
ledcSetup(pwmChannell, freq, resolution);
// attach the channel to the GPIO to be controlled
ledcAttachPin(trans1, pwmChannell);
ledcWrite(pwmChannell, dutyCycle1);
//hora
}
void loop() {
readData();
epochTime = getEpoch(); //fecha en formato UNIX/EPOCH
writeFirebase();
}
void writeFirebase() {
if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 1000 || sendDataPrevMillis == 0)) {
sendDataPrevMillis = millis();
temp_fb = path + "/" + epochTime + "/temperature/";
// Write temperature
if (Firebase.RTDB.setFloat(&fbdo, temp_fb.c_str(), temp1)) {
Serial.println("PASSED");
Serial.println("PATH: " + fbdo.dataPath());
Serial.println("TYPE: " + fbdo.dataType());
}
else {
Serial.println("FAILED");
Serial.println("REASON: " + fbdo.errorReason());
}
pwm_fb = path + "/" + epochTime + "/pwm/";
// Write pwm
if (Firebase.RTDB.setInt(&fbdo, pwm_fb.c_str(), dutyCycle1)) {
Serial.println("PASSED");
Serial.println("PATH: " + fbdo.dataPath());
Serial.println("TYPE: " + fbdo.dataType());
}
else {
Serial.println("FAILED");
Serial.println("REASON: " + fbdo.errorReason());
}
}
}
void readData() {
//The command is sent to read the temperature
sensors1.requestTemperatures();
//Obtain the temperature in ºC of sensor 1
temp1 = sensors1.getTempCByIndex(0);
}
unsigned long getEpoch() {
time_t now;
if (!getLocalTime(&timeinfo)) {
return(0);
}
time(&now);
return now;
}
view raw Practice41.ino hosted with ❤ by GitHub
    
  1. Copy the URL of the project and paste it on line 20 of the code (FIREBASE_HOST variable) previously copied.

  2. On the left side of the screen, click here:

  3. Click on "Project Settings".

  4. Copy the WEB API key and paste it into the API_KEY variable.

  5. Change the WiFi credentials and upload the code to the TSC-Lab.
  6. Once the code is uploaded, in the Realtime Database section you can view the data upload.

                  

Comentarios

Popular Posts

▷ Especificaciones del módulo ESP32

▷ #ESP32 - REAL-TIME CLOCK #RTC INTERNO

▷ #ESP32 - SINCRONIZAR RTC INTERNO CON SERVIDOR NTP

▷ #ESP32 - Display OLED 128x64

▷ Sensor networks for agriculture based on #FPGA

▷ #ESP32 - INSTALAR LIBRERIAS DESDE GESTOR LIBRERIAS ARDUINO

▷ #ESP32 - Over-The-Air programming #OTA

▷ IoT-Based Shrimp Pool Optimization with LoRa Technology

▷ SISTEMAS EMBEBIDOS, PROYECTOS PROPUESTOS (2021 PAO1)

▷ Instalación de ALTIUM CircuitMaker y especificaciones del módulo ESP32