RC2026 – Part 6 – Reading atmospheric pressure from a BME280 on an RC2014

In previous posts, I’ve been able to read the temperature and humidity using a BME280 sensor attached to my RC2014 computer. The BME280 has one other reading it can provide, and that is atmospheric pressure.

As with the temperature and humidity, I need to calculate the value using the calibration data stored in the BME280. I also need the value of t_fine I stored when calculating the temperature. My previous post showed how to get these values. The BME280 datasheet gives me the algorithm and example code to calculate the air pressure.

float readPressure(void) {
    int64_t var1, var2, p;

    readTemperature(); // Must be done first to set t_fine

    int32_t adc_P = read24(BME280_REGISTER_PRESSUREDATA);
    adc_P >>= 4;

    var1 = ((int64_t)t_fine) - 128000;
    var2 = var1 * var1 * (int64_t)_bme280_calib.dig_P6;
    var2 = var2 + ((var1 * (int64_t)_bme280_calib.dig_P5) << 17);
    var2 = var2 + (((int64_t)_bme280_calib.dig_P4) << 35);
    var1 = ((var1 * var1 * (int64_t)_bme280_calib.dig_P3) >> 8) +
           ((var1 * (int64_t)_bme280_calib.dig_P2) << 12);
    var1 =
        (((((int64_t)1) << 47) + var1)) * ((int64_t)_bme280_calib.dig_P1) >> 33;

    if (var1 == 0) {
        return 0; // avoid exception caused by division by zero
    }
    p = 1048576 - adc_P;
    p = (((p << 31) - var2) * 3125) / var1;
    var1 = (((int64_t)_bme280_calib.dig_P9) * (p >> 13) * (p >> 13)) >> 25;
    var2 = (((int64_t)_bme280_calib.dig_P8) * p) >> 19;

    p = ((p + var1 + var2) >> 8) + (((int64_t)_bme280_calib.dig_P7) << 4);
    return (float)p / 256.0;
}

I can plug this into existing code and get the temperature, air pressure, and humidity, then show it on the console.

float temperature = readTemperature();
float pressure = readPressure();
float humidity = readHumidity();
printf("Temperature: %.2f°C, ", temperature);
printf("Pressure: %.2f hPa, ", pressure);
printf("Humidity: %.2f %%\n", humidity);