PZEM-004T

Basic tutorial of how to setup a [V3] PZEM-004T current sensor with the Raspberry Pi.

PZEM-004T Datasheet: https://innovatorsguru.com/wp-content/uploads/2019/06/PZEM-004T-V3.0-Datasheet-User-Manual.pdf

PARTS:

CanaKit Raspberry Pi 4 4GB Starter Kit – https://amzn.to/2Jrlbfj

PZEM-004T Kit – https://amzn.to/3bQ7jqB

USB to TTL Converter – https://amzn.to/3nXrsxe

Wiring Harness [US Standard]

3-Wire Power Cord – https://amzn.to/3bR4y8v

Hinged Cord Outlet – https://amzn.to/3bOe1xd

Lamp Cord – https://amzn.to/3itZlox

 

WIRING HARNESS SETUP:

SCHEMATIC:

PZEM-004T  |  USB to TTL Converter

5V <–> 5V

RX <–> TX

TX <–> RX

GND <–> GND

SETUP:

1. Enable Serial Interface

  1. Start raspi-config: sudo raspi-config.
  2. Select option 3 – Interface Options.
  3. Select option P6 – Serial Port.
  4. At the prompt Would you like a login shell to be accessible over serial? answer ‘No’
  5. At the prompt Would you like the serial port hardware to be enabled? answer ‘Yes’
  6. Exit raspi-config and reboot the Pi for changes to take effect.

2. Find USB Serial Device

dmesg | grep tty

3. Install modbus library

sudo pip3 install modbus-tk

CODE:

Github Source: https://gist.github.com/bandaangosta/134c9d84ae9bd317297e96dcc0b9c860

import time
import json
import serial
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu

if __name__ == "__main__":
    try:
        # Connect to the slave
        serial = serial.Serial(
                               port='/dev/ttyUSB0',
                               baudrate=9600,
                               bytesize=8,
                               parity='N',
                               stopbits=1,
                               xonxoff=0
                              )

        master = modbus_rtu.RtuMaster(serial)
        master.set_timeout(2.0)
        master.set_verbose(True)
        # Changing power alarm value to 100 W 
        # master.execute(1, cst.WRITE_SINGLE_REGISTER, 1, output_value=100)
        dict_payload = dict()

        while True:
            data = master.execute(1, cst.READ_INPUT_REGISTERS, 0, 10)

            dict_payload["voltage"]= data[0] / 10.0
            dict_payload["current_A"] = (data[1] + (data[2] << 16)) / 1000.0 # [A]
            dict_payload["power_W"] = (data[3] + (data[4] << 16)) / 10.0 # [W]
            dict_payload["energy_Wh"] = data[5] + (data[6] << 16) # [Wh]
            dict_payload["frequency_Hz"] = data[7] / 10.0 # [Hz]
            dict_payload["power_factor"] = data[8] / 100.0
            dict_payload["alarm"] = data[9] # 0 = no alarm
            str_payload = json.dumps(dict_payload, indent=2)
            print(str_payload)

            time.sleep(1)

        
    except KeyboardInterrupt:
        print('exiting pzem script')
    except Exception as e:
        print(e)
    finally:
        master.close()