I am using minimalmodbus to communicate with micro motion flow meter which uses rs485 protocol and i am using usb-rs485 converter. The micro motion modbus documentation is give here.
when I read floating point number from 2 registers using this code
import minimalmodbus
minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL=True
import serial
instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 1)
instrument.serial.baudrate = 9600
instrument.serial.timeout = 1
instrument.serial.baudrate = 9600
instrument.serial.bytesize = 8
instrument.serial.parity = serial.PARITY_NONE
instrument.serial.stopbits = 1
instrument.serial.timeout = 0.05
instrument.mode = minimalmodbus.MODE_RTU
instrument.debug = True
try:
values = instrument.read_float(250, 3, 2)
print (values)
except IOError:
print("Failed")
it gives me this response:
MinimalModbus debug mode. Writing to instrument (expecting 9 bytes back): '\x01\x03\x00ú\x00\x02ä:' (01 03 00 FA 00 02 E4 3A)
MinimalModbus debug mode. No sleep required before write. Time since previous read: 1502310315020.7 ms, minimum silent period: 4.01 ms.
MinimalModbus debug mode. Response from instrument: '\x01\x03\x04\x9f3Aâ\x941' (01 03 04 9F 33 41 E2 94 31) (9 bytes), roundtrip time: 28.8 ms. Timeout setting: 50.0 ms.
-3.7959221374830406e-20
which should be like 29.879 or 29.78687 something like that. its due to the order of bytestring. There is a workaround given here. https://minimalmodbus.readthedocs.io/en/master/advancedusage.html#workaround-for-floats-with-wrong-byte-order
as it written there using this code
values = read_registers(3924, numberOfRegisters=2)
registerstring = chr(values[2]) + chr(values[3]) + chr(values[0]) + chr(values[1])
floatvalue = minimalmodbus._bytestringToFloat(registerstring)
or something similar we can put the byte order right to get normal outputs.But im stuck here using
values = read_registers(3924, numberOfRegisters=2)
return singed int and if you read 2 registers it will give 2 values in list.
[61552, 16865]
How I am supposed to get the bytestring to set its order right. Now my question is how I save the payload from slave. I want to save this byte string to'\x01\x03\x04\x9f3Aâ\x941' in variable so I can change the byte order. and pass it to _bytestringToFloat() so I can get a actual value. I am newbie so please help.
Use struct.pack
and struct.unpack
to convert integers to bytestring to float.
import struct
r=[61552, 16865]
b=struct.pack('HH',r[0],r[1])
>>> b'p\xf0\xe1A'
struct.unpack('f',b)[0]
>>> 28.242401123046875