Page 1 of 1

confusing return values

Posted: Tue Feb 23, 2021 5:02 pm
by cyrano1960
Hello,

after several attempts I finally managed to get my MLX90615 sensor working. But I noticed a strange behavior with the return values. The code lines look like this:

Code: Select all

a, b = i2c.readfrom_mem(0x5B, 0x27, 2)
temp = int(hex(b)) + hex(a)[2:], 16)
This works because a and b are of type integer in this case (I also checked with print(type(a))). According to the I2C documentation they should be byte objects. And if I do this:

Code: Select all

a = i2c.readfrom_mem(0x5B, 0x27, 1)
then a is also of type bytes.
My question now is: Why does the first call result in two integer objects? I know, it is more a Python basic problem but I can“t find an answer for such a specific issue anywhere.

Thank you very much and best regards,
cyr

Re: confusing return values

Posted: Tue Feb 23, 2021 5:44 pm
by pythoncoder
If you create a 2 element bytes object and assign it to two integers, Python will unpack it placing element 0 in the left hand integer and element 1 in the right hand one:

Code: Select all

>>> v = b'ab'  # bytes object with two elements
>>> v
b'ab'
>>> x, y = v
>>> x
97  # ord(a)
>>> y
98  # ord(b)
>>> chr(97)
'a'
>>> chr(98)
'b'
>>> 

Re: confusing return values

Posted: Tue Feb 23, 2021 6:28 pm
by cyrano1960
Dear Peter,

thank you so much for this fast and very good and clear explanation. I probably still have too much c in my blood :lol:

Best regards,
cyr

Re: confusing return values

Posted: Mon Mar 01, 2021 6:20 am
by rcolistete
I've made a MicroPython driver module for MLX90615 infrared temperature sensor :
https://github.com/rcolistete/MicroPyth ... 615_driver