why my voltage sensor still reading voltage even when its not even connected to any electrics
excluding wires from esp32 this zmpt101b (voltage sensor) is not conected to any source of electrics from the terminal block on its modules and idk why so my plan is to build a device that can calculate the voltage, current and power that are consumed from other electronics device (schematics embeded) and it should be working right with the code down below but when i tested it i noticed the voltage are odd because when i use like phone charger on terminal Load it doesnt work so i have to calibrate it using the potensio included in the zmpt101b & zmtc103 (current sensor) and it kinda works ig, but when i try to use a big speaker the calculation are off, the voltage ramped up from averaging 223 to 240 wich is not the speaker problem bcs if it really had that much volt it wil already explode from the start. and from my knowledge it shouldnt even be the volt that got bigger it should be the current but the current calculation are the same as the one with phone charger and now here i am, with a voltage sensor that still calculating volt even tho no electricity is inserted and a current sensor that thinks every electricity current is as the same as the one used in a phone charger help please. if you had any idea of whats going on and maybe need more info just tell me, i need your help and also by what i mean still calculating volt, the result from ZMPT101B is like thisConected to electricityzmpt101b value = 100Vnot conected to electricityzmpt101b value = 100vso yeah its the same thats why even using sensitivity from code wont change a thing here cuz yeah it will be around 220v but it will always be 220v :C
this is the code that i use:
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <ZMPT101B.h>
#include <WiFiClientSecure.h>
// GANTI DENGAN SSID DAN PASSWORD HOTSPOT KAMU
const char* ssid = "GG";
const char* password = "geoganteng";
// Firebase Configuration
const char* firebase_host = "https://energy-monitor-9c20a-default-rtdb.firebaseio.com";
const char* firebase_auth = "fhXyDUpGnEqvhXb8PkAbfsM3257NvDdTYiRMsWQg";
// Pin Configuration
const int VOLTAGE_PIN = 39;
const int CURRENT_PIN = 36;
// Inisialisasi ZMPT101B sensor
ZMPT101B voltageSensor(VOLTAGE_PIN, 50);
// Konfigurasi ZHT103 Current Sensor
const float ADC_RESOLUTION = 4095.0;
const float ADC_VREF = 3.3;
const int CURRENT_SAMPLE_COUNT = 1000;
const float CURRENT_OFFSET = 2.5;
const float CURRENT_SCALE = 0.35;
// ZMPT101B Sensitivity
const float ZMPT101B_SENSITIVITY = 500.0f;
// Threshold dan faktor daya
const float VOLTAGE_THRESHOLD = 10.0;
const float CURRENT_THRESHOLD = 0.02;
const float POWER_FACTOR = 0.9;
// Variabel data sensor
float voltageRMS = 0;
float currentRMS = 0;
float activePower = 0;
float apparentPower = 0;
float energyConsumed = 0;
float powerFactor = 0;
// Monitoring
int currentADC_avg = 0;
float currentAnalog_avg = 0;
// Waktu untuk energi dan firebase
unsigned long lastEnergyTime = 0;
unsigned long lastFirebaseTime = 0;
const unsigned long FIREBASE_INTERVAL = 10000;
// Koneksi
int failedAttempts = 0;
const int MAX_FAILED_ATTEMPTS = 3;
bool firebaseConnected = false;
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("\n=== ESP32 Energy Monitor Firebase v3.1 (Hotspot Mode) ===");
analogReadResolution(12);
analogSetAttenuation(ADC_11db);
voltageSensor.setSensitivity(ZMPT101B_SENSITIVITY);
Serial.printf("β
ZMPT101B initialized. Sensitivity: %.1f\n", ZMPT101B_SENSITIVITY);
Serial.printf("\nπΆ Connecting to %s...\n", ssid);
WiFi.begin(ssid, password);
int attempt = 0;
while (WiFi.status() != WL_CONNECTED && attempt < 30) {
delay(500);
Serial.print(".");
attempt++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nβ
WiFi Connected!");
Serial.print("π± IP Address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("\nβ WiFi connection failed. Restarting...");
delay(3000);
ESP.restart();
}
testFirebaseConnectionWithRetry();
lastEnergyTime = millis();
lastFirebaseTime = millis();
}
void loop() {
readSensors();
if (millis() - lastFirebaseTime >= FIREBASE_INTERVAL) {
sendToFirebaseWithRetry();
lastFirebaseTime = millis();
}
delay(100);
}
void readSensors() {
voltageRMS = voltageSensor.getRmsVoltage();
if (voltageRMS < VOLTAGE_THRESHOLD) voltageRMS = 0;
readCurrentSensor();
if (voltageRMS > 0 && currentRMS > 0) {
apparentPower = voltageRMS * currentRMS;
activePower = apparentPower * POWER_FACTOR;
powerFactor = POWER_FACTOR;
} else {
apparentPower = 0;
activePower = 0;
powerFactor = 0;
}
calculateEnergy();
}
void readCurrentSensor() {
long currentSum = 0;
float currentSquareSum = 0;
for (int i = 0; i < CURRENT_SAMPLE_COUNT; i++) {
int currentADC = analogRead(CURRENT_PIN);
float currentAnalog = (currentADC * ADC_VREF) / ADC_RESOLUTION;
currentAnalog = currentAnalog * (5.0 / 3.3);
float currentAC = currentAnalog - CURRENT_OFFSET;
currentSum += currentADC;
currentSquareSum += (currentAC * currentAC);
delayMicroseconds(100);
}
currentADC_avg = currentSum / CURRENT_SAMPLE_COUNT;
currentAnalog_avg = (currentADC_avg * ADC_VREF) / ADC_RESOLUTION;
float currentRMS_raw = sqrt(currentSquareSum / CURRENT_SAMPLE_COUNT);
currentRMS = currentRMS_raw * CURRENT_SCALE;
if (currentRMS < CURRENT_THRESHOLD) currentRMS = 0;
}
void calculateEnergy() {
unsigned long currentTime = millis();
if (lastEnergyTime != 0 && activePower > 0) {
float deltaHours = (currentTime - lastEnergyTime) / 3600000.0;
energyConsumed += (activePower * deltaHours) / 1000.0;
}
lastEnergyTime = currentTime;
}
void testFirebaseConnectionWithRetry() {
Serial.println("π Testing Firebase connection...");
for (int attempt = 1; attempt <= 3; attempt++) {
Serial.printf("Attempt %d/3...\n", attempt);
if (testFirebaseConnection()) {
firebaseConnected = true;
failedAttempts = 0;
Serial.println("β
Firebase connection successful!");
return;
}
if (attempt < 3) {
delay(2000);
}
}
Serial.println("β All Firebase connection attempts failed!");
firebaseConnected = false;
}
bool testFirebaseConnection() {
if (WiFi.status() != WL_CONNECTED) return false;
HTTPClient http;
http.setTimeout(20000);
http.setConnectTimeout(8000);
String testUrl = String(firebase_host) + "/test.json?auth=" + firebase_auth;
http.begin(testUrl);
http.addHeader("Content-Type", "application/json");
String testData = "\"" + String(millis()) + "\"";
int httpCode = http.PUT(testData);
http.end();
delay(100);
return (httpCode == 200);
}
void sendToFirebaseWithRetry() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("β WiFi not connected");
return;
}
if (failedAttempts >= MAX_FAILED_ATTEMPTS) {
Serial.println("β οΈ Too many failures, retrying...");
testFirebaseConnectionWithRetry();
if (!firebaseConnected) return;
}
bool success = sendToFirebase();
if (success) {
failedAttempts = 0;
firebaseConnected = true;
} else {
failedAttempts++;
if (failedAttempts >= MAX_FAILED_ATTEMPTS) firebaseConnected = false;
}
}
bool sendToFirebase() {
HTTPClient http;
http.setTimeout(25000);
http.setConnectTimeout(10000);
unsigned long timestamp = millis();
String latestUrl = String(firebase_host) + "/energy/latest.json?auth=" + firebase_auth;
http.begin(latestUrl);
http.addHeader("Content-Type", "application/json");
DynamicJsonDocument doc(1024);
doc["voltage"] = round(voltageRMS * 10) / 10.0;
doc["current"] = round(currentRMS * 1000) / 1000.0;
doc["power"] = round(activePower * 10) / 10.0;
doc["energy"] = round(energyConsumed * 10000) / 10000.0;
doc["timestamp"] = timestamp;
doc["wifi_rssi"] = WiFi.RSSI();
doc["free_heap"] = ESP.getFreeHeap();
String jsonStr;
serializeJson(doc, jsonStr);
int httpCode = http.PUT(jsonStr);
http.end();
delay(200);
if (httpCode == 200 && activePower > 0.1) {
HTTPClient historyHttp;
historyHttp.setTimeout(15000);
historyHttp.setConnectTimeout(6000);
String historyUrl = String(firebase_host) + "/energy/history/" + String(timestamp) + ".json?auth=" + firebase_auth;
historyHttp.begin(historyUrl);
historyHttp.addHeader("Content-Type", "application/json");
DynamicJsonDocument histDoc(512);
histDoc["voltage"] = doc["voltage"];
histDoc["current"] = doc["current"];
histDoc["power"] = doc["power"];
histDoc["timestamp"] = timestamp;
String histStr;
serializeJson(histDoc, histStr);
historyHttp.PUT(histStr);
historyHttp.end();
delay(100);
}
return (httpCode == 200);
}
