Bonjour à tous, une nouvelle fois …
J’essaie en ce moment d’envoyer mes données (DHT22) sur le serveur Firebase.
Grâce à ce tuto : ESP32 Data Logging to Firebase Realtime Database | Random Nerd Tutorials
J’ai modifié le code pour remplacer cette sonde BME280 par la DHT22. Je passe par l’IDE Arduino
Et bien sûr il y a quelques coquilles que je ne trouve pas …
- Sur la page firebase les données ne s’accumule pas (en plus d’une légère différence de valeur par rapport au moniteur Arduino)
- L’horodatage n’a pas l’air de fonctionner
Ma page Firebase
Le moniteur IDE Arduino :
Voici le code de base du tuto :
#include <Arduino.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include "time.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;
// Database main path (to be updated in setup with the user UID)
String databasePath;
// Database child nodes
String tempPath = "/temperature";
String humPath = "/humidity";
String presPath = "/pressure";
String timePath = "/timestamp";
// Parent Node (to be updated in every loop)
String parentPath;
int timestamp;
FirebaseJson json;
const char* ntpServer = "pool.ntp.org";
// 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();
}
// Function that gets current epoch time
unsigned long getTime() {
time_t now;
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
//Serial.println("Failed to obtain time");
return(0);
}
time(&now);
return now;
}
void setup(){
Serial.begin(115200);
// Initialize BME280 sensor
initBME();
initWiFi();
configTime(0, 0, ntpServer);
// 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 + "/readings";
}
void loop(){
// Send new readings to database
if (Firebase.ready() && (millis() - sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
sendDataPrevMillis = millis();
//Get current timestamp
timestamp = getTime();
Serial.print ("time: ");
Serial.println (timestamp);
parentPath= databasePath + "/" + String(timestamp);
json.set(tempPath.c_str(), String(bme.readTemperature()));
json.set(humPath.c_str(), String(bme.readHumidity()));
json.set(presPath.c_str(), String(bme.readPressure()/100.0F));
json.set(timePath, String(timestamp));
Serial.printf("Set json... %s\n", Firebase.RTDB.setJSON(&fbdo, parentPath.c_str(), &json) ? "ok" : fbdo.errorReason().c_str());
}
}
Mon code modifié :
#include <Arduino.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include "time.h"
#include "DHT.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"
// Définition Pin DHT22
#define DHTPIN 2
#define DHTTYPE DHT22
// Déclaration DHT22
DHT dht(DHTPIN, DHTTYPE);
// Insert your network credentials
#define WIFI_SSID "*******"
#define WIFI_PASSWORD "*******"
// Insert Firebase project API Key
#define API_KEY "*******"
// Insert Authorized Email and Corresponding Password
#define USER_EMAIL "*******"
#define USER_PASSWORD "*******"
// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL "*******"
// Define Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
// Variable to save USER UID
String uid;
// Database main path (to be updated in setup with the user UID)
String databasePath;
// Database child nodes
String tempPath = "/temperature";
String humPath = "/humidity";
String timePath = "/timestamp";
// Parent Node (to be updated in every loop)
String parentPath;
int timestamp;
FirebaseJson json;
const char* ntpServer = "pool.ntp.org";
float temperature;
float humidity;
// Timer variables (send new readings every three minutes)
unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 180000;
// 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();
}
// Function that gets current epoch time
unsigned long getTime() {
time_t now;
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
//Serial.println("Failed to obtain time");
return(0);
}
time(&now);
return now;
}
void setup(){
Serial.begin(115200);
// Serial.println(F("DHTxx test!"));
// Initialise le DHT22 & Wifi & Time
dht.begin();
initWiFi();
configTime(0, 0, ntpServer);
// 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 + "/readings";
}
void loop(){
// Temps entre chaques mesures
delay(180000);
// La lecture de la température ou de l'humidité prend environ 250 millisecondes !
// Les lectures du capteur peuvent également être "anciennes" jusqu'à 2 secondes (c'est un capteur très lent)
float h = dht.readHumidity();
float t = dht.readTemperature();
// Vérifiez si des lectures ont échoué et quittez plus tôt (pour réessayer).
if (isnan(h) || isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Send new readings to database
if (Firebase.ready() && (millis() - sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
sendDataPrevMillis = millis();
//Get current timestamp
timestamp = getTime();
Serial.print ("time: ");
Serial.println (timestamp);
parentPath= databasePath + "/" + String(timestamp);
json.set(tempPath.c_str(), String(dht.readTemperature()));
json.set(humPath.c_str(), String(dht.readHumidity()));
json.set(timePath, String(timestamp));
Serial.printf("Set json... %s\n", Firebase.RTDB.setJSON(&fbdo, parentPath.c_str(), &json) ? "ok" : fbdo.errorReason().c_str());
}
// Calculer l'indice de chaleur en Fahrenheit (valeur par défaut)
// float hif = dht.computeHeatIndex(f, h);
// Calculer l'indice de chaleur en degrés Celsius (isFahreheit = false)
// float hic = dht.computeHeatIndex(t, h, false);
// Ecriture dans le moniteur
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
// Serial.print(f);
// Serial.print(F("°F Heat index: "));
// Serial.print(hic);
// Serial.print(F("°C "));
// Serial.print(hif);
// Serial.println(F("°F"));
}
Je pense que cela vient de l'horodatage ...
Vous voyez le loup ?
MODIFICATION :
Est possible que certaine carte ne puisse pas faire d'horodatage ? Car je viens d'essayer un code pour comprendre l'horodatage sur mon ESP CAM 32 mais cela ne s'acremente pas
https://randomnerdtutorials.com/epoch-unix-time-esp32-arduino/