Skip to content

Commit aea9d07

Browse files
committed
Attempt to write then fall back to read for i2c detect
This approach was suggested by ladyada in Adafruit_CircuitPython_BusDevice PR #22: #22 (comment) > ok tested with a plethora of sensors and the VEML6075 hates this > so turns out you actually need something like.... def __init__(self, i2c, device_address): """ Try to read a byte from an address, if you get an OSError it means the device is not there """ while not i2c.try_lock(): pass try: i2c.writeto(device_address, b'') except OSError: # some OS's dont like writing an empty bytesting... # Retry by reading a byte try: result = bytearray(1) i2c.readfrom_into(device_address, result) except OSError: raise ValueError("No I2C device at address: %x" % device_address) finally: i2c.unlock() self.i2c = i2c self.device_address = device_address
1 parent 793537e commit aea9d07

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

adafruit_bus_device/i2c_device.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ class I2CDevice:
5656
with device:
5757
device.write(bytes_read)
5858
"""
59+
5960
def __init__(self, i2c, device_address):
6061
"""
6162
Try to read a byte from an address,
@@ -64,10 +65,15 @@ def __init__(self, i2c, device_address):
6465
while not i2c.try_lock():
6566
pass
6667
try:
67-
result = bytearray(1)
68-
i2c.readfrom_into(device_address, result)
68+
i2c.writeto(device_address, b'')
6969
except OSError:
70-
raise ValueError("No I2C device at address: %x" % device_address)
70+
# some OS's dont like writing an empty bytesting...
71+
# Retry by reading a byte
72+
try:
73+
result = bytearray(1)
74+
i2c.readfrom_into(device_address, result)
75+
except OSError:
76+
raise ValueError("No I2C device at address: %x" % device_address)
7177
finally:
7278
i2c.unlock()
7379

0 commit comments

Comments
 (0)