smbus2
smbus2 copied to clipboard
Reading Signed bytes / words
Hello, First I would like to thank Karl-Petter for a great I2C driver. With it I was able to read the block data from my sensor. No other code worked. Again KUDOs.
For my sensor I need to read signed bytes and words. Also I need to be able to specify endianness. I could (or at least think I can) modify your code to add signed reads/writes. I would, however prefer not to modify your code for my application. If there is a way for me to modify the Git hub code, I would not as my coding capability is marginal. Is there any plan to add signed functions?
Thanks BR JohnRobert
BTW I could not find how to identify the entry as a request, not a bug.....sorry.
@JonRobert I don't have much time to do much with the lib these days I am afraid.
Regarding signed ints and words, I would say it's basically up to the user to interpret the contents you read out and write back again. However, I don't mind if you feel like extending the interface with methods taking signed values too.
If you choose to do convert from unsigned to signed and back outside of smbus2, you could consider to take the brute-force route and use the ctypes module. Quick'n dirty but it should work OK.
from ctypes import c_int8, c_uint8
....
# Converting unsigned byte read to signed
unsigned_byte = bus.read_byte_data(80, 0) # Assume read value is 200
signed_byte = c_int8(unsigned_byte).value # signed_byte becomes -56
....
# Convert signed byte to unsigned before write
signed_byte = -123
unsigned_byte = c_uint8(signed_byte).value # 133
bus.write_byte_data(80, 0, unsigned_byte)
You can do the same with c_int16 and c_uint16, but here, as you say, little/big endian comes into play as well.