#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include <Wire.h>
#include <Adafruit_Sensor.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"
// WiFi credentials
#define WIFI_SSID "YOUR_WIFI_SSID"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"
// Firebase project API Key
#define API_KEY "YOUR_FIREBASE_API_KEY"
// Firebase Realtime Database URL
#define DATABASE_URL "YOUR_FIREBASE_DATABASE_URL"
// Firebase email and password
#define USER_EMAIL "YOUR_FIREBASE_EMAIL"
#define USER_PASSWORD "YOUR_FIREBASE_PASSWORD"
// Define Firebase objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
// MQ2 sensor pin
#define MQ2PIN 34 // Analog pin for MQ2 sensor
// Variables
float gasValue = 0.0;
unsigned long sendDataPrevMillis = 0;
bool signupOK = false;
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
// Initialize Firebase
config.api_key = API_KEY;
config.database_url = DATABASE_URL;
// Assign user credentials
auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;
// Assign the callback function for the long running token generation task
config.token_status_callback = tokenStatusCallback;
Firebase.begin(&config, &auth);
Firebase.reconnectWiFi(true);
// Wait for Firebase to authenticate
Serial.print("Authenticating with Firebase");
while (!Firebase.ready()) {
Serial.print(".");
delay(300);
}
Serial.println();
Serial.println("Firebase authentication successful");
signupOK = true;
}
void loop() {
// Send data to Firebase every 15 seconds
if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) {
sendDataPrevMillis = millis();
// Read MQ2 sensor value
gasValue = analogRead(MQ2PIN);
gasValue = map(gasValue, 0, 4095, 0, 100); // Convert to percentage (adjust as needed)
Serial.printf("Gas Value: %.2f%%\n", gasValue);
// Send to Firebase
if (Firebase.RTDB.setFloat(&fbdo, "/MQ2/GasValue", gasValue)) {
Serial.println("Data sent to Firebase successfully");
} else {
Serial.println("Failed to send data");
Serial.println("REASON: " + fbdo.errorReason());
}
}
}