Reputation: 11
I am trying to figure out how to write first two bytes using minimalModbus write register command. Register size - 240(unsigned 8 bit int array), I used write.registers command and passed the value as an array but write value is happening in 2 and 4th byte.
Example : 00 03 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Instead I want the result as 03 01 followed by other bytes. Please give some suggestions
Upvotes: 1
Views: 1132
Reputation: 18866
How are you using write_registers
?
I'd expect a list of 16-bit ints, so you may be able to simply write this as
write_registers(address, [3, 1, ...])
Alternatively, you could use the much more verbose write_bits
to push exactly what you want
write_bits(address, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ...])
You can build a binary view of 16-bit blocks from your original ints like
>>> list(map(int, "".join(f"{x:016b}" for x in [3, 1])))
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
Upvotes: 0
Reputation: 66
I've never used minimalmodbus, but the docs suggest that the registers are 16-bits in size. This explains why each value you write is being padded by a byte. 1 and 3 are represented as 0x0001 and 0x0003 in 16 bits. You need to pack your two bytes into a single 16-bit value.
While you can do this with some bitwise operators, it may be more straightforward to use the struct library for this.
You can create your packed value like so:
bin_data = struct.pack('BB', (3,1)) # Turn into bytes 0x0301
packed_value = struct.unpack('H', bin_data) # 259 or 769 (depending on endianness)
Then try passing packed_value
to write_register()
. You may have to play with endianness (<H
vs. >H
) to get the order you want.
Upvotes: 0