Press ESC to close

Home Assistant: Measure electricity with PZEM004T

Hello!

Configuring the monitoring of electricity consumption is a key element in building a smart home. Some time ago I described how to integrate Eastron’s single-phase energy meter with your home automation system, and if you haven’t seen it yet, I encourage you to read that article. Today, we’re going a step further and will cover how to configure the PZEM004T v3 module with ESPHome. In this article, I’ll show you step-by-step how to connect it to Home Assistant so you can precisely monitor your home’s electricity consumption.

Ready? Here we go! 🚀

What is the ESP8266 NodeMCU?

ESP8266, boardThe ESP8266 NodeMCU is a small but extremely powerful development board based on the popular ESP8266 chip from Espressif. Equipped with an integrated Wi-Fi module operating at 802.11 b/g/n, it allows easy connection to existing wireless networks and communication with other devices over the Internet.

At the heart of the board is a 32-bit Tensilica L106 processor at 80-160 MHz and 64 KiB of instruction memory and 96 KiB of data memory. The NodeMCU has a built-in USB-UART converter (CP2102), so it can be easily connected to a computer and programmed using the Arduino IDE or other environment.

A key advantage is the existence of as many as 17 GPIO (General-Purpose Input/Output) pins, which can be freely used as digital I/O or assigned other functions, such as I2C, SPI, UART, etc. This allows communication and control of all kinds of sensors, displays and executive devices.

Despite its compact size and low price, the ESP8266 NodeMCU has great potential in DIY and Internet of Things projects thanks to its strong capabilities, low cost and excellent community support.

What is ESPHome?

ESPHome, Nowe logo

ESPHome is a powerful, open source development environment designed specifically for devices based on the popular ESP8266 and ESP32 microcontrollers. Its main goal is to facilitate the creation of smart Internet of Things (IoT) devices, which can then be fully integrated and controlled through the Home Assistant platform.

Configuration of devices in ESPHome is done through friendly files in YAML format, which allow defining the operation of various components, sensors, displays or actuators. This makes programming intuitive and accessible even to those without in-depth coding knowledge.

In addition to native integration with Home Assistant, ESPHome also supports a wide range of off-the-shelf modules and libraries, allowing it to support many popular other components.

Preparation

Before diving into system adaptation using ESP and ESPHome, it’s a good idea to prepare properly. Below you will find key steps to get your project started.

Make sure you have all the necessary materials:

  • ESP8266 NodeMCU board (or ESP32, if you opt for a newer model),
    • It is worth verifying before purchasing an ESP board that Wi-Fi coverage reaches our installation site. We may need to purchase a board with the ability to connect an external antenna.
  • PZEM004T v3 – single-phase electricity meter (Link to shop),
  • Power source for the ESP board (5V DC),
  • Wire connectors,
  • (Optional) DIN box in which to hide the ESP board with the converter module,
  • Connection wires for all components.

Installing ESPHome in Home Assistant

Install ESPHome in your Home Assistant environment to easily configure and manage the ESP8266. Use the ESPHome documentation and follow the instructions.

Preparation of workspace

Organize a workspace where you will assemble the system. Make sure you have access to tools and are comfortable working on the project.

Health and safety of working with electric voltage

Warning pictogramElectrical safety is key when working with electricity. Here are some important recommendations:

  • Power Off: Before any work on the circuit, turn off the power supply to avoid electric shock.
  • Appropriate Tools: Use tools that are insulated and designed for electrical work – they should meet appropriate safety standards.
  • Experience: Electrical installation work requires experience. If you are unsure of your skills, it is advisable to enlist the help of an experienced person.
  • Eye and Hand Protection: Wearing eye and hand protection is recommended, especially when soldering and handling connections.
  • Check the Power Supply: Make sure you know where the main power supply is and that it is off before taking any action.
  • Knowledge of the Electrical System: Always verify that you know how an electrical system works. Do not take action blindly.

Step 1 – VLAN IoT

As a security practice, I recommend setting up a separate network for IoT devices, separate from the main home network. For this purpose, it is worth using the VLAN (Virtual Local Area Network) function, which allows physical separation of devices, such as those based on ESPHome, from other devices in the home infrastructure.

Benefits

Cloud icon as VLAN

Creating a dedicated network for IoT devices offers several advantages:

  • Security: Separating IoT devices from the main network haelps minimize the potential risk of attacks. If an IoT device is possibly compromised, access to the main home network is difficult.
  • Controlling Communications: Creating a separate network allows for more precise control over who communicates with IoT devices and how. You can define communication rules that only allow specific devices (for example, a server or virtual machine from Home Assistant) to interact with IoT devices.
  • Network Traffic Optimization: Separating IoT device traffic from main network traffic can help optimize network performance.

Implementation

To implement such separation, it is worth consulting the documentation and settings of the router. In the case of Home Assistant, using the appropriate firewall rules on the router, you can customize access to IoT devices. This approach introduces a layer of additional security to our smart home infrastructure.

Step 2 – Install and configure firmware to work with Home Assistant

Once you run the ESPHome add-on on the Home Assistant server, you can proceed to add your first ESPHome-based device.

