From 1de49c9b2666561414fb897e291fa626042279f4 Mon Sep 17 00:00:00 2001 From: tyeth Date: Fri, 25 Aug 2023 11:23:55 +0100 Subject: [PATCH 1/2] Humidity data I2C Error - ESP32 Fixes #13 Updated after feedback from @ladyada --- Adafruit_AM2320.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Adafruit_AM2320.cpp b/Adafruit_AM2320.cpp index a5b4121..0eb11f9 100644 --- a/Adafruit_AM2320.cpp +++ b/Adafruit_AM2320.cpp @@ -128,16 +128,27 @@ float Adafruit_AM2320::readHumidity() { /**************************************************************************/ uint32_t Adafruit_AM2320::readRegister32(uint8_t reg) { uint8_t buffer[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + bool written = false; // wake up - i2c_dev->write(buffer, 1); + for (int i = 0; i < 3; i++) { + written = i2c_dev->write(buffer, 1); + if(written) break; + delay(100); // 50-70 lead to 2 errors each time + } + if (!written) return 0xFFFFFFFF; // no ACK! delay(10); // wait 10 ms // send a command to read register buffer[0] = AM2320_CMD_READREG; buffer[1] = reg; buffer[2] = 4; // 4 bytes - i2c_dev->write(buffer, 3); + for (int i = 0; i < 3; i++) { + written = i2c_dev->write(buffer, 3); + if(written) break; + delay(5); + } + if (!written) return 0xFFFFFFFF; // read not acknowledged! delay(2); // wait 2 ms // 2 bytes preamble, 4 bytes data, 2 bytes CRC From 27336667d10cb0f2b82e48b744bafe229c82dc9c Mon Sep 17 00:00:00 2001 From: tyeth Date: Fri, 25 Aug 2023 11:27:47 +0100 Subject: [PATCH 2/2] Appease CLang --- Adafruit_AM2320.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Adafruit_AM2320.cpp b/Adafruit_AM2320.cpp index 0eb11f9..be794ed 100644 --- a/Adafruit_AM2320.cpp +++ b/Adafruit_AM2320.cpp @@ -133,11 +133,13 @@ uint32_t Adafruit_AM2320::readRegister32(uint8_t reg) { // wake up for (int i = 0; i < 3; i++) { written = i2c_dev->write(buffer, 1); - if(written) break; + if (written) + break; delay(100); // 50-70 lead to 2 errors each time } - if (!written) return 0xFFFFFFFF; // no ACK! - delay(10); // wait 10 ms + if (!written) + return 0xFFFFFFFF; // no ACK! + delay(10); // wait 10 ms // send a command to read register buffer[0] = AM2320_CMD_READREG; @@ -145,11 +147,13 @@ uint32_t Adafruit_AM2320::readRegister32(uint8_t reg) { buffer[2] = 4; // 4 bytes for (int i = 0; i < 3; i++) { written = i2c_dev->write(buffer, 3); - if(written) break; + if (written) + break; delay(5); } - if (!written) return 0xFFFFFFFF; // read not acknowledged! - delay(2); // wait 2 ms + if (!written) + return 0xFFFFFFFF; // read not acknowledged! + delay(2); // wait 2 ms // 2 bytes preamble, 4 bytes data, 2 bytes CRC i2c_dev->read(buffer, 8);