Hi, Need help.
When I uploaded the code and compiled it successfully. The sensor data are not updated to the firebase. I can see all JSON data in the serial monitor. The updates from “digital, message, and pvm are updated n the serial monitor. I’m using DHT11 and made the necessary changes in the code for that particular sensor. Please help. Thanks
DHT 11 code
#include <Arduino.h>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <DHT.h> // Add DHT library
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// DHT11 sensor
#define DHTPIN 4 // Define the pin where the DHT sensor is connected
#define DHTTYPE DHT11 // Define the DHT sensor type
DHT dht(DHTPIN, DHTTYPE);
float temperature;
float humidity;
void setup(){
Serial.begin(115200);
// Init DHT sensor, OLED, and WiFi
initOLED();
initWiFi();
// Initialize DHT sensor
dht.begin();
void loop(){
// Get latest sensor readings from DHT sensor
temperature = dht.readTemperature();
humidity = dht.readHumidity();
Serial Monitor
0, Type: object, Name: digital, Value: {"2":0,"12":20}
1, Type: object, Name: 2, Value: 0
2, Type: object, Name: 12, Value: 20
3, Type: object, Name: message, Value: "its working"
4, Type: object, Name: pwm, Value: {"13":0,"14":0}
5, Type: object, Name: 13, Value: 0
6, Type: object, Name: 14, Value: 0
Received stream payload size: 112 (Max. 112)
FAILED
REASON: Invalid data; couldn't parse JSON object, array, or value.
Great.
I’m glad everything is working as expected.
Unfortunately, we don’t have any tutorials about Flutter.
Regards,
Sara
Hi.
Please share the code you’re using.
The code you’re sharing is just a regular DHT code.
Regards,
Sara
Thank you for the quick response. Please check the code
/*********
Rui Santos
Complete instructions at https://RandomNerdTutorials.com/firebase-esp32-esp8266-ebook/
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>
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <DHT.h> // Add DHT library
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.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 “Tp-link”
#define WIFI_PASSWORD “”
// Insert Firebase project API Key
#define API_KEY “”
// Insert Authorized Username and Corresponding Password
#define USER_EMAIL “”
#define USER_PASSWORD “”
// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL “”
// Define Firebase objects
FirebaseData stream;
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 listenerPath;
// DHT11 sensor
#define DHTPIN 23 // Define the pin where the DHT sensor is connected
#define DHTTYPE DHT11 // Define the DHT sensor type
DHT dht(DHTPIN, DHTTYPE);
float temperature;
float humidity;
//OLED Display
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Timer variables (send new readings every other minute)
unsigned long sendDataPrevMillis = 0;
unsigned long timerDelay = 120000;
// Declare outputs
const int output1 = 2;
const int output2 = 12;
const int slider1 = 13;
const int slider2 = 14;
// Variable to save input message
String message;
// Setting PWM properties
const int freq = 5000;
const int slider1Channel = 0;
const int slider2Channel = 1;
const int resolution = 8;
// Initialize OLED
void initOLED(){
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)){
Serial.println(F(“SSD1306 allocation failed”));
for(;;);
}
display.clearDisplay();
}
// Display message on OLED display
void displayMessage(String message){
display.clearDisplay();
display.setTextSize(2);
display.setCursor(0,0);
display.setTextColor(WHITE);
display.print(message);
display.display();
}
// 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());
}
}
// Callback function that runs on database changes
void streamCallback(FirebaseStream data){
Serial.printf(“stream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\n\n”,
data.streamPath().c_str(),
data.dataPath().c_str(),
data.dataType().c_str(),
data.eventType().c_str());
printResult(data); //see addons/RTDBHelper.h
Serial.println();
// Get the path that triggered the function
String streamPath = String(data.dataPath());
// Check for changes in the digital output values
if(streamPath.indexOf(“/digital/”) >= 0){
// Get the string path length
int stringLen = streamPath.length();
// Get the index of the last slash
int lastSlash = streamPath.lastIndexOf(“/”);
// Get the GPIO number (it’s after the last slash “/”)
// UsersData/<uid>/outputs/digital/<gpio_number>
String gpio = streamPath.substring(lastSlash + 1, stringLen);
Serial.print(“DIGITAL GPIO: “);
Serial.println(gpio);
// Get the data published on the stream path (it’s the GPIO state)
if(data.dataType() == “int”){
int gpioState = data.intData();
Serial.print(“VALUE: “);
Serial.println(gpioState);
// Update GPIO state (LED) based on the received value (1 for ON, 0 for OFF)
if(gpio == “2”){
digitalWrite(output1, gpioState);
}elseif(gpio == “12”){
digitalWrite(output2, gpioState);
}
}
Serial.println();
}
/* When it first runs, it is triggered on the root (/) path and returns a JSON with all key
and values of that path.So, we can get all values from the database and updated the GPIO
states, PWM, and message on OLED*/
if (data.dataTypeEnum() == fb_esp_rtdb_data_type_json){ FirebaseJson *json = data.to<FirebaseJson *>(); FirebaseJsonData result;
if (json->get(result, “/digital/” + String(output1), false)){
bool state = result.to<bool>();
digitalWrite(output1, state); }
if (json->get(result, “/digital/” + String(output2), false)){ bool state = result.to<bool>();
digitalWrite(output2, state);
}
if (json->get(result, “/message”, false)){
String message = result.to<String>();
displayMessage(message); }
if (json->get(result, “/pwm/” + String(slider1), false)){ int pwmValue = result.to<int>();
analogWrite(slider1, map(pwmValue, 0, 100, 0, 255)); }
if (json->get(result, “/pwm/” + String(slider2), false)){ int pwmValue = result.to<int>();
analogWrite(slider2, map(pwmValue, 0, 100, 0, 255));
} }
// Check for changes in the digital output values
if(streamPath.indexOf(“/digital/”) >= 0){ // Get string path lengh
int stringLen = streamPath.length();
// Get the index of the last slash
int lastSlash = streamPath.lastIndexOf(“/”);
// Get the GPIO number (it’s after the last slash “/”)
// UsersData/<uid>/outputs/digital/<gpio_number>
String gpio = streamPath.substring(lastSlash+1, stringLen);
Serial.print(“DIGITAL GPIO: “);
Serial.println(gpio);
// Get the data published on the stream path (it’s the GPIO state)
if(data.dataType() == “int”) {
int gpioState = data.intData();
Serial.print(“VALUE: “);
Serial.println(gpioState);
//Update GPIO state digitalWrite(gpio.toInt(), gpioState);
}
Serial.println();
}
// Check for changes in the slider values
else if(streamPath.indexOf(“/pwm/”) >= 0){ // Get string path lengh
int stringLen = streamPath.length();
// Get the index of the last slash
int lastSlash = streamPath.lastIndexOf(“/”);
// Get the GPIO number (it’s after the last slash “/”)
// UsersData/<uid>/outputs/PWM/<gpio_number>
int gpio = (streamPath.substring(lastSlash+1, stringLen)).toInt(); Serial.print(“PWM GPIO: “);
Serial.println(gpio);
// Get the PWM Value
if(data.dataType() == “int”){
int PWMValue = data.intData(); Serial.print(“VALUE: “); Serial.println(PWMValue);
analogWrite(gpio, map(PWMValue, 0, 100, 0, 255));
} }
// Check for changes in the message
else if (streamPath.indexOf(“/message”) >= 0){ if (data.dataType() == “string”) {
message = data.stringData();
Serial.print(“MESSAGE: “); Serial.println(message); // Print on OLED displayMessage(message);
} }
//This is the size of stream payload received (current and max value)
//Max payload size is the payload size under the stream path since the stream c onnected
//and read once and will not update until stream reconnection takes place.
//This max value will be zero as no payload received in case of ESP8266 which
//BearSSL reserved Rx buffer size is less than the actual stream payload. Serial.printf(“Received stream payload size: %d (Max. %d)\n\n”, data.payloadLen
Serial.printf(“Received stream payload size: %d (Max. %d)\n\n”, data.payloadLength(),
data.maxPayloadLength()); }
void streamTimeoutCallback(bool timeout){
if(timeout)
Serial.println(“stream timeout, resuming…\n”);
if(!stream.httpConnected())
Serial.printf(“error code: %d, reason: %s\n\n”, stream.httpCode(), stream.errorReason().c_str());
}
void setup(){
Serial.begin(115200);
// Init DHT sensor, OLED, and WiFi
initOLED();
initWiFi();
// Initialize DHT sensor
dht.begin();
// Initialize Outputs
pinMode(output1, OUTPUT);
pinMode(output2, OUTPUT);
pinMode(slider1, OUTPUT);
pinMode(slider2, OUTPUT);
// 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 authentication 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 with user UID
databasePath = “/UsersData/” + uid;
// Define database path for sensor readings
tempPath = databasePath + “/sensor/temperature”; // –> UsersData/<user_uid>/sensor/temperature
humPath = databasePath + “/sensor/humidity”; // –> UsersData/<user_uid>/sensor/humidity
// Update database path for listening
listenerPath = databasePath + “/outputs/”;
// Streaming (whenever data changes on a path)
// Begin stream on a database path –> UsersData/<user_uid>/outputs
if(!Firebase.RTDB.beginStream(&stream, listenerPath.c_str()))
Serial.printf(“stream begin error, %s\n\n”, stream.errorReason().c_str());
// Assign a callback function to run when it detects changes on the database
Firebase.RTDB.setStreamCallback(&stream, streamCallback, streamTimeoutCallback);
delay(2000);
}
void loop(){
// Send new readings to the database
if(Firebase.ready() && (millis() – sendDataPrevMillis > timerDelay || sendDataPrevMillis == 0)){
sendDataPrevMillis = millis();
// Get latest sensor readings from DHT sensor
temperature = dht.readTemperature();
humidity = dht.readHumidity();
// Send readings to the database:
sendFloat(tempPath, temperature);
sendFloat(humPath, humidity);
}
// … (rest of the code remains the same)
}
Hi.
The section to send sensor readings seems to be correct.
Did you change anything else in the code?
Can you comment the section of code that sends the sensor readings to check if the code is working properly without that section? So that we can figure out if it is anything elese that is causing the issue.
Regards,
Sara
Thanks, I reconnected everything and ran the code. works successfully. I created the web app also. working flawlessly. it was a great project. Do you have any course materials to mage Flutter app with vs code or any platform?