Skip to content

Commit 928f574

Browse files
committed
Retry Calibration with AHT20 command on failure
If try-except around legacy calibrate command fails, try to send new one instead afterwards
1 parent c6c02ac commit 928f574

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

adafruit_ahtx0.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@
4545
__repo__: str = "https://github.com/adafruit/Adafruit_CircuitPython_AHTx0.git"
4646

4747
AHTX0_I2CADDR_DEFAULT: int = const(0x38) # Default I2C address
48-
AHTX0_CMD_CALIBRATE: int = const(0xE1) # Calibration command
48+
AHT10_CMD_CALIBRATE: int = const(0xE1) # Calibration command for AHT10 sensor
49+
AHT20_CMD_CALIBRATE: int = const(0xBE) # Calibration command for AHT20 sensor
4950
AHTX0_CMD_TRIGGER: int = const(0xAC) # Trigger reading command
5051
AHTX0_CMD_SOFTRESET: int = const(0xBA) # Soft reset command
5152
AHTX0_STATUS_BUSY: int = const(0x80) # Status bit for busy
@@ -107,15 +108,27 @@ def reset(self) -> None:
107108

108109
def calibrate(self) -> bool:
109110
"""Ask the sensor to self-calibrate. Returns True on success, False otherwise"""
110-
# Newer AHT20's may not succeed, so wrapping in try/except
111-
self._buf[0] = AHTX0_CMD_CALIBRATE
111+
self._buf[0] = AHT10_CMD_CALIBRATE
112112
self._buf[1] = 0x08
113113
self._buf[2] = 0x00
114+
calibration_failed = False
114115
with self.i2c_device as i2c:
115116
try:
117+
# Newer AHT20's may not succeed with old command, so wrapping in try/except
116118
i2c.write(self._buf, start=0, end=3)
117119
except Exception: # pylint: disable=broad-except
118-
pass
120+
calibration_failed = True
121+
122+
if calibration_failed:
123+
# try another calibration command for newer AHT20's
124+
time.sleep(0.01)
125+
self._buf[0] = AHT20_CMD_CALIBRATE
126+
with self.i2c_device as i2c:
127+
try:
128+
i2c.write(self._buf, start=0, end=3)
129+
except Exception:
130+
pass
131+
119132
while self.status & AHTX0_STATUS_BUSY:
120133
time.sleep(0.01)
121134
if not self.status & AHTX0_STATUS_CALIBRATED:

0 commit comments

Comments
 (0)