Page 1 of 1

bug in meshkit sense iot_hts221_get_temperature()

Posted: Fri Jun 05, 2020 4:00 pm
by Creinarz
Hi,

this is just to let you know there is a bug in function iot_hts221_get_temperature(), file hts221.c. The function returns wrong values for temperatures under 21ÂșC. The reason is you are using unsigned integers instead of signed integers to calculate the temperature. In the code below, tmp_32 as well as the casts to calculate tmp_32 need to be signed.

Code: Select all

esp_err_t iot_hts221_get_temperature(hts221_handle_t sensor, int16_t *temperature)
{
    int16_t t0_out, t1_out, t_out, t0_degc_x8_u16, t1_degc_x8_u16;
    int16_t t0_degc, t1_degc;
    uint8_t buffer[4], tmp_8;
    uint32_t tmp_32;
    
    iot_hts221_read(sensor, HTS221_T0_DEGC_X8, 2, buffer);
    iot_hts221_read(sensor, HTS221_T0_T1_DEGC_H2, 1, &tmp_8);
    t0_degc_x8_u16 = (((uint16_t)(tmp_8 & 0x03)) << 8) | ((uint16_t)buffer[0]);
    t1_degc_x8_u16 = (((uint16_t)(tmp_8 & 0x0C)) << 6) | ((uint16_t)buffer[1]);
    t0_degc = t0_degc_x8_u16 >> 3;
    t1_degc = t1_degc_x8_u16 >> 3;

    iot_hts221_read(sensor, HTS221_T0_OUT_L, 4, buffer);
    t0_out = (((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0];
    t1_out = (((uint16_t)buffer[3]) << 8) | (uint16_t)buffer[2];

    iot_hts221_read(sensor, HTS221_TEMP_OUT_L_REG, 2, buffer);
    t_out = (((uint16_t)buffer[1]) << 8) | (uint16_t)buffer[0];

    tmp_32 = ((uint32_t)(t_out - t0_out)) * ((uint32_t)(t1_degc - t0_degc) * 10);

    if ((t1_out - t0_out) == 0) {
        return ESP_FAIL;
    }

    *temperature = tmp_32 / (t1_out - t0_out) + t0_degc * 10;
    return ESP_OK;
}
Changing the following two lines fixes the problem:

Code: Select all

int32_t tmp_32;
tmp_32 = ((int32_t)(t_out - t0_out)) * ((int32_t)(t1_degc - t0_degc) * 10);