Contents — 26 sections
Project Overview
Meters each machine's real power use so a factory can see where its energy actually goes, cut the waste it never knew about, and spot a machine drawing abnormally.
A factory's electricity bill is a single number, and that single number hides everything useful. Which machines are the energy hogs? What is being wasted running idle overnight? Is a motor drawing more than it should because a bearing is dragging? The utility meter cannot answer any of this because it measures the whole site as one lump. This project breaks that lump apart: it meters each machine individually, so a factory finally sees where its energy actually goes — and once you can see per-machine consumption, you can cut waste and catch anomalies that were previously invisible in the aggregate.
Each machine gets a power meter — a module (like a PZEM-004T) or a current-transformer clamp — that measures its real power, energy, voltage, current and power factor without breaking into the wiring. An ESP32 reads these and streams them to a time-series database and a dashboard (the classic InfluxDB + Grafana stack), giving live and historical per-machine consumption. The value is immediate: you discover the machines left drawing power while "off" (phantom/idle loads), the compressor that runs far more than anyone thought, the process that spikes demand and drives up peak charges — and you can quantify the saving from fixing each one, which is what turns an energy dashboard from a curiosity into a paying investment.
Beyond visibility, per-machine metering enables anomaly detection. A machine has a characteristic power profile for its normal duty; a sustained deviation — a motor drawing steadily more than baseline (a developing mechanical problem or a failing supply), a heater cycling abnormally, a machine running when it should be idle — is a signal worth an alert. Watching power factor adds another layer, revealing reactive-power inefficiency that costs money on the bill. It is honest that this is monitoring and insight, not a substitute for a professional energy audit or safety-critical metering, and that CT/meter accuracy and correct installation matter — but as an affordable, per-machine, always-on energy dashboard, it converts an opaque bill into a map of consumption a factory can actually act on, typically paying for itself in the waste it uncovers.
What this project does
- Meters each machine's real power, energy, voltage, current and power factor
- Streams live and historical per-machine data to a time-series dashboard
- Reveals idle/phantom loads and the true energy hogs
- Detects anomalies — a machine drawing abnormally vs its baseline
- Surfaces power-factor and peak-demand issues that cost money
- Quantifies the saving from each fix
- Alerts on abnormal consumption and left-on-idle machines
Real-World Applications
| Setting | How it is used |
|---|---|
| Factory energy management | Per-machine visibility to target waste, idle loads and peak-demand drivers and cut the bill. |
| Predictive-maintenance signal | A motor drawing steadily more than baseline flags a developing mechanical/electrical problem. |
| Sustainability / reporting | Measured per-process energy for efficiency programmes and carbon reporting. |
| Facilities / building services | Metering HVAC, compressors and pumps to find and fix inefficiency. |
Deployment contexts where a build of this kind earns its keep.
Features & Capabilities
- Per-machine metering (not one site lump)
- Real power/energy/PF via meter modules or CT clamps (non-invasive)
- InfluxDB + Grafana time-series dashboard
- Idle/phantom-load discovery and quantified savings
- Baseline anomaly detection per machine
- Power-factor and peak-demand insight
- Honest scope: insight tool, not audit/safety metering
Difficulty, Time & Required Skills
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 12–18 hours |
| Indicative build cost | ₹5,000 – ₹9,000 (multi-machine) |
| Primary discipline | Industrial |
| Reference platform | ESP32 DevKit V1 (ESP-WROOM-32) |
Skills you should have (or will pick up)
- Non-invasive power metering (PZEM/CT) and reading real power/PF
- Streaming to a time-series database (InfluxDB) and Grafana dashboards
- Baseline anomaly detection on power profiles
- Interpreting power factor and peak demand
- Safe installation around mains/machine power
Bill of Materials
Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.
| Component | Key specification | Qty | Approx. cost |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC | 1 | ₹450 |
| PZEM-004T v3 AC energy meter (100 A CT) The measurement side sits at mains potential — the opto-isolated UART is the only safe boundary. | 80–260 VAC, 0–100 A, voltage/current/power/energy/PF/frequency, ±0.5 % | 1 | ₹950 |
| ACS712 hall-effect current sensor (20 A) Zero-offset drifts with temperature — re-zero at boot with no load. | ±20 A, 100 mV/A, 80 kHz bandwidth, 1.2 mΩ internal resistance, 2.1 kV isolation | 1 | ₹180 |
| ZMPT101B AC voltage sensor Trim the on-board pot so the idle output sits exactly at Vcc/2. | 0–250 VAC input, 2 mA:2 mA precision transformer, ±1 % linearity | 1 | ₹220 |
| 0.96″ SSD1306 OLED display Static images burn in — invert or scroll the screen periodically. | 128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C | 1 | ₹250 |
| microSD card 32 GB A1 class For 24/7 loggers buy a high-endurance card — normal cards die in months. | A1 rated, 10 MB/s random write, UHS-I, endurance-grade recommended | 1 | ₹450 |
| 5 V 3 A regulated SMPS adapter Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A. | 100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection | 1 | ₹350 |
| Per-machine power meter / CT clamps Split-core CTs clip on without breaking wiring | PZEM-004T (with CT) or split-core CTs sized to each machine's current | 4 | ₹6,400 |
| InfluxDB + Grafana host Or a cloud/self-hosted stack | A small server/Pi running the time-series DB and dashboard | 1 | ₹4,500 |
| DIN enclosure + isolation | Safe enclosure, fusing and isolation for mains-side metering | 1 | ₹800 |
| Three-phase meter (optional) Match to the machine's supply | For three-phase machines, a suitable 3-phase meter | 1 | ₹2,000 |
Estimated total: ₹16,550, excluding tools, shipping and consumables.
Tools and consumables
- Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
- Digital multimeter — continuity, DC volts and current ranges
- Wire strippers, flush cutters and a small set of precision screwdrivers
- Heat-shrink tubing and a heat gun (or a lighter, carefully)
- A laptop with a USB port and the toolchain listed above
Hardware Specifications
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC | 3.3 V logic / 5 V USB | UART, SPI, I²C, I²S, CAN, PWM | Datasheet |
| PZEM-004T v3 AC energy meter (100 A CT) | 80–260 VAC, 0–100 A, voltage/current/power/energy/PF/frequency, ±0.5 % | 5 V logic side | UART Modbus-RTU 9600 | Datasheet |
| ACS712 hall-effect current sensor (20 A) | ±20 A, 100 mV/A, 80 kHz bandwidth, 1.2 mΩ internal resistance, 2.1 kV isolation | 5 V | Analogue | Datasheet |
| ZMPT101B AC voltage sensor | 0–250 VAC input, 2 mA:2 mA precision transformer, ±1 % linearity | 5 V | Analogue | Datasheet |
| 0.96″ SSD1306 OLED display | 128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C | 3.3–5 V | I²C (0x3C) | Datasheet |
| microSD card 32 GB A1 class | A1 rated, 10 MB/s random write, UHS-I, endurance-grade recommended | 3.3 V | SDIO / SPI | Datasheet |
| 5 V 3 A regulated SMPS adapter | 100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection | 5 V | DC barrel / USB | Datasheet |
Consolidated electrical and interface specifications for every active part in the build.
Power Budget & Supply Sizing
Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. |
| PZEM-004T v3 AC energy meter (100 A CT) | 5 V logic side | 20 | The measurement side sits at mains potential — the opto-isolated UART is the only safe boundary. |
| ACS712 hall-effect current sensor (20 A) | 5 V | 10 | Zero-offset drifts with temperature — re-zero at boot with no load. |
| ZMPT101B AC voltage sensor | 5 V | 20 | Trim the on-board pot so the idle output sits exactly at Vcc/2. |
| 0.96″ SSD1306 OLED display | 3.3–5 V | 20 | Static images burn in — invert or scroll the screen periodically. |
| microSD card 32 GB A1 class | 3.3 V | 100 | For 24/7 loggers buy a high-endurance card — normal cards die in months. |
| 5 V 3 A regulated SMPS adapter | 5 V | 3000 | Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A. |
Summed typical draw is 3330 mA. With a 1.5× design margin the supply should deliver at least 5000 mA continuously at the stated rail voltage.
Software Requirements & Development Environment
Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.
- Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
- Add
https://espressif.github.io/arduino-esp32/package_esp32_index.jsonunder File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager. - Set the correct port under Tools → Port. On Linux add yourself to the
dialoutgroup:sudo usermod -aG dialout $USERand log out and back in. - Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
- Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.
Required libraries
| Library | Why it is needed | Install |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| PubSubClient 2.8 | Lightweight MQTT 3.1.1 client for constrained devices. | Library Manager → "PubSubClient" by Nick O'Leary |
| ModbusMaster 2.0.1 | Modbus-RTU master framing for RS-485 meters and drives. | Library Manager → "ModbusMaster" by Doc Walker |
| Adafruit SSD1306 + GFX 2.5.x | Framebuffer and text/graphics primitives for the OLED. | Library Manager → "Adafruit SSD1306" |
| InfluxDB 2.x + Telegraf 2.7 | Time-series storage with retention policies and downsampling. | docker run -p 8086:8086 influxdb:2.7 |
| Grafana 11.x | Dashboards, threshold alerting and shareable panels. | docker run -p 3000:3000 grafana/grafana-oss |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager → "ArduinoJson" by Benoit Blanchon |
Block Diagram
The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.
Circuit Diagram & Wiring
Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| PZEM-004T | TX/RX | GPIO 16/17 | Real power/energy/V/I/PF (UART/Modbus) |
| CT (alt) | AOUT | GPIO 34 (ADC) | Current (with voltage ref) |
| Voltage ref (ZMPT) | AOUT | GPIO 35 (ADC) | Mains voltage for real power |
| OLED | SDA/SCL | GPIO 21/22 | Live per-machine readout |
| Wi-Fi | on-chip | — | Stream to InfluxDB |
| microSD | SPI | shared + CS | Local buffer |
| 5V supply | +/– | 3V3 reg | Isolated power |
Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.
Wiring explanation
- Prefer an integrated meter module (PZEM-004T) that measures real power and power factor directly; if using bare CTs, you also need a voltage reference and phase to compute real power.
- Split-core CTs clip around a conductor without breaking it; never open the secondary of a CT while primary current flows (dangerous voltage).
- Keep the mains-side metering fused, isolated and enclosed; have a qualified electrician do or verify the installation.
- One meter per machine (or per circuit) so the data is genuinely per-machine, not a shared circuit lump.
- Isolate the low-voltage electronics and its power supply from the mains-side measurement.
System Architecture
Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.
Working Principle
The entire value proposition rests on disaggregation: a single site-level meter reading is nearly useless for action because it averages away everything, while per-machine metering reveals the structure of consumption. Once you can see that machine A draws 40% of the total, that machine B sits at 2 kW all night while "off", and that machine C spikes the site's peak demand every hour, you have specific, quantifiable targets. Energy management is fundamentally "you cannot manage what you cannot measure", and this project supplies the measurement at the resolution where decisions actually live — the individual machine.
Measuring correctly means measuring real power, not just current, which is the most common amateur mistake. Machines are largely inductive loads (motors), so their current and voltage are out of phase; the true power consumed (watts) is the current times voltage times the power factor (the cosine of that phase angle), and it is less than the "apparent power" (volt-amps) that current alone implies. Reading only current over-states consumption and, worse, hides the power-factor story entirely. So the design uses meters that measure real power and power factor directly (or, with bare CTs, adds a voltage reference and computes the phase relationship). Power factor is itself valuable: a poor power factor means the machine draws more current than its real power needs, wasting capacity and often incurring utility penalties, and per-machine PF pinpoints where correction would pay.
With per-machine real-power data flowing into a time-series dashboard, the insights are direct and monetisable. Idle/phantom loads — machines drawing power while nominally off — jump out as flat non-zero baselines overnight, and switching those off is often free money. The true energy hogs are ranked, so efficiency effort goes where it matters. Peak demand events, which drive a big part of many industrial tariffs, become visible and schedulable. And crucially, each fix can be quantified from the same data — you measure the before and after, prove the saving, and justify the next investment. This closed loop of measure-act-verify is what makes an energy dashboard pay for itself rather than being a dashboard nobody looks at.
Per-machine power is also a condition signal. A machine's power draw for a given duty is characteristic; when it drifts up over time — a motor pulling steadily more amps than its baseline for the same work — that often indicates a developing mechanical problem (friction, a dragging bearing, misalignment) or an electrical one, sometimes before vibration or temperature would flag it. So the dashboard learns each machine's baseline profile and alerts on sustained anomalies, adding a maintenance dimension to the energy one. The design is candid about scope: it is an insight and monitoring tool, not billing-grade metering or an electrical-safety device, and its accuracy depends on the meter/CT class and correct, safe installation (mains work carries real danger and often legal requirements for a qualified electrician). Within that honest frame, though, it does something a factory rarely has: it turns one opaque number into a live, per-machine map of where the energy goes — and where the money is being wasted.
The maths behind it
Real vs apparent power (why PF matters)
For an AC load:
apparent power S = V_rms · I_rms (VA)
real power P = V_rms · I_rms · cosφ (W)
power factor PF = cosφ = P / S
Current alone gives S (misleading). Measure P and PF.
Low PF = more current than the real power needs = waste.
Energy and idle load
Energy accumulates real power over time:
E = ∫ P dt (kWh)
Idle/phantom load = P > 0 while the machine should be OFF.
waste_kWh = P_idle · off_hours
saving = waste_kWh · tariff → often free to eliminate.
Baseline anomaly (condition signal)
For a machine's duty state, learn baseline P_base:
P_base ← P_base + α·(P − P_base) (during normal duty)
anomaly if P sustained > k·P_base for the same duty
→ developing mechanical/electrical fault, or left-on.
Compare like-with-like (same duty state).
Program Flowchart
The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.
Assembly Instructions
Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.
Install per-machine metering safely
Fit a real-power meter (PZEM-004T with its CT, or split-core CTs plus a voltage reference) on each machine's supply, enclosed, fused and isolated. Have a qualified electrician do or verify the mains-side work.
Clip split-core CTs around the live conductor without breaking it; never open a CT secondary under load.
Set up collection and storage
Read each meter's real power/energy/V/I/PF with the ESP32 and stream to InfluxDB, with a local buffer so a network drop does not lose data.
Build the dashboard and baselines
Create Grafana panels for per-machine live/historical power, energy, PF and site total, and learn each machine's baseline for anomaly alerts.
Step-by-Step Implementation Guide
Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.
Read real power and detect anomalies
Read real power and PF per machine, accumulate energy, maintain a per-duty baseline, and flag sustained deviations or idle-but-on conditions.
cppenergy-monitor.inostruct Machine { float pBase; float energyKWh; bool baselined; }; // Update baseline during normal duty; flag sustained anomalies. const char* checkMachine(Machine &m, float realW, bool shouldBeOff, float dtHrs) { m.energyKWh += realW/1000.0f * dtHrs; // accumulate energy if (shouldBeOff && realW > IDLE_W) return "idle/phantom load (on while off)"; // free saving if (!m.baselined) { if (realW > MIN_DUTY_W) { m.pBase = realW; m.baselined = true; } return nullptr; } if (realW > MIN_DUTY_W) m.pBase += 0.01f*(realW - m.pBase); // slow baseline if (realW > 1.3f * m.pBase) // 30% over baseline, sustained return "drawing above baseline (check machine)"; return nullptr; }m.energyKWh += realW/1000.0f * dtHrsEnergy is integrated from real power over time, giving the kWh figure that translates directly to cost and savings.if (shouldBeOff && realW > IDLE_W)Power drawn while the machine should be off is flagged as an idle/phantom load — usually the cheapest saving a factory can make.if (realW > MIN_DUTY_W) m.pBase += 0.01f*(realW - m.pBase)The baseline is learned slowly during real duty, so the anomaly test compares each reading against this machine's own normal.if (realW > 1.3f * m.pBase)A sustained draw well above baseline for the same duty flags a developing fault or a machine left running — the condition-monitoring dimension of energy data.Stream, dashboard and quantify savings
Stream readings to InfluxDB, build Grafana panels for per-machine and site trends, and use before/after data to quantify the saving from each fix.
Complete Source Code
The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.
/* ═══════════════════════════════════════════════════════════════
Factory Energy Dashboard — ESP32, per-machine real-power metering
Reads each machine's real power / energy / PF, streams to InfluxDB
for a Grafana dashboard, detects idle/phantom loads and baseline
anomalies, and quantifies waste. Insight tool, not billing metering.
══════════════════════════════════════════════════════════════════ */
#include <WiFi.h>
#include <PZEM004Tv30.h>
#include <HTTPClient.h>
#include <Preferences.h>
#define PZEM_RX 16
#define PZEM_TX 17
#define IDLE_W 30.0f
#define MIN_DUTY_W 100.0f
#define MACHINE "press-1"
PZEM004Tv30 pzem(Serial2, PZEM_RX, PZEM_TX);
Preferences prefs;
float pBase = 0; bool baselined = false;
uint32_t lastMs = 0;
const char* check(float realW, float pf, bool shouldBeOff, float dtHrs) {
if (shouldBeOff && realW > IDLE_W) return "idle/phantom load";
if (!baselined) { if (realW > MIN_DUTY_W){pBase=realW;baselined=true;} return nullptr; }
if (realW > MIN_DUTY_W) pBase += 0.01f*(realW - pBase);
if (realW > 1.3f*pBase) return "above baseline";
if (pf > 0 && pf < 0.7f) return "poor power factor";
return nullptr;
}
void toInflux(float v,float i,float p,float e,float pf,const char*note){
HTTPClient http;
http.begin(String(INFLUX_URL) + "/api/v2/write?bucket=energy&precision=s");
http.addHeader("Authorization", String("Token ") + INFLUX_TOKEN);
http.addHeader("Content-Type","text/plain");
// line protocol: measurement,tags fields
char line[220];
snprintf(line,sizeof line,
"power,machine=%s v=%.1f,i=%.2f,p=%.1f,e=%.3f,pf=%.2f",
MACHINE, v, i, p, e, pf);
http.POST(line);
http.end();
}
void setup(){
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASS);
prefs.begin("energy",true);
pBase=prefs.getFloat("base",0); baselined=pBase>0; prefs.end();
lastMs = millis();
}
void loop(){
uint32_t now = millis();
float dtHrs = (now - lastMs)/3600000.0f; lastMs = now;
float v = pzem.voltage();
float i = pzem.current();
float p = pzem.power(); // REAL power (W)
float e = pzem.energy(); // cumulative kWh
float pf = pzem.pf();
if (!isnan(p)) {
bool shouldBeOff = isOffShift(); // from schedule/relay state
const char *note = check(p, pf, shouldBeOff, dtHrs);
toInflux(v, i, p, e, pf, note);
if (note) publishAlert(MACHINE, note); // anomaly/idle/PF alert
}
delay(5000); // 0.2 Hz per machine
}
Configuration & Calibration
Configuration steps
- Assign one meter per machine and tag its data; set idle/duty thresholds and baseline behaviour.
- Configure InfluxDB (bucket/token) and Grafana panels for per-machine and site views.
- Define off-shift schedules so idle-load detection knows when a machine should be off.
- Set anomaly and power-factor alert thresholds per machine.
Calibration procedure
An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.
Meter accuracy
Verify the meter/CT reads correctly against a reference for a known load; ensure it reports real power and PF, not just current.
Baselines
Capture each machine's normal power profile per duty state before trusting anomaly alerts.
Idle detection
Confirm off-shift/idle detection matches reality so phantom-load alerts are accurate.
Network Architecture & Connectivity
Communication protocol
Each meter streams real power/energy/PF to a time-series database on a few-second cadence; anomalies and idle loads publish alerts. Local buffering covers network drops.
| Topic / endpoint | Direction | Payload |
|---|---|---|
energy/machineX/reading | node → DB | V, I, real power, energy, PF |
energy/machineX/alert | node → ops | idle load / above baseline / poor PF |
energy/machineX/status | node → ops | meter/link health |
Message contract between the device and the broker.
Cloud platform configuration
InfluxDB stores the time series and Grafana visualises per-machine and site energy, rankings, PF and peak demand; alerts drive action, and before/after comparisons quantify savings.
Dashboard setup
Per-machine power/energy/PF trends, a consumer ranking, site total and peak-demand view, and annotations for fixes and their measured savings.
Mobile app integration
Alerts for idle/phantom loads, above-baseline draw, and poor power factor.
Security considerations
- Secure the InfluxDB/Grafana stack and authenticate nodes.
- Keep mains-side metering safely isolated from the low-voltage network.
- Alert on meter/link silence so a blind machine is noticed.
Testing Procedure & Expected Output
Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.
| Test | What you should see |
|---|---|
| Run a machine at known load | Real power/energy/PF match a reference within meter accuracy |
| Leave a machine on while "off" | Idle/phantom-load alert; visible as a non-zero overnight baseline |
| Load a machine above its baseline | Above-baseline anomaly alert |
| Add a poor-PF load | Power-factor alert; PF shown per machine |
| Drop the network | Local buffer holds data; streams when reconnected |
| Fix an idle load and compare | Dashboard quantifies the kWh/cost saving |
Bench-test checklist. If a row fails, stop and fix it before moving on.
Expected output
Grafana shows per-machine and site power/energy trends, PF, and rankings of the biggest consumers; anomalies and idle loads raise alerts.
power,machine=press-1 v=232.1,i=8.4,p=1740.0,e=412.836,pf=0.89
# note: idle/phantom load overnight — 2.1 kW for 8 h = ~16.8 kWh/day wasted
# fix: switch off at shift end -> ~₹X/day saved (tariff x kWh)
A per-machine reading with real power and PF; the annotated note shows an overnight idle load quantified into a daily kWh (and cost) saving — the measure-act-verify loop that makes the dashboard pay.
Troubleshooting: Common Errors & Fixes
Performance Optimisation
- A few-second cadence per machine is ample for energy trends; heavier sampling is unnecessary.
- Read real power/PF from the meter directly rather than computing from raw ADC where possible.
- Buffer locally and backfill so the time series has no gaps.
- Aggregate/downsample in InfluxDB for long-term trends.
- Replace every
delay()with amillis()comparison — blocking delays are the single most common cause of dropped readings. - Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
- Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
- Use
uint8_t/uint16_twhere the range allows; on an 8-bit AVR a 32-bit add costs four times as much. - Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
- Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
- For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.
Safety Precautions
- Mains metering is dangerous — isolate, fuse and enclose, and have a qualified electrician do or verify the work; never open a CT secondary under load.
- This is an insight/monitoring tool, not billing-grade or safety metering; accuracy depends on the meter/CT and installation.
- Keep low-voltage electronics isolated from the mains-side measurement.
- Act on anomalies (which may indicate electrical faults) with appropriate caution and expertise.
- Mains voltage kills. Anything on the load side of the relay is at 230 V. Do not work on a powered circuit, and never leave exposed mains wiring on a bench where someone could touch it.
- Keep at least 6 mm of creepage between the mains and low-voltage sides of any board you make, and never route mains tracks under the microcontroller.
- Have a qualified electrician do the final installation into a consumer unit or wall fitting. In most jurisdictions this is a legal requirement, not a suggestion.
- Fit an RCD/RCBO upstream and fuse the load appropriately for its rating.
- Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
- Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
- Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.
Maintenance
- Verify meter/CT accuracy periodically against a reference.
- Re-baseline after process/machine changes.
- Check the InfluxDB/Grafana stack and buffering are healthy.
- Review and act on idle-load and anomaly alerts, and log the savings.
- Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
- Rotate the microSD card annually and keep an image of the working system. Cards used as loggers wear out silently.
- Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
- Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
- Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.
Future Improvements & Upgrades
A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.
- Add three-phase and sub-metering granularity where needed.
- Add automatic power-factor-correction recommendations per machine.
- Add ML disaggregation to estimate loads from fewer meters.
- Integrate with the maintenance system so power anomalies raise work orders.
- Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
- Add over-the-air firmware updates so you never have to physically reach a deployed node again.
- Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
- Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
- Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
- Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.
Frequently Asked Questions
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.