RC2026 – Part 5 – Reading the humidity from a BME280 on an RC2014

In my last post, I showed how to read the temperature from a BME280 sensor using a Z80-based RC2014 computer.

The BME280 can also provide readings for humidity and atmospheric pressure. In this post, I’m going to look at reading humidity.

The BME280 provides the humidity value as a 24bit integer. I can use the read24 function I defined in my last post to read this value from the BME280. However, I can’t use it directly. Like the temperature reading, I have to do some calculations using the calibration data from the BME280. Thankfully, the BME280 datasheet gives me an algorithm to do this on page 25, so I just need to tweak this to drop in the relevant values.

float readHumidity(void) {
    int32_t adc_H = read16(BME280_REGISTER_HUMIDDATA);
    int32_t v_x1_u32r;

    v_x1_u32r = (t_fine - ((int32_t)76800));
    v_x1_u32r = (((((adc_H << 14) - (((int32_t)_bme280_calib.dig_H4) << 20) -
                    (((int32_t)_bme280_calib.dig_H5) * v_x1_u32r)) +
                   ((int32_t)16384)) >>
                  15) *
                 (((((((v_x1_u32r * ((int32_t)_bme280_calib.dig_H6)) >> 10) *
                      (((v_x1_u32r * ((int32_t)_bme280_calib.dig_H3)) >> 11) + ((int32_t)32768))) >>
                     10) +
                    ((int32_t)2097152)) *
                       ((int32_t)_bme280_calib.dig_H2) +
                   8192) >>
                  14));
    v_x1_u32r =
        (v_x1_u32r -
         (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) *
           ((int32_t)_bme280_calib.dig_H1)) >>
          4));
    v_x1_u32r = (v_x1_u32r < 0 ? 0 : v_x1_u32r);
    v_x1_u32r = (v_x1_u32r > 419430400 ? 419430400 : v_x1_u32r);
    return (float)(v_x1_u32r >> 12) / 1024.0;
}

I can now simply tweak my main() function to query this and display the results to the console.

float humidity = readHumidity();
printf("Humidity: %.2f %%\n", humidity);

That was really simple because most of the hard work had already been done in my previous post. The readHumidity function looks complex, but it’s just the example code from the datasheet tweaked to use my variables.