Skip to content

Instantly share code, notes, and snippets.

@michalpelka
Created January 29, 2025 05:06
Show Gist options
  • Save michalpelka/16444026e9e61ae8554f353c355a5643 to your computer and use it in GitHub Desktop.
Save michalpelka/16444026e9e61ae8554f353c355a5643 to your computer and use it in GitHub Desktop.
from pymodbus.client import ModbusTcpClient
import struct
import os
# Define device connection
client = ModbusTcpClient('127.0.0.1', port=502) # Change IP and port as needed
# Connect to the device
while client.connect():
num_registers = 12
response = client.read_input_registers(7013, num_registers, unit=1)
if response.isError():
print("Error reading registers")
else:
registers = response.registers
float_values = []
# Convert register pairs to float values
for i in range(0, len(registers), 2):
raw = struct.pack(">HH", registers[i], registers[i+1]) # Change to "<HH" for little-endian
value = struct.unpack(">f", raw)[0] # Change to "<f" for little-endian
float_values.append(value)
os.system('cls')
print ("J1 %.2f" %float_values[0] )
print ("J2 %.2f" %float_values[1] )
print ("J3 %.2f" %float_values[2] )
print ("J4 %.2f" %float_values[3] )
print ("J5 %.2f" %float_values[4] )
print ("J6 %.2f" %float_values[5] )
client.close()
else:
print("Failed to connect to device")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment