#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak API
const char* server = "http://api.thingspeak.com/update";
String apiKey = "0LZPYNP254P5NJI2";
// Potentiometer pins
const int pot1Pin = 34; // Simulates voltage
const int pot2Pin = 35; // Simulates current
// Energy calculation
unsigned long lastMillis = 0;
float energy_kWh = 0.0;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected.");
lastMillis = millis();
}
void loop() {
// Read raw analog values
int rawVolt = analogRead(pot1Pin); // 0 - 4095
int rawAmp = analogRead(pot2Pin); // 0 - 4095
// Map to realistic values
float voltage = rawVolt * (300.0 / 4095.0); // 0 - 300V
float current = rawAmp * (20.0 / 4095.0); // 0 - 20A
// Power in kW
float power_kW = (voltage * current) / 1000.0;
// Time since last reading
unsigned long now = millis();
float deltaHours = (now - lastMillis) / 3600000.0; // ms to hours
lastMillis = now;
// Energy in kWh
energy_kWh += power_kW * deltaHours;
// Output
Serial.printf("Voltage: %.2f V, Current: %.2f A, Power: %.3f kW, Energy: %.5f kWh\n",
voltage, current, power_kW, energy_kWh);
// Send to ThingSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(server) + "?api_key=" + apiKey +
"&field1=" + String(voltage) +
"&field2=" + String(current) +
"&field3=" + String(power_kW) +
"&field4=" + String(energy_kWh);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.println("Data sent to ThingSpeak.");
} else {
Serial.printf("Failed to send: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(20000); // Wait at least 15s for ThingSpeak
}