Skip to content

add more retrying to make for greater stable #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions adafruit_am2320.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,23 @@ class AM2320:

"""
def __init__(self, i2c_bus, address=AM2320_DEFAULT_ADDR):
self._i2c = I2CDevice(i2c_bus, address)
for _ in range(3):
# retry since we have to wake up the devices
try:
self._i2c = I2CDevice(i2c_bus, address)
return
except ValueError:
pass
time.sleep(0.25)
raise ValueError("AM2320 not found")

def _read_register(self, register, length):
with self._i2c as i2c:
# wake up sensor
i2c.write(bytes([0x00]))
try:
i2c.write(bytes([0x00]))
except OSError:
pass
time.sleep(0.01) # wait 10 ms

# Send command to read register
Expand All @@ -103,7 +114,7 @@ def _read_register(self, register, length):
# print("$%02X => %s" % (register, [hex(i) for i in result]))
# Check preamble indicates correct readings
if result[0] != 0x3 or result[1] != length:
raise RuntimeError('I2C modbus read failure')
raise RuntimeError('I2C read failure')
# Check CRC on all but last 2 bytes
crc1 = struct.unpack("<H", bytes(result[-2:]))[0]
crc2 = _crc16(result[0:-2])
Expand Down
15 changes: 4 additions & 11 deletions examples/am2320_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,11 @@
import busio
import adafruit_am2320

# can also use board.SDA and board.SCL for neater looking code!
i2c = busio.I2C(board.D2, board.D0)
# create the I2C shared bus
i2c = busio.I2C(board.SCL, board.SDA)
am = adafruit_am2320.AM2320(i2c)


while True:
try:
print("Temperature: ", am.temperature)
print("Humidity: ", am.relative_humidity)
except OSError:
# These sensors are a bit flakey, its ok if the readings fail
pass
except RuntimeError:
pass
print("Temperature: ", am.temperature)
print("Humidity: ", am.relative_humidity)
time.sleep(2)