#include <WiFi.h>
#include<Firebase_ESP_Client.h>
#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define API_KEY "AIzaSyD9wbqNYYUNnS4gTBz-ZDLfhEeANegayPU"
#define DATABASE_URL "https://esp32--firebase-project-default-rtdb.asia-southeast1.firebasedatabase.app/"
#define LED1_PIN 12
#define LED2_PIN 14
#define LDR_PIN 36
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
unsigned long sendDataPrevMillis=0; //so we can write real time interval in an unblocking way
bool signupOK=false;
int ldrData=0; // to store 12 bit ADC data from 0 to 4095
float voltage=0.0;
void setup() {
// put your setup code here, to run once:
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();
config.api_key=API_KEY;
config.database_url= DATABASE_URL;
if(Firebase.signUp(&config , &auth, "","")){ // last two arguments are empty , this denotes an anonymous user signup.
Serial.println("signUp OK"); // every time a the esp32 connects it creates a new anonymous user.
signupOK=true; // if signup is successfull change it to true
}
else{
Serial.printf("%s\n",config.signer.signupError.message.c_str());
}
config.token_status_callback=tokenStatusCallback;
Firebase.reconnectWiFi(true);
}
void loop() {
if(Firebase.ready() && signupOK && (millis() - sendDataPrevMillis>5000 || sendDataPrevMillis == 0)){
sendDataPrevMillis=millis(); // we have to assign PrevMillis every time it exceeds 5000 millisecond mark to start if condition
// -------------STORE sensor data to a RTDB(real time data base)
ldrData=analogRead(LDR_PIN);
voltage=(float)analogReadMilliVolts(LDR_PIN)/1000; // to convert millivolts to volts
//we have different types of functions which returns bool value indicating success- set,setInt,setFloat,setDouble,setString,setFile etc. // this is how we store data in realtime database
// retruns true if HTTP status code returns 200. data types matched between request and response
// in our program we send integer data thats why setInt
if(Firebase.RTDB.setInt(&fbdo, "Sensor/ldr_data", ldrData)){ // Sensor/ldr_data is the desired path if we dont specify path it will create automatically
Serial.println();Serial.print(ldrData);
Serial.print("... successfully saved to: " + fbdo.dataPath());
Serial.println(" (" + fbdo.dataType() + ")");
}
else{
Serial.println("Failed: " + fbdo.errorReason());
}
if(Firebase.RTDB.setInt(&fbdo, "Sensor/voltage", voltage)){ // Sensor/ldr_data is the desired path if we dont specify path it will create automatically
Serial.println();Serial.print(voltage);
Serial.print("... successfully saved to: " + fbdo.dataPath());
Serial.println(" (" + fbdo.dataType() + ")");
}
else{
Serial.println("Failed: " + fbdo.errorReason());
}
}
}