Python3 lee datos de Modbus, incluido el procesamiento de números de punto flotante
1. Introducir bibliotecas dependientes
import modbus_tk.modbus_tcp as mt
import modbus_tk.defines as md
import time
import datetime
import struct
2. Descripción del tipo de operación Modbus
3. Lee el registro de tenencia
def read_AI():
AI = {
}
master_0 = mt.TcpMaster(
"192.168.1.111",
502
)
master_0.set_timeout(5.0)
try:
a_0 = master_0.execute(1, md.READ_HOLDING_REGISTERS, 512, 3)
AI[0] =float('%.2f' % int2float(a_0[0], a_0[1]))
AI[1] =float(a_0[2]/100.0)
except BaseException as e:
print(e)
return (AI)
4. Convierta los datos leídos a tipo de punto flotante
def int2float(a,b):
f=0
try:
z0=hex(a)[2:].zfill(4)
z1=hex(b)[2:].zfill(4)
z=z1+z0
f=struct.unpack('!f', bytes.fromhex(z))[0]
except BaseException as e:
print(e)
return f
5. Sube el código completo
import modbus_tk.modbus_tcp as mt
import modbus_tk.defines as md
import time
import datetime
import struct
def read_AI():
AI = {
}
master_0 = mt.TcpMaster(
"192.168.1.111",
502
)
master_0.set_timeout(5.0)
try:
a_0 = master_0.execute(1, md.READ_HOLDING_REGISTERS, 512, 3)
AI[0] =float('%.2f' % int2float(a_0[0], a_0[1]))
AI[1] =float(a_0[2]/100.0)
except BaseException as e:
print(e)
return (AI)
def read_DI():
DI = {
}
master_0 = mt.TcpMaster(
"192.168.1.111",
502
)
master_0.set_timeout(5.0)
try:
d_0 = master_0.execute(1, md.READ_DISCRETE_INPUTS, 3072, 4)
DI[0] = d_0[0]
DI[1] = d_0[1]
DI[2] = d_0[2]
DI[3] = d_0[3]
except BaseException as e:
print(e)
return (DI)
def int2float(a,b):
f=0
try:
z0=hex(a)[2:].zfill(4)
z1=hex(b)[2:].zfill(4)
z=z1+z0
f=struct.unpack('!f', bytes.fromhex(z))[0]
except BaseException as e:
print(e)
return f
if __name__ == "__main__":
print(read_AI())
print(read_DI())
6. Prueba del programa