[SOLVED] "Strange" behaviour reading I2C device

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
pmulvey
Posts: 45
Joined: Sun Jul 29, 2018 8:12 am
Location: Athlone, Ireland

[SOLVED] "Strange" behaviour reading I2C device

Post by pmulvey » Sun Nov 03, 2019 2:51 pm

I was reading the I2C PCF8574 i/o expander and branching depending on results. This is a re-creation of the situation:

Code: Select all

from machine import I2C
while True:
    i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)
    x = i2c.readfrom(0x20, 1)   #i2c returns 0x10
    print ("First attempt: x = ", x, "and is type", type(x))
    if x == 0x10:
        print ("The value is 0x10, but I never get here!!!")

    x = ord(i2c.readfrom(0x20, 1))   #i2c returns 0x10
    print ("Second attempt: x = ", x, "and is type", type(x))
    if x == 0x10:
        print ("The value is 0x10 and here I am!")   
        
    print (".............")
This is the output:

Code: Select all

First attempt: x =  b'\x10' and is type <class 'bytes'>
Second attempt: x =  16 and is type <class 'int'>
The value is 0x10 and here I am!
.............
The first IF statement never saw a True expression because the i2c read returned a byte object. This had me stumped for ages, finally I discovered ord() which converted the byte to int and allowed the second IF statement to behave as predicted.

Hope this saves someone grief.
Paul Mulvey

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: [SOLVED] "Strange" behaviour reading I2C device

Post by dhylands » Sun Nov 03, 2019 11:24 pm

IIRC you’ re getting a byte string of length 1. So you’d want to compare x[0] to 0x10

Post Reply