How to send negative values through modbus serial master (TRB145)

Hi

I am trying to write some values to a register on a device connected to a TRB145 through Modbus serial master.

The writing works fine for positive values, but i am unsure to write negative values. I keep getting an error from the interface when i do.

The device requires both values to be written at the same time which is why i am using set multiple holding registers. It works for positive values, but not sure how to enter negative ones.

regards

Hello,

I will have to check with RnD regarding negative floats with floats data type.

However, Modbus uses bits, and the data type just determines how these bits are interpreted. If you want to transmit the values β€˜0.85’ and β€˜-69’ to the slave registers, you can use various data types, provided that the bits align correctly for the receiving device to understand them.

For instance, using a 32-bit UINT (unsigned integer) and function code 16 (write multiple holding registers), you can send the following values to write β€˜0.85’ and β€˜-69’:

  • For β€˜0.85’: 1062836634
  • For β€˜-69’: 3263823872

To determine the correct bit order, you can take the value you need, like β€˜0.85,’ and use an online tool (like the one here) to verify the bit order. Then, convert the binary representation to decimal (here). In this case, the result is 1062836634, which you can use with the 32-bit UINT data type. Keep in mind that the byte order is important, so I suggest checking what works for you. For example, usin the Modbus simulator with the order of 3,4,1,2:

image

Kind Regards,

Thanks, i’ll try this out. I even created a small python script to assist in this so i don’t have to rely on online tools.

import struct


def float_converter(floatlist):
    for f in floatlist:
        print(f,"->",binary(f),"->",int(binary(f),2))

def binary(num):
    #https://stackoverflow.com/questions/16444726/binary-representation-of-float-in-python-bits-not-hex
    return ''.join('{:0>8b}'.format(c) for c in struct.pack('!f', num))


float_converter([0.85,-69])
1 Like

This topic was automatically closed after 15 days. New replies are no longer allowed.