Created
January 15, 2020 15:30
-
-
Save dotmat/053bfba0af0ff2a7ea9d442266a98a6e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import minimalmodbus | |
import serial | |
powerMeter = minimalmodbus.Instrument('/dev/ttyUSB0', 1) | |
powerMeter.serial.baudrate = 9600 | |
powerMeter.serial.bytesize = 8 | |
powerMeter.serial.parity = serial.PARITY_NONE | |
powerMeter.serial.stopbits = 1 | |
powerMeter.mode = minimalmodbus.MODE_RTU | |
# Print the details of the power meter here, these also include the config needed to talk to the unit. | |
print('Details of the power meter are:') | |
print(powerMeter) | |
def readPowerMeter(): | |
print("Attempting to read power meter") | |
try: | |
voltageReading = powerMeter.read_register(0, 0, 4) | |
ampsReading = powerMeter.read_register(1, 0, 4) | |
wattsReading = powerMeter.read_register(3, 0, 4) | |
frequencyReading = powerMeter.read_register(7, 0, 4) | |
print("Voltage", voltageReading/10) | |
print("Amps", ampsReading/10) | |
print("Watts", wattsReading/10) | |
print("Frequency", frequencyReading/10) | |
except IOError: | |
print("Failed to read from instrument") | |
# Run the function to read the power meter. | |
readPowerMeter() | |
Thanks for this reference code.
The hardware documentation for the PZEM-016 indicates that the current, power, and cumulative energy measurements are contained in two adjacent registers. I could not get the multi-register read to work on the PZEM-016 so used two 16-bit reads instead and shifted the high-16 bits up before adding in the low 16-bits.
e.g.
watts = ((powerMeter.read_register(4, 0, 4) << 16) + powerMeter.read_register(3, 0, 4))/10.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would like to point out a error in the script. for the amps you divided by 10 when it should be 1000 to give proper amperage.