Connecting to a computer

  • Connect the board using a USB cable to your computer. It is important to use a USB cable with data transmission, as many cheap cables only provide power.
    • To be sure of correct operation, I recommend using Chrome or Edge browser (there is a transfer of data transmission through the COM port to the browser using WebSerial).

Home Assistant

  • After completing these steps, log in to Home Assistant,

Home Assistant, login screen

  • From the side panel, go to the ESPHome tab,
  • Then click New Device,

ESPHome, Button New device

  • After selecting the option to add a new device, we may encounter a browser incompatibility message, especially for browsers that do not support WebSerial. Alternatively, we may also encounter a message indicating that there is no secure connection (HTTPS) to the dashboard. In this situation, we can click Continue to continue the process of adding the device.

ESPHome, New device

  • In the next window, we enter a name for our device (it can be a name or alias we created) and the details of our Wi-Fi network.
    • Wi-Fi network entry is only necessary when adding a device for the first time. Subsequent ESPHome-based additions will not require this step.
  • Then, for ESPHome to install the firmware on the ESP8266 board, click Connect.

ESPHome, Installation

  • After a while, the browser will display a window for selecting a device for serial port communication. Find your device, whose name should include CP210x UART, and click Connect.
  • Then wait until the firmware is installed on the board.

Completion of the process

After a successful installation, you should receive a message confirming the completion of the process. Your device will also appear on the dashboard with the description ONLINE. This means that the board has been correctly configured and is ready to proceed.

Step 3 – Mount the module

Connecting the PZEM004T v3 energy meter to the electrical system requires accuracy and following proper safety procedures.

Types of modules

When installing the module, it is worth noting the two types of models available: supporting currents up to 10A and up to 100A. The difference between them lies mainly in the way the current transformer (CT) is connected.

  • 10A version: The module contains a built-in current sensor that directly measures the current flowing through the circuit. This is simpler to install, but limited to circuits that do not exceed 10A.

  • 100A version: This version uses an external current transformer (CT), which is more flexible for installation. This transformer must be mounted on the phase conductor, and has the advantage that it can be easily attached to the existing conductor without disconnecting the installation. It is ideal for monitoring larger circuits with currents up to 100A.

The installation method described will be based on the 100A version using a current transformer.

Preparation

  • Location selection: The PZEM004T v3 module does not have a display, so you don’t need to install it in a location that is easily accessible for reading data. You can mount it in any safe location near the circuit you want to monitor. However, it is important that the mounting location is dry, well ventilated and complies with local electrical codes.
  • Installation preparation: Turn off the power to the electrical circuit where you will be installing the meter. Always make sure you work in a de-energized condition to avoid the risk of electric shock. Check that the wires are dry and free from damage.
  • Module installation: Mount the PZEM004T v3 in the desired location using the fasteners of your choice. Make sure the module is firmly attached to avoid accidental damage during use.

Actions

  • Connecting electrical wires:
    • Current transformer (CT): The current transformer (split-core) should be installed on the phase conductor (L) of the circuit you wish to monitor. Ensure that the arrow on the transformer housing points in the direction of the current flow, from the energy source to the load. This positioning is crucial for accurate readings. Unlike a standard conductor, the CT doesn’t carry the current directly through itself. Instead, it detects the magnetic field generated by the current flow, enabling it to measure the current without interrupting the circuit.
    • Phase wire (L): The phase wire connected to the PZEM004T module doesn’t carry the full load of current; its primary role is to measure the voltage in the circuit. It should be connected to the designated terminal on the module, as indicated by the markings. Proper connection of the phase wire ensures that the meter can accurately monitor the voltage in the system.
    • Neutral (N) wire: The neutral wire is used for voltage measurement in the system and must be connected to the appropriate terminal on the PZEM004T module. Unlike the phase wire, the neutral does not pass through the current transformer (CT), but its connection is essential for accurate voltage measurements and overall functionality of the monitoring system.
  • Power on: Once the connection is complete, power up the circuit and verify that the module is working properly. PZEM004T v3 communicates via UART, so verification of proper operation will be through readings in ESPHome or Home Assistant.

Recommendations

  • Checking connections: Make sure all wires are securely fastened and connections are well insulated. Loose connections can lead to incorrect readings or pose a safety hazard.
  • Testing: Check that all parameters are correctly reported by the module in the monitoring system. You can run load tests to make sure the meter is accurately monitoring power consumption.
  • Use of cable ferrules: Crimping ferrules should be applied to the ends of cable wires to prevent them from fraying during terminal installation. By using these sleeves, you ensure a more durable connection, improve electrical contact, and protect the wires from mechanical damage that can occur while tightening the terminals.

Step 4 – Connect the module to the board

  • Connect the 5V on PZEM-004T to pin 5V on board.
  • Connect the GND on PZEM-004T to pin GND on board.
  • Connect the RXon PZEM-004T to pin RX on board ESP8266 (or another pin according to the configuration).
  • Connect the TX on PZEM-004T to pin RX on board ESP8266 (or another pin according to the configuration).

