From 06243aaa007be6e380915f18ab4c8e3234ad8a06 Mon Sep 17 00:00:00 2001 From: ladyada Date: Mon, 1 Oct 2018 22:32:25 -0400 Subject: [PATCH 1/2] make I2C init more standard, move try/except into the wakeup location --- adafruit_am2320.py | 7 +++++-- examples/am2320_simpletest.py | 15 ++++----------- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/adafruit_am2320.py b/adafruit_am2320.py index 3e38195..560bebf 100644 --- a/adafruit_am2320.py +++ b/adafruit_am2320.py @@ -90,7 +90,10 @@ def __init__(self, i2c_bus, address=AM2320_DEFAULT_ADDR): 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 @@ -103,7 +106,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(" Date: Mon, 1 Oct 2018 22:40:21 -0400 Subject: [PATCH 2/2] add init retries --- adafruit_am2320.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/adafruit_am2320.py b/adafruit_am2320.py index 560bebf..59fac53 100644 --- a/adafruit_am2320.py +++ b/adafruit_am2320.py @@ -85,7 +85,15 @@ 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: