Kaliningrad 54.71° N 20.45° E
territwin

Home digital shadow: per-circuit energy monitoring on PZEM-004T + ESP32

Why meter a house per circuit, and how to build a box with seven PZEM-004T V4.0 and an ESP32-S3: test bench, custom firmware, panel, power and enclosure.

12 min read

Building a digital shadow of the house: electricity at seven points — PZEM-004T V4.0, ESP32-S3 and an AI partner.

Seven PZEM-004T modules on one bus with an ESP32-S3 meter my main feed, boiler and water heater. We made it in time for the heating season. In this post: why meter per circuit, the test bench and custom firmware, the panel, power supply and enclosure.

Caution: 230 V. The current transformer (CT) rings and the voltage tap go into the panel, on live house wiring. Don’t try this without experience with electrical installations. My box has no barrier between the 230 V part and the low-voltage part: that is only acceptable for a panel nobody but me has access to.

Why meter electricity per circuit

The outdoor meter shows one number for the whole house. I need to know how the electricity consumption splits up. There are four metering points:

  • main feed: three phases, the whole house;
  • electric boiler: three phases;
  • water heater: one phase, L1;
  • the rest = main feed − boiler − water heater.

That makes seven channels: three for the main feed, three for the boiler and one for the water heater.

The main goal is winter. From the daily energy and the indoor–outdoor temperature difference, you can build a regression and get the house’s heat loss in watts per kelvin. For that, the water heater has to be metered separately: its heat leaves with the hot water instead of heating the house.

Why not an off-the-shelf Wi-Fi meter? I need seven channels in one box and my own firmware. This is the first step toward a digital shadow of the house: real data for each load.

Power wiring diagram for electricity metering: PZEM CT rings on the main feed upstream of the Eaton main breaker, at the output of the boiler RCD and downstream of the water heater breaker, voltage tap through breaker QF

Power wiring diagram (labels in Russian): where the CTs sit and which device switches off what.

How the AI and I worked together

I ran the project together with an AI partner. To keep it from making things up, we had three rules.

The log is the only source. One README file: the current state, the plan with statuses, decisions made, “discussed and rejected”. Every decision has a date and a “rationale” column. Mistakes go in there too, marked with whose mistake it was. A dashboard is built from the log; you can see it in the picture below.

Every number has a source or an “unverified” mark. A datasheet, a measurement, a photo, a part record from the inventory. I wrote my home parts inventory system myself, and now it’s easy to find a part and look up its pinout and datasheet. A number without a source goes into the “Unverified” section and waits to be checked.

One step at a time. We took a step, checked it, noted it in the log and moved on.

Energy monitoring project log dashboard: plan with statuses, decisions made and unverified claims

The dashboard is built from the project log (labels in Russian): plan, decisions, what isn’t verified.

Test bench: one PZEM-004T and custom firmware on the ESP32-S3

I started with a test bench: one ESP32-S3 N16R8 board (YD-ESP32-S3), one PZEM-004T-100A V4.0 and a breadboard. UART on pins GPIO17 (TX) and GPIO18 (RX), 9600 baud, 8N1. The module’s VCC gets 3.3 V from the ESP.

Test bench: ESP32-S3 and PZEM-004T connected with Dupont wires through a breadboard

The bench: ESP32-S3, breadboard and one PZEM. The wire colors are the same as later in the box: VCC orange, RX purple, TX white, GND gray.

The first firmware was Arduino with a ready-made library, and it didn’t work: on the S3 the library didn’t bring up the UART from its constructor, and the module’s reply was only visible on the raw-bytes page /diag. So I switched to ESP-IDF and wrote my own Modbus-RTU code to talk to the PZEM. I passed on ESPHome too: I want one framework for all my ESP32 projects.

The protocol is simple: a six-byte request, CRC16 and a fixed-length response. The whole exchange fits in one function.

src/pzem.c, lines 8–38: CRC16 and the request–response exchange.

