SI7021: Implement Status

This allows us to detect if the I2C device is indeed an Si7021.
By reading status, turning the heater on, reading status, and turning
the heater off, reading status, we will see three different states:
status bit13 is 'heater on' (0=off, 1=on).
In status0, bit13 will be 0,
In status1, bit13 will be 1, (the heater is now on)
In status2, bit13 will be 0.
This commit is contained in:
Pim van Pelt
2018-04-02 21:40:42 +02:00
parent 6b0774033e
commit 37838f0062
2 changed files with 33 additions and 2 deletions

View File

@ -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) {

View File

@ -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;
}