diff --git a/src/mgos_sht31.c b/src/mgos_sht31.c index b2e8743..83be65b 100644 --- a/src/mgos_sht31.c +++ b/src/mgos_sht31.c @@ -48,11 +48,28 @@ static uint8_t crc8(const uint8_t *data, int len) } return crc; } + +static uint16_t mgos_sht31_status(struct mgos_sht31 *sensor) { + uint8_t data[3]; + uint16_t value; + + mgos_sht31_cmd(sensor, MGOS_SHT31_READSTATUS); + if (!mgos_i2c_read(sensor->i2c, sensor->i2caddr, data, 3, true)) + return 0; + + // Check CRC8 checksums + if ((data[2]!=crc8(data, 2))) + return 0; + value=(data[0]<<8) + data[1]; + + return value; +} // Private functions end // Public functions follow struct mgos_sht31 *mgos_sht31_create(struct mgos_i2c *i2c, uint8_t i2caddr) { struct mgos_sht31 *sensor; + uint16_t status0, status1, status2; if (!i2c) return NULL; @@ -63,7 +80,21 @@ struct mgos_sht31 *mgos_sht31_create(struct mgos_i2c *i2c, uint8_t i2caddr) { sensor->last_read_time=0; mgos_sht31_cmd(sensor, MGOS_SHT31_SOFTRESET); - return sensor; + + // Toggle heater on and off, which shows up in status register bit 13 (0=Off, 1=On) + status0=mgos_sht31_status(sensor); // heater is off, bit13 is 0 + mgos_sht31_cmd(sensor, MGOS_SHT31_HEATEREN); + status1=mgos_sht31_status(sensor); // heater is on, bit13 is 1 + mgos_sht31_cmd(sensor, MGOS_SHT31_HEATERDIS); + status2=mgos_sht31_status(sensor); // heater is off, bit13 is 0 + + if (((status0 & 0x2000) == 0) && ((status1 & 0x2000) != 0) && ((status2 & 0x2000) == 0)) { + LOG(LL_INFO, ("SHT31 created at I2C 0x%02x", i2caddr)); + return sensor; + } + + free(sensor); + return NULL; } void mgos_sht31_destroy(struct mgos_sht31 **sensor) { diff --git a/src/mgos_si7021.c b/src/mgos_si7021.c index 5117482..1781fa1 100644 --- a/src/mgos_si7021.c +++ b/src/mgos_si7021.c @@ -60,7 +60,6 @@ struct mgos_si7021 *mgos_si7021_create(struct mgos_i2c *i2c, uint8_t i2caddr) { LOG(LL_ERROR, ("Chip ID register invalid, expected 0x3A got 0x%02x (%d)", ret, ret)); return NULL; } - LOG(LL_INFO, ("SI7021 found at I2C 0x%02x", i2caddr)); sensor=calloc(1, sizeof(struct mgos_si7021)); if (!sensor) return NULL; @@ -68,6 +67,7 @@ struct mgos_si7021 *mgos_si7021_create(struct mgos_i2c *i2c, uint8_t i2caddr) { sensor->i2c=i2c; sensor->last_read_time=0; + LOG(LL_INFO, ("SI7021 created at I2C 0x%02x", i2caddr)); return sensor; }