Checking connections:

  • Make sure to connect all wires firmly and correctly assign them to their respective pins (5V, GND, RX, TX).
  • Verify that the communication wires (RX, TX) are in the correct order, as proper connection is key for UART communication.
  • Check that the board contacts do not touch metal (possibly) parts of the case or other wires that could damage your electronics.
  • Connect the installation to the power supply.
  • Wait for the board to connect to your Wi-Fi network.

Step 5 – Upload the code in ESPHome

In this section, we will now upload the relevant entries for configuring the connection to the electricity meter. Copy the necessary code elements into your installation.
esphome:
  name: esp06-pzemac
  comment: "I like pancakes"
  area: "Roof" 
#  on_boot: 
#    then:
#      - pzemac.reset_energy: pzemac_wardrobe

esp8266:
  board: esp01_1m

# Enable logging
logger:
  baud_rate: 0

web_server:
  port: 80

# Enable Home Assistant API
api:
  encryption:
    key: "HERE WILL BE THE CODE GENERATED BY ESPHOME"

ota:
  - platform: esphome
    password: "HERE WILL APPEAR THE PASSWORD GENERATED BY ESPHOME"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Esp06-Roof Fallback Hotspot"
    password: "123456789"

captive_portal:
    
uart:
  tx_pin: RX
  rx_pin: TX
  baud_rate: 9600
  stop_bits: 1

modbus: 

button:
  - platform: restart
    name: "Restart device"   

sensor:
  - platform: pzemac
    address: 1
    current:
      name: "Current"
      id: "pzem_current"
      unit_of_measurement: "A"
    voltage:
      name: "Voltage"
      id: "pzem_voltage"
      unit_of_measurement: "V"
    energy:
      name: "Energy"
      id: "pzem_energy"
      unit_of_measurement: "kWh"
      accuracy_decimals: 2
      filters:
        - lambda: return x / 1000.0;
    power:
      name: "Power"
      id: "pzem_power"
      unit_of_measurement: "W"
    frequency:
      name: "Frequency"
      id: "pzem_frequency"
      unit_of_measurement: "Hz"
    power_factor:
      name: "Power Factor"
      id: "pzem_power_factor"
      unit_of_measurement: "%"
    update_interval: 10s
    id: "pzemac_roof"
  - platform: wifi_signal
    name: "Wi-Fi Signal"
    update_interval: 60s

binary_sensor:
  - platform: status
    name: "Connection status"  
  • We’re now waiting for the software to compile and upload to the board. After the installation finishes successfully, the log preview shows a summary of your board’s configuration, allowing you to verify that everything is set up correctly.

Step 6 – Reverse proxy on Synology using Nginx Proxy Manager

Do you use Synology and want to improve access to your Home Assistant server? Here’s a quick step-by-step guide on how to set up a login using a domain name and subdomain, such as ha.xyz.com, instead of entering an IP address. You can achieve all this with Docker Compose in the Portainer.

👉 Check it out now and get your environment ready for more improvements!

Thus, by using a domain name instead of an IP address, you simplify the process of logging into your Home Assistant server on Synology.

Step 7 – Adding a device to Home Assistant

  • In the Home Assistant notification section, you’ll notice that our home automation server has detected a new device,
  • Next, navigate to Settings, then to Integrations and Devices,
  • You’ll see the new device highlighted with a blue border. Approve the new device for integration.
  • Set the area where the device will be located.
  • Congratulations! You’ve made it to this stage, which means you’ve successfully completed the configuration process. Now it’s time to test your new device! Head over to it and check the parameters measured by the electricity metering module directly from Home Assistant. 🚀
  • Depending on the set reporting time – wait a while until the module installed at the ESP board detects the values measured by the meter. You can preview the raw data from the logs in ESPHome.

Good luck!

If you have additional questions about the setup, go ahead and leave a comment under this article or contact me directly. I will be happy to answer any concerns and help solve any problems. Your questions can help improve this guide for other users.

Additional materials and information

Electricity meter reset

If you want to reset the energy (kWh) meter and delete the stored data, you can use the reset function available in ESPHome. In the code, you can add a section on_boot, which will automatically reset the counter every time the device is started. Such a record looks like this:

on_boot:
  then:
    - pzemac.reset_energy: pzemac_roof

This will reset the energy meter to zero, allowing you to start new measurements from zero, for example, after the end of a particular billing period or after testing. This is useful when you want to start tracking energy consumption from scratch, without having to reset it manually.

If you need to reset the kWh value once, you can temporarily add this section to your code, start the device, and then delete or “comment out” (#) the code to remember the new values in the future.

Useful links

For further exploration and detailed information, I recommend checking out the links below. They are valuable sources that were used in the development of this guide.

Filip Chochół

Filip Chochol runs two blogs: personal “chochol.io” and together with his girlfriend “Warsaw Travelers” about travel. He specializes in IT resource management and technical support, and has been active in the field of cyber security awareness for almost two years. A proponent of open-source technologies, he previously worked in the film and television industry in the camera division (2013-2021). After hours, he develops interests in smart homes and networking.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.