1

I have created modbus slave to write data to the registers. I am able to write both float values and integer values from the slave side.

In the modbus master I am able to access only the integer values but not able to read float values.

I went through this https://github.com/ljean/modbus-tk/issues/72 but that didn't solve my problem.

For the integer values reading I can use the below code and read the values.

master = modbus_tcp.TcpMaster()
master.set_timeout(time_out_period)
result = master.execute(slave = 100, function_code = 3 , starting_address = 0, quantity_of_x = 25) 

But for the float values I used both the above and below code.

master = modbus_tcp.TcpMaster()
master.set_timeout(time_out_period)
result = master.execute(slave = 100, function_code = 3 , starting_address = 0, quantity_of_x = 25 , data_format='>f') 

I get error while reading the float as,

unpack requires a bytes object of length 4

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
Abhinandan s
  • 11
  • 1
  • 4

3 Answers3

0

The quantity of x should be a multiple of 2. Because the float requires two 16 bit registers or words so if you want 25 it should be 50.

sumit
  • 11
  • 5
0

You also need to provide the correct data format reflective of how many individual float values(below are big endian) are trying to be unpacked;

1 float

logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='>f'))

2 floats

logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 4, data_format='>ff'))

3 floats

logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 6, data_format='>fff'))
Kiran Mistry
  • 2,614
  • 3
  • 12
  • 28
0

It's easy, using Numpy. For example:

import numpy as np

# Sample registers to read
start_address = 0
items = 10
# Get the reply from slave
reply = master.execute(1, cst.READ_HOLDING_REGISTERS, start_address, items*2)
# Convert the reply to Numpy array of type int16
d16 = np.array(reply, dtype=np.int16)
# Convert to an array of type float32
f32 = d16.view(dtype = np.float32)
abesis
  • 21
  • 3