Skip to content

Commit 26c73be

Browse files
authored
Merge pull request #5 from ladyada/master
Looks good. Tested on a Pi Zero W and no additional pull ups.
2 parents 879c298 + 60ef01a commit 26c73be

File tree

2 files changed

+18
-14
lines changed

2 files changed

+18
-14
lines changed

adafruit_am2320.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,12 +85,23 @@ class AM2320:
8585
8686
"""
8787
def __init__(self, i2c_bus, address=AM2320_DEFAULT_ADDR):
88-
self._i2c = I2CDevice(i2c_bus, address)
88+
for _ in range(3):
89+
# retry since we have to wake up the devices
90+
try:
91+
self._i2c = I2CDevice(i2c_bus, address)
92+
return
93+
except ValueError:
94+
pass
95+
time.sleep(0.25)
96+
raise ValueError("AM2320 not found")
8997

9098
def _read_register(self, register, length):
9199
with self._i2c as i2c:
92100
# wake up sensor
93-
i2c.write(bytes([0x00]))
101+
try:
102+
i2c.write(bytes([0x00]))
103+
except OSError:
104+
pass
94105
time.sleep(0.01) # wait 10 ms
95106

96107
# Send command to read register
@@ -103,7 +114,7 @@ def _read_register(self, register, length):
103114
# print("$%02X => %s" % (register, [hex(i) for i in result]))
104115
# Check preamble indicates correct readings
105116
if result[0] != 0x3 or result[1] != length:
106-
raise RuntimeError('I2C modbus read failure')
117+
raise RuntimeError('I2C read failure')
107118
# Check CRC on all but last 2 bytes
108119
crc1 = struct.unpack("<H", bytes(result[-2:]))[0]
109120
crc2 = _crc16(result[0:-2])

examples/am2320_simpletest.py

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,11 @@
33
import busio
44
import adafruit_am2320
55

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

10-
1110
while True:
12-
try:
13-
print("Temperature: ", am.temperature)
14-
print("Humidity: ", am.relative_humidity)
15-
except OSError:
16-
# These sensors are a bit flakey, its ok if the readings fail
17-
pass
18-
except RuntimeError:
19-
pass
11+
print("Temperature: ", am.temperature)
12+
print("Humidity: ", am.relative_humidity)
2013
time.sleep(2)

0 commit comments

Comments
 (0)