How to measure home energy with ESP32 and PZEM
Learn how to integrate the industrial PZEM-004T current sensor with an ESP32 microcontroller to monitor residential electrical consumption in real time.
Summary
- Precise alternating current reading requires proper galvanic isolation between high mains voltage and low-level microcontroller electronics.
- UART communication at TTL logic levels ensures stable and low-power serial data exchange between the energy sensor and the ESP32 board.
- The specialized PZEM004Tv30 library simplifies synchronous requests for critical parameters like voltage, current, frequency, and power factor.
- Continuous transmission of collected data to local platforms or cloud servers enables analytical dashboards updated every second.
- Rigorous exception handling prevents crashes and unexpected firmware reboots on the ESP32 during temporary power fluctuations.
Why monitor electrical consumption with ESP32 and PZEM?
Understanding residential electrical consumption goes far beyond simply looking at the utility bill at the end of the month. In practice, it means identifying hidden villains in your electrical grid, such as appliances in standby mode or devices with compromised efficiency. To structure this measurement accurately, hardware selection makes all the difference. The ESP32 microcontroller, known for its versatility and built-in wireless connectivity, acts as the brain of the system, while the PZEM-004T sensor takes on the role of collecting alternating current electrical quantities with industrial safety and laboratory accuracy.
When dealing with home automation, a major challenge is ensuring monitoring systems do not suffer from instability or communication bottlenecks, similar to the care we apply when fixing timeout errors in Nginx. The ESP32 provides a robust platform based on low-power Wi-Fi and Bluetooth, allowing data to be processed locally before sending it to a central broker or visualization dashboard. This decentralized architecture prevents local network congestion and ensures rapid response times in case of anomalies in electrical consumption.
Understanding the PZEM-004T sensor and galvanic isolation
The PZEM-004T is a compact module designed to measure voltage, current, active power, frequency, and power factor in alternating current networks up to 100 amperes. The major advantage of this component for hobbyist or professional use is its built-in galvanic isolation. In practice, this means the circuit part handling high mains voltage is physically separated by optical barriers from the part connecting to the microcontroller. This protects your ESP32 against surges and prevents severe risks of electric shock when handling the development board.
Integrating industrial sensors into microcontrollers requires extra attention to voltage levels and signal integrity. The PZEM communicates via serial ports using the TTL standard, which translates digital states into voltage variations. Since the ESP32 operates natively at 3.3 volts, it is vital to power the sensor module properly and cross-connect the transmission and reception pins, ensuring that one device's outgoing signal is correctly read as input by the other.
Physical assembly and bench connections
The safe execution of the project begins with assembling the electrical components. Before touching any wire, make sure the main circuit breaker of your electrical panel is turned off. The PZEM-004T sensor uses a toroidal current coil, often called a current transformer or CT, which must be installed around only one of the phase wires feeding the residential circuit or monitored appliance. Never pass both the phase and neutral wires together through the inside of the coil, otherwise magnetic fields will cancel each other out and the current reading will always result in zero.
- Turn off the main power supply at the electrical panel and open the compartment where the main cables are accessible.
- Pass the main residential phase cable through the inside of the current transformer (CT) ring provided with the PZEM.
- Connect the secondary terminals of the current transformer to the specific current input terminals on the PZEM module board.
- Wire the voltage measurement terminals of the PZEM directly to the phase and neutral conductors to allow correct active power calculation.
- Connect the power and serial communication pins (TX and RX) of the PZEM to the corresponding pins on the ESP32 development board.
Writing the reading code with ESP32
With the hardware properly assembled and isolated, the next step is programming the ESP32 to interact with the PZEM module. We will use the Arduino IDE, which features mature libraries for this purpose. The PZEM004Tv30 library manages all the complexity of the data request protocol via the serial port, sending specific byte frames and interpreting binary responses returned by the sensor. In practice, this frees the developer to focus on business logic and transmitting the collected information.
Below is a functional code snippet that initializes hardware serial communication and performs periodic readings of electrical quantities. Note that we use the secondary hardware serial pins on the ESP32 to avoid conflicts with the USB debugging port.
#include <PZEM004Tv30.h>PZEM004Tv30 pzem(Serial2, 16, 17);void setup() { Serial.begin(115200); delay(1000);}void loop() { float voltage = pzem.voltage(); float current = pzem.current(); float power = pzem.power(); float energy = pzem.energy(); float frequency = pzem.frequency(); float pf = pzem.pf(); if(isnan(voltage)){ Serial.println("Error reading PZEM"); } else { Serial.print("Voltage: "); Serial.print(voltage); Serial.println(" V"); Serial.print("Current: "); Serial.print(current); Serial.println(" A"); Serial.print("Power: "); Serial.print(power); Serial.println(" W"); } delay(2000);}Transmitting data via lightweight protocols
Measuring data locally is only half the challenge; the next step involves transmitting it efficiently to a central server or monitoring dashboard. In IoT environments, the MQTT protocol has become the industry standard because it is extremely lightweight and consumes minimal network bandwidth. Unlike traditional HTTP, which opens and closes heavy connections on every request, MQTT maintains a persistent connection and uses a publish-subscribe model, ideal for resource-constrained microcontrollers.
When structuring energy data communication, it is important to ensure temporary Wi-Fi disconnections do not crash the device firmware. The ESP32 can temporarily store readings in RAM or an internal partition if the MQTT broker becomes unavailable. This operational resilience is essential to maintain historical data integrity, ensuring monitoring infrastructure functions with the reliability required in complex distributed software architectures.
Final considerations
Automating residential energy measurement using the ESP32 alongside the PZEM-004T sensor provides an accessible, robust, and high-precision solution for monitoring electricity flow in real time. By combining industrial galvanic isolation with microcontroller communication flexibility and lightweight protocols like MQTT, we build a secure and scalable system. Whether reducing utility bills, identifying operational bottlenecks, or exploring applied electronics, mastering this integration opens doors to truly intelligent automation projects.