#include <LiquidCrystal_I2C.h>
#include <SD.h>
// Pin Definitions
#define VOLTAGE_PIN A0 // Voltage simulated by potentiometer
#define CURRENT_PIN A1 // Current simulated by potentiometer
#define SD_CS 10 // Chip Select pin for SD Card Module
// Constants
const float REF_VOLTAGE = 5.0; // Reference voltage for ADC
const int ADC_RESOLUTION = 1024; // ADC resolution
const float VOLTAGE_DIVIDER_RATIO = 5.0; // Voltage divider ratio
const float CURRENT_SENSOR_SENSITIVITY = 0.185; // Sensitivity for current sensor (A/V)
// Objects
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD with I2C address 0x27
// Global Variables
float voltage = 0.0;
float current = 0.0;
float power = 0.0;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Initializing...");
// Initialize SD card
if (!SD.begin(SD_CS)) {
Serial.println("SD Card failed or not present!");
lcd.setCursor(0, 1);
lcd.print("SD Failed!");
while (true); // Halt the program if SD initialization fails
} else {
Serial.println("SD Card initialized.");
lcd.setCursor(0, 1);
lcd.print("SD Ready!");
}
delay(2000);
lcd.clear();
}
void loop() {
// Read voltage and current
voltage = analogRead(VOLTAGE_PIN) * (REF_VOLTAGE / ADC_RESOLUTION) * VOLTAGE_DIVIDER_RATIO;
current = (analogRead(CURRENT_PIN) * (REF_VOLTAGE / ADC_RESOLUTION) - 2.5) / CURRENT_SENSOR_SENSITIVITY;
power = voltage * current;
// Display data on LCD
lcd.setCursor(0, 0);
lcd.print("V: ");
lcd.print(voltage, 2);
lcd.print(" V");
lcd.setCursor(0, 1);
lcd.print("I: ");
lcd.print(current, 2);
lcd.print("A ");
lcd.print("P: ");
lcd.print(power, 2);
// Log data to SD card
File logFile = SD.open("energy_log.txt", FILE_WRITE);
if (logFile) {
logFile.print("Voltage: ");
logFile.print(voltage, 2);
logFile.print(" V, Current: ");
logFile.print(current, 2);
logFile.print(" A, Power: ");
logFile.print(power, 2);
logFile.println(" W");
logFile.close();
Serial.println("Data logged to SD card.");
} else {
Serial.println("Error opening file!");
}
delay(1000); // Update every second
}