#include <WiFi.h>
#include <HTTPClient.h>
// ----- Energy Monitoring Sensors -----
#define VOLTAGE_PIN 34 // Analog pin for voltage sensor (ZMPT101B or similar)
#define CURRENT_PIN 35 // Analog pin for current sensor (ACS712 or SCT-013)
#define GAS_PIN 32 // Analog pin for gas sensor (MQ-2, MQ-5, or similar)
// ----- Device Control (Relays/LEDs) -----
#define DEVICE_1_PIN 12 // Main load control
#define DEVICE_2_PIN 27 // Secondary load control
bool device1State = false;
bool device2State = false;
// ----- Energy Calculation Variables -----
float voltage = 0.0;
float current = 0.0;
float power = 0.0;
float energyToday = 0.0;
float gasLevel = 0.0;
unsigned long lastEnergyUpdate = 0;
unsigned long lastReading = 0;
// ----- Calibration Constants -----
const float VOLTAGE_CALIBRATION = 220.0 / 3.3; // Adjust based on your voltage divider
const float CURRENT_CALIBRATION = 30.0 / 3.3; // Adjust based on your current sensor (ACS712-30A)
const float VOLTAGE_OFFSET = 1.65; // ADC offset for AC measurements
const float CURRENT_OFFSET = 1.65; // ADC offset for AC measurements
// ----- WiFi & Firebase -----
#define FIREBASE_HOST "eya-sesame-default-rtdb.europe-west1.firebasedatabase.app"
// ⚠️ IMPORTANT: Replace with your Firebase Database Secret (NOT API Key!)
// Get it from: Firebase Console → Project Settings → Service Accounts → Database Secrets
#define FIREBASE_AUTH "AIzaSyAN5EQyDzE1G1jDNNq2neQJEnJEzLi9p8Q" // ← REPLACE THIS!
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// ----- Setup -----
void setup() {
Serial.begin(115200);
// Setup device control pins
pinMode(DEVICE_1_PIN, OUTPUT);
pinMode(DEVICE_2_PIN, OUTPUT);
digitalWrite(DEVICE_1_PIN, LOW);
digitalWrite(DEVICE_2_PIN, LOW);
// Setup analog input pins
pinMode(VOLTAGE_PIN, INPUT);
pinMode(CURRENT_PIN, INPUT);
pinMode(GAS_PIN, INPUT);
// Connect to WiFi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi!");
Serial.println("Energy Monitoring System Started");
lastEnergyUpdate = millis();
lastReading = millis();
}
// ----- Loop -----
void loop() {
// Read device states from Firebase
readDeviceStates();
// Read and send energy data every 2 seconds
if (millis() - lastReading >= 2000) {
readAndSendEnergyData();
lastReading = millis();
}
// Update daily energy accumulation
updateEnergyAccumulation();
delay(100); // Small delay to prevent overwhelming the system
}
// ----- Read Device States from Firebase -----
void readDeviceStates() {
HTTPClient http;
String url = String("https://") + FIREBASE_HOST + "/.json?auth=" + FIREBASE_AUTH;
http.begin(url);
int code = http.GET();
if (code == 200) {
String payload = http.getString();
// Parse device states
device1State = payload.indexOf("\"Device_1\":true") != -1;
digitalWrite(DEVICE_1_PIN, device1State);
device2State = payload.indexOf("\"Device_2\":true") != -1;
digitalWrite(DEVICE_2_PIN, device2State);
Serial.println("Device 1: " + String(device1State ? "ON" : "OFF") +
" | Device 2: " + String(device2State ? "ON" : "OFF"));
}
http.end();
}
// ----- Read and Send Energy Data -----
void readAndSendEnergyData() {
// Read voltage sensor (simulated with potentiometer in Wokwi)
int voltageRaw = analogRead(VOLTAGE_PIN);
float voltageReading = voltageRaw * (3.3 / 4095.0);
// For simulation: map 0-3.3V to 200-240V range
// In real hardware, use proper voltage sensor calibration
voltage = 200.0 + (voltageReading / 3.3) * 40.0;
// Read current sensor (simulated with potentiometer in Wokwi)
int currentRaw = analogRead(CURRENT_PIN);
float currentReading = currentRaw * (3.3 / 4095.0);
// For simulation: map 0-3.3V to 0-15A range
// In real hardware, use proper current sensor calibration (ACS712, SCT-013)
current = (currentReading / 3.3) * 15.0;
// Calculate power (P = V × I)
power = voltage * current;
// Read gas sensor (simulated with potentiometer in Wokwi)
int gasRaw = analogRead(GAS_PIN);
gasLevel = gasRaw * (3.3 / 4095.0); // Convert to voltage (0-3.3V)
// In real hardware with MQ-2/MQ-5:
// - gasLevel represents analog voltage output
// - Higher voltage = higher gas concentration
// - Typical range: 0-3.3V or 0-5V depending on sensor
// Print readings
Serial.println("=== Energy Readings ===");
Serial.println("Voltage: " + String(voltage, 1) + " V");
Serial.println("Current: " + String(current, 2) + " A");
Serial.println("Power: " + String(power, 1) + " W");
Serial.println("Energy Today: " + String(energyToday, 3) + " kWh");
Serial.println("Gas Level: " + String(gasLevel, 2) + " V");
// Send to Firebase
Serial.println("📤 Sending to Firebase...");
sendValue("/Voltage", voltage);
sendValue("/Current", current);
sendValue("/Power", power);
sendValue("/EnergyToday", energyToday);
sendValue("/Gas", gasLevel);
Serial.println("✅ All values sent!");
}
// ----- Update Energy Accumulation -----
void updateEnergyAccumulation() {
// Calculate energy consumed since last update
// Energy (kWh) = Power (W) × Time (hours) / 1000
unsigned long currentTime = millis();
unsigned long timeDiff = currentTime - lastEnergyUpdate;
if (timeDiff >= 1000) { // Update every second
float hours = timeDiff / 3600000.0; // Convert ms to hours
float energyIncrement = (power * hours) / 1000.0; // Convert W to kW
energyToday += energyIncrement;
lastEnergyUpdate = currentTime;
}
}
// ----- Send a value to Firebase -----
void sendValue(String path, float value) {
HTTPClient http;
String url = String("https://") + FIREBASE_HOST + path + ".json?auth=" + FIREBASE_AUTH;
http.begin(url);
http.addHeader("Content-Type", "application/json");
String json = String(value);
int httpCode = http.PUT(json);
// Debug: Print HTTP response code
if (httpCode != 200) {
Serial.println("❌ Firebase Error on " + path + ": HTTP " + String(httpCode));
}
http.end();
}