[SOLVED] "Strange" behaviour reading I2C device
Posted: 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:
This is the output:
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.
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 (".............")
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!
.............
Hope this saves someone grief.