confusing return values

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
cyrano1960
Posts: 39
Joined: Fri Mar 29, 2019 7:08 pm

confusing return values

Post by cyrano1960 » Tue Feb 23, 2021 5:02 pm

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

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: confusing return values

Post by pythoncoder » Tue Feb 23, 2021 5:44 pm

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'
>>> 
Peter Hinch
Index to my micropython libraries.

cyrano1960
Posts: 39
Joined: Fri Mar 29, 2019 7:08 pm

Re: confusing return values

Post by cyrano1960 » Tue Feb 23, 2021 6:28 pm

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

User avatar
rcolistete
Posts: 352
Joined: Thu Dec 31, 2015 3:12 pm
Location: Brazil
Contact:

Re: confusing return values

Post by rcolistete » Mon Mar 01, 2021 6:20 am

I've made a MicroPython driver module for MLX90615 infrared temperature sensor :
https://github.com/rcolistete/MicroPyth ... 615_driver
My "MicroPython Samples". My "MicroPython Firmwares" with many options (double precision, ulab, etc).

Post Reply