#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int batPin = 35; // Analog pin for ESP32
const int loadPin = 32;
const int voltPin = 34;
const float sensitivity = 0.066; // Sensitivity of ACS712-30A in V/A (66 mV/A)
const float dividerRatioBat = 19.8 / 3.3; // Adjust based on your resistor values
const float dividerRatioSensor = 5 / 3.3;
float zeroCurrentVoltageB = 2.3; // Voltage at zero current
float zeroCurrentVoltageL = 2.3;
// Initialize the LCD with the I2C address, width, and height
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
pinMode(batPin, INPUT);
pinMode(loadPin, INPUT);
pinMode(voltPin, INPUT);
}
void loop() {
float voltBat = (readPin(voltPin) + 0.166) * dividerRatioBat;
float powerBat = (readPin(batPin) * dividerRatioSensor - zeroCurrentVoltageB) / sensitivity;
float powerLoad = (readPin(loadPin) * dividerRatioSensor - zeroCurrentVoltageL) / sensitivity ;
float powerTotal = powerBat + powerLoad;
float wattTotal = voltBat * powerTotal;
float wattLoad = voltBat * powerLoad;
wattTotal = max(wattTotal, 0.0f);
wattLoad = max(wattLoad, 0.0f);
powerLoad = max(powerLoad, 0.0f);
powerTotal = max(powerTotal, 0.0f);
// Create formatted strings for voltages and wattage
char voltStr[8];
char powertotalStr[8];
char watttotalStr[8];
char powerbatStr[8];
char powerloadStr[8];
char wattloadStr[8];
// Format voltage strings
snprintf(voltStr, 8, "%4.1fV", voltBat);
snprintf(powertotalStr, 8, "%4.1fA", powerTotal);
snprintf(watttotalStr, 8, "%3.0fW", wattTotal);
//snprintf(powerbatStr, 8, "%4.1fC", powerBat);
if (powerBat < 0) {
snprintf(powerbatStr, 8, "%4.1fD", -powerBat);
} else {
snprintf(powerbatStr, 8, "%4.1fC", powerBat);
}
snprintf(powerloadStr, 8, "%4.1fA", powerLoad);
snprintf(wattloadStr, 8, "%3.0fW", wattLoad);
// Print solar voltage on the first row
lcd.setCursor(0, 0);
lcd.print(voltStr);
lcd.setCursor(6, 0);
lcd.print(powertotalStr);
lcd.setCursor(12, 0);
lcd.print(watttotalStr);
// Print battery voltage on the second row
lcd.setCursor(0, 1);
lcd.print(powerbatStr);
lcd.setCursor(6, 1);
lcd.print(powerloadStr);
// Print wattage on the second row, replace previous text if needed
// Here it assumes you want to display wattage in the second row, replacing the previous content
lcd.setCursor(12, 1);
lcd.print(wattloadStr);
delay(400); // Update every second
}
float readPin(int pin) {
int adcValue = analogRead(pin);
return (adcValue / 4095.0) * 3.3; // Convert ADC value to voltage (0-3.3V)
}