So I have a project where I am reading data from MODBUS registers.
Each register is 16 bits, and each value is 32 bits. So I have to read two registers at a time to read each value.
So what I'm doing now is reading both registers and storing them in a regs array and getting their bits like so:
bits = (regs[0] << 16) + regs[1]
then I try converting the bits to a float like this:
s = struct.pack('>l', bits)
final = struct.unpack('>f', s)[0]
And final should be my 32-bit float. This works pretty much all the time, however, in a few cases I get this error:
Read registers failed: 'l' format requires -2147483648 <= number <= 2147483647
And so I went back and added a print statement to see what bits looked like before I turn it into a float, and it was this: 3309382817, which is clearly outside of that range...
So what am I doing wrong that's causing me to get this error? Is there something I am missing?
Update:
Just to give a bit more info, ran it again while printing the value of regs as well and got this:
[50561, 10024] # this is the value of regs
3313575720 # this is the value of bits
You are using the signed type l in your struct.pack. Use the unsigned type L instead.
See Struct Format Characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With