#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// GPIO Pins
const int voltagePin = 34; // Use GPIO 34 for voltage input
const int currentPin = 35; // Use GPIO 35 for current input
const int buttonPin = 2; // Use GPIO 2 for button input
// LCD setup
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD address and dimensions
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
int displayMode = 0; // 0: voltage, 1: current, 2: power
bool buttonPressed = false; // Flag to detect button press
void setup() {
Serial.begin(115200);
// Initialize LCD
lcd.init();
lcd.backlight();
pinMode(buttonPin, INPUT_PULLUP); // Configure button pin as input with internal pull-up resistor
// 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");
// Serve the web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
String html = "<html><body>";
html += "<h1>ESP32 Solar Monitor</h1>";
html += "<p>Voltage: " + String(getVoltage(), 2) + " V</p>";
html += "<p>Current: " + String(getCurrent(), 2) + " A</p>";
html += "<p>Power: " + String(getPower(), 2) + " W</p>";
html += "</body></html>";
request->send(200, "text/html", html);
});
server.begin();
}
void loop() {
int buttonState = digitalRead(buttonPin);
if (buttonState == LOW && !buttonPressed) {
// Button pressed, toggle display mode
displayMode = (displayMode + 1) % 3;
buttonPressed = true;
} else if (buttonState == HIGH && buttonPressed) {
// Button released, reset flag
buttonPressed = false;
}
lcd.clear(); // Clear the LCD display
if (displayMode == 0) {
// Display solar voltage
float voltage = getVoltage();
lcd.setCursor(0, 0);
lcd.print("Voltage: ");
lcd.print(voltage, 2); // Print with 2 decimal places
lcd.print("V");
} else if (displayMode == 1) {
// Display solar current
float current = getCurrent();
lcd.setCursor(0, 0);
lcd.print("Current: ");
lcd.print(current, 2); // Print with 2 decimal places
lcd.print("A");
} else {
// Display solar power
float power = getPower();
lcd.setCursor(0, 0);
lcd.print("Power: ");
lcd.print(power, 2); // Print with 2 decimal places
lcd.print("W");
}
delay(100); // Debounce delay
}
float getVoltage() {
int voltageValue = analogRead(voltagePin);
return (voltageValue * 3.3 / 4095.0); // ESP32 uses a 12-bit ADC with 3.3V reference
}
float getCurrent() {
int currentValue = analogRead(currentPin);
return (currentValue * 3.3 / 4095.0); // ESP32 uses a 12-bit ADC with 3.3V reference
}
float getPower() {
return getVoltage() * getCurrent();
}