From 5bce26d9b76e204058efe41ef33f24de04364722 Mon Sep 17 00:00:00 2001 From: Alexander Balya Date: Mon, 25 May 2026 04:03:24 +0200 Subject: [PATCH] Fix SHT2x detection for INA219 addresses (#10482) --- src/detect/ScanI2CTwoWire.cpp | 37 +++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/src/detect/ScanI2CTwoWire.cpp b/src/detect/ScanI2CTwoWire.cpp index e3471c32a..c1c48eac8 100644 --- a/src/detect/ScanI2CTwoWire.cpp +++ b/src/detect/ScanI2CTwoWire.cpp @@ -179,8 +179,22 @@ String readSEN5xProductName(TwoWire *i2cBus, uint8_t address) #endif #if HAS_TELEMETRY && !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR +static uint8_t crcSHT2X(const uint8_t *data, uint8_t len) +{ + uint8_t crc = 0; + for (uint8_t i = 0; i < len; i++) { + crc ^= data[i]; + for (uint8_t bit = 0; bit < 8; bit++) { + crc = (crc & 0x80) ? (crc << 1) ^ 0x31 : crc << 1; + } + } + return crc; +} + bool detectSHT21SerialNumber(TwoWire *i2cBus, uint8_t address) { + uint8_t serialA[8] = {0}; + uint8_t serialB[6] = {0}; i2cBus->beginTransmission(address); i2cBus->write(0xFA); @@ -189,12 +203,13 @@ bool detectSHT21SerialNumber(TwoWire *i2cBus, uint8_t address) if (i2cBus->endTransmission() != 0) return false; - if (i2cBus->requestFrom(address, (uint8_t)8) != 8) + if (i2cBus->requestFrom(address, (uint8_t)sizeof(serialA)) != sizeof(serialA)) return false; - // Just flush the data - while (i2cBus->available() < 8) { - i2cBus->read(); + for (uint8_t i = 0; i < sizeof(serialA); i++) { + if (!i2cBus->available()) + return false; + serialA[i] = i2cBus->read(); } i2cBus->beginTransmission(address); @@ -204,16 +219,18 @@ bool detectSHT21SerialNumber(TwoWire *i2cBus, uint8_t address) if (i2cBus->endTransmission() != 0) return false; - if (i2cBus->requestFrom(address, (uint8_t)6) != 6) + if (i2cBus->requestFrom(address, (uint8_t)sizeof(serialB)) != sizeof(serialB)) return false; - // Just flush the data - while (i2cBus->available() < 6) { - i2cBus->read(); + for (uint8_t i = 0; i < sizeof(serialB); i++) { + if (!i2cBus->available()) + return false; + serialB[i] = i2cBus->read(); } - // Assume we detect the SHT21 if something came back from the request - return true; + return crcSHT2X(&serialA[0], 1) == serialA[1] && crcSHT2X(&serialA[2], 1) == serialA[3] && + crcSHT2X(&serialA[4], 1) == serialA[5] && crcSHT2X(&serialA[6], 1) == serialA[7] && + crcSHT2X(&serialB[0], 2) == serialB[2] && crcSHT2X(&serialB[3], 2) == serialB[5]; } #endif