From e47498b8bd1c232f45f28f2af3cbf59b0b66b46a Mon Sep 17 00:00:00 2001 From: Anatole SCHRAMM Date: Thu, 11 Jan 2024 13:41:43 +0100 Subject: [PATCH] Improved pressure computation function by reading the pressure and temperature registers in one shot --- .../app/app_drivers/i2c/BMP280.c | 56 +++++++++++-------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/src/W800_SDK_v1.00.10/app/app_drivers/i2c/BMP280.c b/src/W800_SDK_v1.00.10/app/app_drivers/i2c/BMP280.c index 2fb83cd..e2b9c38 100644 --- a/src/W800_SDK_v1.00.10/app/app_drivers/i2c/BMP280.c +++ b/src/W800_SDK_v1.00.10/app/app_drivers/i2c/BMP280.c @@ -117,6 +117,28 @@ static bool _BMP280_read_calibration_data(void) return true; } +static float _BMP280_compute_temperature(uint8_t *data) +{ + int32_t var1, var2; + int32_t adc_T = data[0] << 16 | data[1] << 8 | data[2]; + adc_T >>= 4; + + var1 = ((((adc_T >> 3) - ((int32_t)_calibration_data.dig_T1 << 1))) * + ((int32_t)_calibration_data.dig_T2)) >> + 11; + + var2 = (((((adc_T >> 4) - ((int32_t)_calibration_data.dig_T1)) * + ((adc_T >> 4) - ((int32_t)_calibration_data.dig_T1))) >> + 12) * + ((int32_t)_calibration_data.dig_T3)) >> + 14; + + t_fine = var1 + var2; + + float T = (t_fine * 5 + 128) >> 8; + return T / 100.0; +} + bool BMP280_init(void) { uint8_t data; @@ -162,39 +184,27 @@ bool BMP280_is_measuring(void) float BMP280_get_temperature(void) { - int32_t var1, var2; uint8_t data[3]; if(!i2c_read(BMP280_I2C_ADDR, BMP280_TEMP_MSB, data, sizeof data)) return 0.0f; - int32_t adc_T = data[0] << 16 | data[1] << 8 | data[2]; - adc_T >>= 4; - - var1 = ((((adc_T >> 3) - ((int32_t)_calibration_data.dig_T1 << 1))) * - ((int32_t)_calibration_data.dig_T2)) >> - 11; - - var2 = (((((adc_T >> 4) - ((int32_t)_calibration_data.dig_T1)) * - ((adc_T >> 4) - ((int32_t)_calibration_data.dig_T1))) >> - 12) * - ((int32_t)_calibration_data.dig_T3)) >> - 14; - - t_fine = var1 + var2; - - float T = (t_fine * 5 + 128) >> 8; - return T / 100; + return _BMP280_compute_temperature(data); } float BMP280_get_pressure(float * const temperature) { int64_t var1, var2, p; - uint8_t data[3]; - - float temp = BMP280_get_temperature(); - if(temperature) *temperature = temp; + uint8_t data[6]; - if(!i2c_read(BMP280_I2C_ADDR, BMP280_PRESS_MSB, data, sizeof data)) return 0.0f; + /* When reading the pressure, we also need to get the associated temperature, so let's read everything at once */ + if(!i2c_read(BMP280_I2C_ADDR, BMP280_PRESS_MSB, data, sizeof data)) + { + if(temperature) *temperature = 0.0f; + return 0.0f; + } + + float temp = _BMP280_compute_temperature(&data[3]); + if(temperature) *temperature = temp; int32_t adc_P = data[0] << 16 | data[1] << 8 | data[2]; adc_P >>= 4;