// CRC16 Modbus: polynomial 0xA001, initial value 0xFFFF (PZEM manual)
static uint16_t crc16(const uint8_t *d, int n) {
    uint16_t c = 0xFFFF;
    for (int i = 0; i < n; i++) {
        c ^= d[i];
        for (int b = 0; b < 8; b++) c = (c & 1) ? (c >> 1) ^ 0xA001 : c >> 1;
    }
    return c;
}

void pzem_init(int uart_num, int tx_pin, int rx_pin) {
    s_uart = uart_num;
    uart_config_t cfg = {
        .baud_rate = 9600, .data_bits = UART_DATA_8_BITS, .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1, .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, .source_clk = UART_SCLK_DEFAULT,
    };
    uart_driver_install(uart_num, 256, 0, 0, NULL, 0);
    uart_param_config(uart_num, &cfg);
    uart_set_pin(uart_num, tx_pin, rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
}

// Send the request (the CRC is appended here) and read a response of the expected length within 500 ms
int pzem_raw(const uint8_t *req, int req_len, uint8_t *resp, int resp_max) {
    uint8_t buf[16];
    memcpy(buf, req, req_len);
    uint16_t c = crc16(buf, req_len);
    buf[req_len] = c & 0xFF; buf[req_len + 1] = c >> 8;
    uart_flush_input(s_uart);
    uart_write_bytes(s_uart, buf, req_len + 2);
    return uart_read_bytes(s_uart, resp, resp_max, pdMS_TO_TICKS(500));
}

The module returns all its readings for a single request: ten registers, a 25-byte response. The catch is in the 32-bit values: the low word comes first.

src/pzem.c, lines 46–60: reading the ten registers.

bool pzem_read(uint8_t addr, pzem_values_t *v) {
    uint8_t req[6] = {addr, 0x04, 0x00, 0x00, 0x00, 0x0A};
    uint8_t r[25];
    if (pzem_raw(req, 6, r, 25) != 25 || !frame_ok(r, 25) || r[1] != 0x04) return false;
    #define REG(i) ((uint32_t)r[3 + 2 * (i)] << 8 | r[4 + 2 * (i)])
    v->voltage   = REG(0) / 10.0f;
    v->current   = (REG(1) | REG(2) << 16) / 1000.0f;   // the low word comes first
    v->power     = (REG(3) | REG(4) << 16) / 10.0f;
    v->energy_wh = (float)(REG(5) | REG(6) << 16);
    v->frequency = REG(7) / 10.0f;
    v->pf        = REG(8) / 100.0f;
    v->alarm     = REG(9) == 0xFFFF;
    #undef REG
    return true;
}

The first load on the bench was a hair dryer: 226.4 V, 8.33 A, 1886 W, cos φ 1.00. Voltage times current gives the same power the module calculated itself.

Next came the addresses. While a module is alone on the bus, it can be polled at the general address 0xF8. I connected the modules one at a time and wrote each one its own address through the /addr web page: 0x01–0x07. I read the first address back as a check. I labeled the cases: “#1 · 0x01 · CT1” and so on.

Close-up of the PZEM-004T-100A V4.0 board: terminal block, P2 connector and the U3 chip next to the connector

PZEM-004T-100A V4.0. The eight-pin U3 next to the P2 connector is an isolator; we’ll come back to it.

Bench wiring diagram: ESP32-S3, solderless breadboard, PZEM-004T and an extension cord with the CT ring

Bench diagram (labels in Russian): ESP TX (GPIO17) → module RX, module TX → ESP RX (GPIO18), VCC 3.3 V, common GND.

Panel, power supply and enclosure

CT rings. Main feed: on the conductors between the stripped end of the armored cable and the terminals of the Eaton main breaker. Only there does the whole house’s current run through separate conductors. Boiler: at the output of its RCD, after the breaker, because the breaker’s input has jumpers to the banya, a Russian sauna. Water heater: downstream of its breaker. One CT, one phase conductor; N doesn’t go through the CT. Each PZEM takes its voltage from the same phase its CT sits on: from another phase, the power would be calculated with a 120° phase shift.

Voltage tap. Phases L1–L3 come from the Eaton input through a three-pole DEKraft VA-103 C25 breaker; N comes straight from the panel’s neutral bar. This breaker, QF, works as a switch: with it off, you can work in the box without touching the outdoor panel. The tap is protected by 1 A ceramic fuses FU1–FU3 in the box itself.

Three-pole DEKraft VA-103 C25 breaker for the voltage tap to the PZEM box

QF is a DEKraft VA-103 3P C25: phases only, the neutral bypasses it.

Power. The low-voltage part runs off an HLK-5M05: 5 V, 1 A. The math from the datasheets: the ESP32-S3 needs a supply of at least 0.5 A, and at peak, when transmitting over Wi-Fi, it draws 340 mA. The regulator on the board is linear, so the current on 5 V is almost the same as on 3.3 V. The isolators in the seven PZEMs draw fractions of a milliamp. The 5M05 has a twofold margin.

Enclosure. I modeled the base in FreeCAD with a script and printed it on a Bambu Lab P1S. Internal dimensions: 246 × 198 mm, 45 mm deep, built as “base plate + lid”. On the plate: seven PZEMs in a row, WAGO 221 connectors above them, and two 5 × 7 cm boards at the bottom: the 230 V one on the left (FU1–FU3 and the HLK), the low-voltage one with the ESP on the right.

Test fit of the enclosure skeleton: three PZEMs, WAGO connectors and two prototype boards on the printed frame

I printed a skeleton first, to check how the PZEMs, WAGOs and boards fit.

GSMIN 5 × 7 cm prototype board on the printed enclosure base

A 5 × 7 cm board on the base.

  • WAGO slots drawn to another part’s drawing · whose mistake: both. The printed base was ready, but the WAGO 221s didn’t fit the slots. I had sent a photo of a WAGO 221, but the slots got drawn to the 222-413 drawing: we misunderstood each other. Cost: 4 hours of printing. The slots were redone for the 221-413 and 221-415 from my measurements: 19 × 19 and 30 × 19 mm. Lesson: build from the human’s measurements, and ask for clarification when something is ambiguous.
  • PZEM terminals mirrored. On the layout the terminal block was “CT CT N L”, but on the actual board the power is on the two left terminals. I caught it during assembly. Now it’s “L N CT CT”, and all the diagrams have been redrawn.
  • An extra Lx bus. While the water heater’s phase was unknown, a separate bus got drawn for it “just in case”. The water heater turned out to be on L1, and the bus was removed. Its slot in the printed enclosure still sits empty.

Mounting seven PZEM-004T modules in the printed enclosure, cables to the P2 connectors

Modules on standoffs; the cables to P2 are crimped from Dupont wires.

The assembled electricity metering box: seven PZEM-004T, WAGO connectors, the 230 V board with the HLK-5M05 and the board with the ESP32-S3

The assembled box. The fuses here are still glass; I later replaced them with ceramic ones.

PZEM box layout: modules, WAGO connectors, 230 V and low-voltage boards, wire routes

Box layout in millimeters, with wire routes (labels in Russian).

Seven PZEM modules on one bus: silence

We assembled the box and tested it on the table: the three phases jumpered to a plug, N to N. The ESP booted from the HLK, Wi-Fi was up. The D3 LED by the P2 connector blinked on all seven modules, so the requests were getting through. But there was no reply. The /scan page went through addresses 0x01–0x07, and none of them answered. The /diag?a=1 page showed 0 bytes.

The /scan page of the PZEM hub firmware: addresses 0x01–0x07, all with “no reply”

/scan (labels in Russian): none of the seven answers.

I unplugged every P2 connector except the first. /diag?a=1 immediately returned a full response: 25 bytes, 237.4 V, 50.0 Hz, current 0. So the TX and RX wiring and the firmware were right, and something broke when there was more than one module on the bus.

The /diag page: a 25-byte response from one PZEM-004T module

The same request with one module: 25 bytes, 237.4 V and 50.0 Hz (labels in Russian).

With one module there’s a reply; with seven, silence. Why, and what the U3 by the connector has to do with it, I’ll explain in the next post.

To be continued.