Search code examples
pythonpython-3.xmodbuspymodbus

Getting Integer Value from a Modbus RTU Slave using Python Code


I am reading the values in the registers of a modbus slave. But the values stored in the registers is combination of two registers. That is if register 3 has 72, and register 4 has 489. The actual value is 72489. I was able to do this.

But the problem arises, when the value in the second register starts with 0. That is if register 2 has 72, and register 4 has 012. The actual value should be 72012, but I get 7212. Is there a way to prevent this.

The part of code which does this is,

`rr = client.read_holding_registers(2, 22, unit=1)
 unconcatenateSensorConsumptionValues = rr.registers
 sensorsConsumptionValues = []
 for i in range(0, 10, 2):
    ftemp = ""+str(unconcatenateSensorConsumptionValues[i])
    stemp = ""+str(unconcatenateSensorConsumptionValues[i+1])
    fin = ftemp+stemp
    sensorsConsumptionValues.append(int(fin))`

Solution

  • I don't know if this is the best way to do it or not,I got two solution:

    First Solution: fill one register up to 65535 and add remaining to the other register. So the actual value will be addition of first and second register. But here we can have a max value of 131070(65535+65535).

    Second Solution: convert the value into hex and then divide the two octets and convert to decimal. Now store those decimal in the modbus registers. To get the original Value. Read the two modbus registers, convert them into hex, convert the both hex values combined to a decimal value. This decimal value is the actual value. In this way the maximum value can be stored with two registers is 4294967295.

    To understand easily, I attached a Image(I created using MS Paint but is there any easy way)

    This can be used for multiples registers and can use for big numbers.

    .enter image description here