#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// LCD at address 0x27, 16x2
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Pins
#define RELAY_PIN 14 // Relay module input pin
#define BUZZER_PIN 27 // Buzzer pin
#define SENSOR_PIN 34 // Potentiometer simulating current sensor
// Constants
float voltage = 220.0; // Assume fixed mains voltage
float energy = 0.0; // Energy in Wh
unsigned long lastMillis = 0;
float threshold = 50.0; // Current threshold for alert (adjust as needed)
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW); // Relay OFF initially
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW); // Buzzer OFF
lcd.setCursor(0,0);
lcd.print("Smart Monitor");
delay(2000);
lcd.clear();
}
void loop() {
// Read sensor (0–4095 ADC → 0–5 A example scaling)
int adcVal = analogRead(SENSOR_PIN);
float current = (adcVal / 4095.0) * 5.0; // 0–5 A range
// Calculate power
float power = voltage * current; // Watts
// Update energy every second
unsigned long now = millis();
if (now - lastMillis >= 1000) {
energy += power / 3600.0; // Convert W → Wh per second
lastMillis = now;
}
// Display on LCD
lcd.setCursor(0,0);
lcd.print("I:");
lcd.print(current,2);
lcd.print("A ");
lcd.print("P:");
lcd.print(power,0);
lcd.print("W ");
lcd.setCursor(0,1);
lcd.print("E:");
lcd.print(energy,2);
lcd.print("Wh ");
// Control relay + buzzer
if (current > threshold/100.0) { // Example: >0.5A if threshold=50
digitalWrite(RELAY_PIN, HIGH); // Turn ON relay
// --- BUZZER ALERT ---
tone(BUZZER_PIN, 1000); // 1kHz sound
delay(200); // short beep
noTone(BUZZER_PIN); // stop
} else {
digitalWrite(RELAY_PIN, LOW); // Relay OFF
noTone(BUZZER_PIN); // Make sure buzzer is OFF
}
delay(500);
}