#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
int voltagePin = 34; // GPIO34 for voltage sensor (Potentiometer 1)
int currentPin = 35; // GPIO35 for current sensor (Potentiometer 2)
int redLED = 13; // Abnormal power consumption alert
int greenLED = 14; // Normal power consumption indicator
float voltage = 0;
float current = 0;
float power = 0;
float energy = 0; // Total energy in kWh
void setup() {
// Initialize serial communication for debugging
Serial.begin(115200);
// Initialize the OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (1);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// Set up LED pins
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
// Set up voltage and current sensor pins
pinMode(voltagePin, INPUT);
pinMode(currentPin, INPUT);
// Display initialization message
display.setCursor(0, 0);
display.println("Smart Energy Meter");
display.display();
delay(2000);
display.clearDisplay();
}
void loop() {
// Read analog values from potentiometers
int voltageValue = analogRead(voltagePin); // From GPIO34
int currentValue = analogRead(currentPin); // From GPIO35
// Convert analog readings to realistic voltage and current values
voltage = voltageValue * (220.0 / 4095.0); // Simulate voltage range from 0 to 220V
current = currentValue * (30.0 / 4095.0); // Simulate current range from 0 to 30A
// Calculate power (P = V * I) and energy (in kWh)
power = voltage * current;
energy += power / 3600000.0; // Convert to kWh over time
// Print the raw analog values for debugging
Serial.print("Raw Voltage Value: ");
Serial.println(voltageValue);
Serial.print("Raw Current Value: ");
Serial.println(currentValue);
// Display values on OLED
display.clearDisplay();
display.setCursor(0, 0);
display.println("Power Consumption:");
display.print("Vrms: "); display.println(voltage);
display.print("Irms: "); display.println(current);
display.print("Power: "); display.println(power);
display.print("Energy: "); display.println(energy);
display.display();
// Check if power consumption is abnormal
if (power > 1000.0) { // Set a threshold for abnormal usage
digitalWrite(redLED, HIGH); // Turn on red LED
digitalWrite(greenLED, LOW); // Turn off green LED
} else {
digitalWrite(redLED, LOW); // Turn off red LED
digitalWrite(greenLED, HIGH); // Turn on green LED
}
delay(1000); // Refresh every second
}