Knowing exactly how much electricity your home uses is the first step to cutting the bill. In this guide you will build a DIY energy monitor with an ESP32 and a PZEM-004T v3 sensor that sends voltage, current, power, energy, frequency and power factor to Home Assistant over MQTT. The sensors appear automatically through MQTT discovery, and the energy counter plugs straight into the Home Assistant Energy dashboard.
The project is built from inexpensive modules and open-source software. Everything stays on your local network, with no cloud account required.
What you need
| Part | Notes |
|---|---|
| ESP32 development board | Any ESP32 DevKit with UART2 pins (GPIO16 and GPIO17). |
| PZEM-004T v3 module | Choose the 10 A version (direct connection) or the 100 A version (external split-core CT). See the next section. |
| 5 V power supply | A certified USB charger, or an enclosed, certified isolated 230 V to 5 V module. |
| Resistors 1 kΩ and 2 kΩ | Voltage divider for the PZEM TX line (5 V to about 3.3 V). |
| Small fuse or breaker (about 2 A) | Protects the voltage-sense wires of the PZEM. |
| Insulated enclosure | A DIN-rail box keeps mains and low-voltage parts apart and out of reach. |
| Home Assistant with the Mosquitto broker | Any install type that supports add-ons, or an external MQTT broker. |
Safety first
Warning: mains voltage can kill. If you are not qualified to work on your electrical panel, ask a licensed electrician to do the mains-side connections. Local regulations may require it.
- Switch off the main breaker and prove the circuit is dead with a voltage tester before touching any wire.
- Never work alone on a live installation.
- Keep mains wiring physically separated from the ESP32 and the low-voltage side, inside a closed insulated enclosure.
- Protect the voltage-sense wires with a small dedicated fuse or breaker.
- If you use the CT version, never leave the clamp around a live conductor with its leads disconnected from the module.
- Measure only a single conductor with the CT (the live wire), never the whole cable with live and neutral together.
Choose the right PZEM-004T v3 version
Two versions look similar but are wired differently:
- 10 A version: the load current flows through the module terminals, so it sits in series with the live wire. Good for a single appliance or a small circuit.
- 100 A version: the module only senses voltage on its L and N terminals, and the current is measured by an external split-core current transformer (CT) clamped around the live wire. This is the safer choice for a whole-home meter because you do not cut the main conductor.
The module works from about 80 V to 260 V AC, so it can also be used on 120 V systems. For a three-phase installation use one module per phase.
Wiring
Low-voltage side (ESP32 to PZEM)
| PZEM-004T pin | ESP32 pin | Note |
|---|---|---|
| 5V | VIN / 5V | Powers the PZEM serial interface. |
| GND | GND | Common ground. |
| TX | GPIO16 (RX2) | Through the voltage divider: PZEM TX → 1 kΩ → GPIO16, and GPIO16 → 2 kΩ → GND. |
| RX | GPIO17 (TX2) | Direct connection. |
The PZEM serial interface is powered from 5 V, so treat its TX output as a 5 V signal. The ESP32 inputs are not 5 V tolerant, which is why the divider (or a logic-level shifter) is recommended.
Mains side
- Voltage sensing: connect the live (L) and neutral (N) terminals of the PZEM to the circuit you want to measure, through the small fuse or breaker.
- 10 A version: route the live wire of the monitored circuit through the PZEM load terminals, in series.
- 100 A version: clamp the CT around the live wire of the monitored circuit only. Make sure the CT arrow or label direction matches the module instructions, and close the clamp fully.
- Close and secure the enclosure before restoring power.
The ESP32 code
Install these libraries from the Arduino IDE Library Manager:
PZEM-004T-v30by Jakub MandulaPubSubClientby Nick O’Leary
Select your ESP32 board, paste the sketch, replace the placeholder Wi-Fi and MQTT credentials, and upload it.
/*
ESP32 + PZEM-004T v3 -> MQTT -> Home Assistant (auto-discovery)
Libraries: PZEM004Tv30 (mandulaj), PubSubClient (Nick O'Leary)
Board: any ESP32 dev board. PZEM is read over UART2.
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include <PZEM004Tv30.h>
// ---------- User settings ----------
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST = "192.168.1.100"; // IP of your Home Assistant / MQTT broker
const uint16_t MQTT_PORT = 1883;
const char* MQTT_USER = "esp32_energy";
const char* MQTT_PASS = "YOUR_MQTT_PASSWORD";
const char* NODE_ID = "energy_meter"; // used in topics and unique IDs
const unsigned long PUBLISH_INTERVAL_MS = 10000;
// UART2: ESP32 GPIO16 (RX2) <- PZEM TX, ESP32 GPIO17 (TX2) -> PZEM RX
const int PZEM_RX_PIN = 16;
const int PZEM_TX_PIN = 17;
PZEM004Tv30 pzem(Serial2, PZEM_RX_PIN, PZEM_TX_PIN);
WiFiClient wifiClient;
PubSubClient mqtt(wifiClient);
String baseTopic; // e.g. energy_meter
String availTopic; // e.g. energy_meter/status
unsigned long lastPublish = 0;
unsigned long lastMqttAttempt = 0;
unsigned long lastWifiAttempt = 0;
struct SensorDef {
const char* key;
const char* name;
const char* unit;
const char* deviceClass;
const char* stateClass;
};
const SensorDef SENSORS[] = {
{"voltage", "Voltage", "V", "voltage", "measurement"},
{"current", "Current", "A", "current", "measurement"},
{"power", "Power", "W", "power", "measurement"},
{"energy", "Energy", "kWh", "energy", "total_increasing"},
{"frequency", "Frequency", "Hz", "frequency", "measurement"},
{"pf", "Power factor", "", "power_factor", "measurement"}
};
void publishDiscovery() {
for (const SensorDef& s : SENSORS) {
String topic = String("homeassistant/sensor/") + NODE_ID + "/" + s.key + "/config";
String json = "{";
json += "\"name\":\"" + String(s.name) + "\",";
json += "\"unique_id\":\"" + String(NODE_ID) + "_" + s.key + "\",";
json += "\"state_topic\":\"" + baseTopic + "/" + s.key + "\",";
json += "\"availability_topic\":\"" + availTopic + "\",";
json += "\"device_class\":\"" + String(s.deviceClass) + "\",";
json += "\"state_class\":\"" + String(s.stateClass) + "\",";
if (strlen(s.unit) > 0) {
json += "\"unit_of_measurement\":\"" + String(s.unit) + "\",";
}
json += "\"device\":{\"identifiers\":[\"" + String(NODE_ID) + "\"],";
json += "\"name\":\"ESP32 Energy Monitor\",\"manufacturer\":\"DIY\",";
json += "\"model\":\"ESP32 + PZEM-004T v3\"}}";
mqtt.publish(topic.c_str(), json.c_str(), true); // retained
}
}
bool connectMqtt() {
String clientId = String("esp32-") + NODE_ID + "-" + String((uint32_t)ESP.getEfuseMac(), HEX);
// Last Will: Home Assistant shows the sensors as "unavailable" if the ESP32 drops offline
if (!mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS,
availTopic.c_str(), 0, true, "offline")) {
Serial.printf("MQTT connect failed, rc=%d\n", mqtt.state());
return false;
}
mqtt.publish(availTopic.c_str(), "online", true);
publishDiscovery();
Serial.println("MQTT connected, discovery published.");
return true;
}
void publishValue(const char* key, float value, uint8_t decimals) {
if (isnan(value)) return;
char payload[16];
snprintf(payload, sizeof(payload), "%.*f", decimals, value);
String topic = baseTopic + "/" + key;
mqtt.publish(topic.c_str(), payload);
}
void readAndPublish() {
float voltage = pzem.voltage();
if (isnan(voltage)) {
Serial.println("PZEM read failed - check wiring, 5V supply and mains voltage.");
return;
}
publishValue("voltage", voltage, 1);
publishValue("current", pzem.current(), 3);
publishValue("power", pzem.power(), 1);
publishValue("energy", pzem.energy(), 3); // kWh, stored inside the PZEM
publishValue("frequency", pzem.frequency(), 1);
publishValue("pf", pzem.pf(), 2);
Serial.printf("V=%.1f P=%.1f W\n", voltage, pzem.power());
}
void startWifi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED && millis() - start < 20000) {
delay(500);
Serial.print(".");
}
Serial.println(WiFi.status() == WL_CONNECTED ? " connected" : " failed (will retry)");
}
void setup() {
Serial.begin(115200);
baseTopic = String(NODE_ID);
availTopic = baseTopic + "/status";
startWifi();
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setBufferSize(1024); // discovery messages are larger than the 256-byte default
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
if (millis() - lastWifiAttempt > 10000) {
lastWifiAttempt = millis();
WiFi.disconnect();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
return;
}
if (!mqtt.connected()) {
if (millis() - lastMqttAttempt > 5000) {
lastMqttAttempt = millis();
connectMqtt();
}
} else {
mqtt.loop();
if (millis() - lastPublish >= PUBLISH_INTERVAL_MS) {
lastPublish = millis();
readAndPublish();
}
}
}
How the code works
- MQTT discovery: on every connection the ESP32 publishes a retained configuration message for each sensor, so Home Assistant creates the entities automatically. No YAML is needed.
- Larger MQTT buffer:
setBufferSize(1024)is required because the default PubSubClient buffer (256 bytes) is too small for discovery messages. - Availability: a Last Will message marks the sensors as unavailable in Home Assistant if the ESP32 loses power or Wi-Fi.
- Non-blocking reconnects: Wi-Fi and MQTT reconnect without freezing the main loop.
- Safe readings: the sketch skips a publish cycle when the PZEM returns an invalid value (NaN) instead of sending bad data.
- Energy counter: the cumulative kWh value is stored inside the PZEM, so it survives ESP32 restarts. The
total_increasingstate class lets Home Assistant handle it correctly.
Set up Home Assistant
Step 1: Install the MQTT broker
Go to Settings → Add-ons → Add-on Store, install Mosquitto broker, and start it. Then open Settings → Devices & Services and configure the discovered MQTT integration.
Step 2: Create an MQTT user
Open Settings → People → Users (enable Advanced Mode in your profile if the Users tab is hidden) and create a dedicated user such as esp32_energy with a strong password. Enable Can only log in from the local network. Use these credentials in the sketch.
Step 3: Check that the device appears
Power the ESP32 and watch the Serial Monitor at 115200 baud. After a few seconds ESP32 Energy Monitor appears under the MQTT integration with six entities: voltage, current, power, energy, frequency and power factor.
Add it to the Energy dashboard
- Open Settings → Dashboards → Energy.
- Under Electricity grid, choose Add consumption.
- Select the Energy sensor of your monitor.
Home Assistant starts building daily, weekly and monthly consumption charts, and you can add your electricity price to see the cost.
Validate the accuracy
Do not trust any meter blindly. Before relying on the numbers, compare the monitor with a reference:
- Plug a known resistive load (for example a kettle or heater with a rated power on its label) on the monitored circuit.
- Compare the Power reading with the rated power and, if you have one, with a plug-in wattmeter.
- Compare the cumulative kWh against your utility meter over a full day.
The manufacturer specifies roughly a 1% accuracy class, but real-world results depend on installation, load type and CT placement. Note your own measurements and keep them with the project.
Automation example: high-power alert
This Home Assistant automation sends a notification when consumption stays above 5 kW for one minute. Replace the entity ID with the one shown in your installation.
alias: High power alert
description: Notify me if the house draws more than 5 kW for one minute
trigger:
- platform: numeric_state
entity_id: sensor.esp32_energy_monitor_power
above: 5000
for: "00:01:00"
action:
- service: notify.notify
data:
message: "Power draw has been above 5 kW for a minute."
mode: single
Troubleshooting
| Symptom | Likely cause and fix |
|---|---|
| Serial Monitor shows "PZEM read failed" | Check the 5 V and GND connections, swap the TX/RX wires, and confirm the module is connected to live mains voltage. |
| MQTT connect fails (rc=5) | Wrong MQTT username or password. Recreate the Home Assistant user and update the sketch. |
| No device appears in Home Assistant | Check that the MQTT integration is set up, the buffer size line is present, and the broker IP is correct. |
| Current stays at 0 A (100 A version) | The CT is not closed, is on the neutral wire, or clamps both live and neutral together. |
| Readings jump or the sketch hangs | Use a stable 5 V supply and keep the serial wires short and away from mains cables. |
| I want to reset the kWh counter | Call pzem.resetEnergy() once from a temporary sketch, then upload the normal sketch again. |
Frequently asked questions
Can I measure my whole house with this?
Yes, with the 100 A version and its split-core CT on the main live conductor, installed by a qualified person. The 10 A version is better for individual appliances or small circuits.
Does it work without internet?
Yes. The ESP32, the MQTT broker and Home Assistant all communicate on your local network.
Can I use it on a three-phase supply?
Use one PZEM-004T module and one CT per phase, and give each module its own serial connection or address. See the library examples for multiple devices.
Why does the energy value not drop to zero after a reboot?
The PZEM stores cumulative energy in its own memory. Only a manual reset command clears it.
What to build next
- Build a smart solar EV charger with ESP32 and Home Assistant
- Build your own Matter smart plug with an ESP32
- ESP32-S3 offline voice control for a smart home
- DIY smart bench power supply with ESP32 control and data logging
Browse more in our hubs: Power & Energy projects and ESP32 Smart Home projects.
Conclusion
With an ESP32, a PZEM-004T v3 and Home Assistant you get a local, private energy monitor with live power data, history and Energy dashboard support. Start with a single appliance to learn the setup, then extend it to your whole panel once you are comfortable with the mains-side work. Questions about wiring, MQTT or the code? Leave a comment below.

No comments
Post a Comment