Skip to content

Commit 29441f2

Browse files
authored
Merge pull request #35 from CapableRobot/skip-init-write
Adding ability to skip device probing upon object init. …
2 parents cf7eabc + db586d2 commit 29441f2

File tree

1 file changed

+26
-19
lines changed

1 file changed

+26
-19
lines changed

adafruit_bus_device/i2c_device.py

+26-19
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ class I2CDevice:
3535
3636
:param ~busio.I2C i2c: The I2C bus the device is on
3737
:param int device_address: The 7 bit device address
38+
:param bool probe: Probe for the device upon object creation, default is true
3839
3940
.. note:: This class is **NOT** built into CircuitPython. See
4041
:ref:`here for install instructions <bus_device_installation>`.
@@ -57,29 +58,14 @@ class I2CDevice:
5758
device.write(bytes_read)
5859
"""
5960

60-
def __init__(self, i2c, device_address):
61-
"""
62-
Try to read a byte from an address,
63-
if you get an OSError it means the device is not there
64-
"""
65-
while not i2c.try_lock():
66-
pass
67-
try:
68-
i2c.writeto(device_address, b'')
69-
except OSError:
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)
77-
finally:
78-
i2c.unlock()
61+
def __init__(self, i2c, device_address, probe=True):
7962

8063
self.i2c = i2c
8164
self.device_address = device_address
8265

66+
if probe:
67+
self.__probe_for_device()
68+
8369
def readinto(self, buf, **kwargs):
8470
"""
8571
Read into ``buf`` from the device. The number of bytes read will be the
@@ -164,3 +150,24 @@ def __enter__(self):
164150
def __exit__(self, *exc):
165151
self.i2c.unlock()
166152
return False
153+
154+
def __probe_for_device(self):
155+
"""
156+
Try to read a byte from an address,
157+
if you get an OSError it means the device is not there
158+
or that the device does not support these means of probing
159+
"""
160+
while not self.i2c.try_lock():
161+
pass
162+
try:
163+
self.i2c.writeto(self.device_address, b'')
164+
except OSError:
165+
# some OS's dont like writing an empty bytesting...
166+
# Retry by reading a byte
167+
try:
168+
result = bytearray(1)
169+
self.i2c.readfrom_into(self.device_address, result)
170+
except OSError:
171+
raise ValueError("No I2C device at address: %x" % self.device_address)
172+
finally:
173+
self.i2c.unlock()

0 commit comments

Comments
 (0)