Advertisement
-KARMA-

PZEM-004T

Mar 22nd, 2023 (edited)
790
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1. from pymodbus.client import ModbusSerialClient as ModbusClient
  2.  
  3. client = ModbusClient(method = "rtu", port = "/dev/ttyUSB0", stopbits = 1, bytesize = 8, parity = 'N', baudrate= 9600)
  4.  
  5. connection = client.connect()
  6.  
  7. #Polling the first device
  8. result = client.read_input_registers(0, 10, 1)
  9.  
  10. #Polling N device
  11. #result = client.read_input_registers(0, 10, N)
  12.  
  13. #Voltage
  14. print(result.registers[0])
  15. #Current
  16. print(result.registers[1] + (result.registers[2] << 16))
  17. #Power
  18. print(result.registers[3] + (result.registers[4] << 16))
  19. #Energy
  20. print(result.registers[5] + (result.registers[6] << 16))
  21. #Frequency
  22. print(result.registers[7])
  23. #Power factor
  24. print(result.registers[8])
  25.  
  26. client.close()
Advertisement
Comments
  • iero
    1 year
    # Python 1.56 KB | 1 0
    1. Наверное  примерно так
    2. from pymodbus.client import ModbusSerialClient as ModbusClient
    3. import json
    4.  
    5. devices = [
    6.     {"name": "device1", "id": 1},
    7.     {"name": "device2", "id": 2},
    8.     {"name": "device3", "id": 3},
    9.     {"name": "device4", "id": 4},
    10.     {"name": "device5", "id": 5}
    11. ]
    12.  
    13. data = []
    14. errors = []
    15.  
    16. client = ModbusClient(method="rtu", port="/dev/ttyUSB0", stopbits=1, bytesize=8, parity='N', baudrate=9600)
    17.  
    18. try:
    19.     connection = client.connect()
    20.     for device in devices:
    21.         try:
    22.             result = client.read_input_registers(0, 10, device["id"])
    23.             voltage = result.registers[0] / 10
    24.             current = (result.registers[1] + (result.registers[2] << 16)) / 1000
    25.             power = (result.registers[3] + (result.registers[4] << 16)) / 10
    26.             energy = (result.registers[5] + (result.registers[6] << 16)) / 10
    27.             frequency = result.registers[7] / 10
    28.             power_factor = result.registers[8] / 100
    29.             data.append({"name": device["name"], "id": device["id"], "voltage": voltage, "current": current, "power": power, "energy": energy, "frequency": frequency, "power_factor": power_factor})
    30.         except:
    31.             errors.append(device["name"])
    32.             data.append({"name": device["name"], "id": device["id"], "voltage": 0, "current": 0, "power": 0, "energy": 0, "frequency": 0, "power_factor": 0})
    33.  
    34. except:
    35.     print("Failed to connect to Modbus device")
    36.  
    37. client.close()
    38.  
    39. with open("data.json", "w") as f:
    40.     json.dump({"data": data, "errors": errors}, f, indent=4)
    41.  
Add Comment
Please, Sign In to add comment
Advertisement