Page 1 of 1

[SOLVED] "Strange" behaviour reading I2C device

Posted: Sun Nov 03, 2019 2:51 pm
by pmulvey
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.

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

Posted: Sun Nov 03, 2019 11:24 pm
by dhylands
IIRC you’ re getting a byte string of length 1. So you’d want to compare x[0] to 0x10