#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int batPin = 35, loadPin = 32, voltPin = 34;
const float sensitivity = 0.066, dividerRatioBat = 19.8 / 3.3, dividerRatioSensor = 5 / 3.3;
const float zeroCurrentVoltageB = 2.3, zeroCurrentVoltageL = 2.3;
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Wi-Fi credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Initialize Wi-Fi and server
WiFiServer server(80);
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Start the server
server.begin();
}
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 = max(powerBat + powerLoad, 0.0f);
float wattTotal = max(voltBat * powerTotal, 0.0f);
float wattLoad = max(voltBat * powerLoad, 0.0f);
powerLoad = max(powerLoad, 0.0f);
lcd.setCursor(0, 0);
lcd.printf("%4.1fV %4.1fA %3.0fW", voltBat, powerTotal, wattTotal);
lcd.setCursor(0, 1);
lcd.printf("%4.1f%s %4.1fA %3.0fW", powerBat < 0 ? -powerBat : powerBat, powerBat < 0 ? "D" : "C", powerLoad, wattLoad);
webServer();
delay(1000);
}
void webServer() {
// Handle incoming client requests
WiFiClient client = server.available();
if (client) {
Serial.println("New client connected");
String request = "";
while (client.connected() || client.available()) {
if (client.available()) {
char c = client.read();
request += c;
if (c == '\n') {
if (request.startsWith("GET / ")) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println(generateHTML());
}
break;
}
}
}
client.stop();
Serial.println("Client disconnected");
}
}
String generateHTML() {
// Use the already calculated values to generate the HTML
String html = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Monitor</title>
</head>
<body>
<h1>Battery Voltage: )rawliteral" + String(voltBat, 1) + R"rawliteral(V</h1>
<h2>Total Power: )rawliteral" + String(powerTotal, 1) + R"rawliteral(A</h2>
<h2>Total Wattage: )rawliteral" + String(wattTotal, 0) + R"rawliteral(W</h2>
<h2>Battery Current: )rawliteral" + String(powerBat < 0 ? -powerBat : powerBat, 1) + (powerBat < 0 ? "D" : "C") + R"rawliteral(</h2>
<h2>Load Current: )rawliteral" + String(powerLoad, 1) + R"rawliteral(A</h2>
<h2>Load Wattage: )rawliteral" + String(wattLoad, 0) + R"rawliteral(W</h2>
</body>
</html>
)rawliteral";
return html;
}
float readPin(int pin) {
return analogRead(pin) * 3.3 / 4095.0;
}