Skip to content

Commit b67185b

Browse files
JordanYatescarlescufi
authored andcommitted
sensor: bme680: fix fetch API conformance
`sensor_sample_fetch` is documented to read all of a sensor's active channels and block until complete. The previous implementation read the result from the previous call and triggered the next sample. As a result the first call always failed, and subsequent calls would return data one sampling period old. Signed-off-by: Jordan Yates <[email protected]>
1 parent 98d0fe4 commit b67185b

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

drivers/sensor/bosch/bme680/bme680.c

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -213,17 +213,41 @@ static int bme680_sample_fetch(const struct device *dev,
213213
uint8_t gas_range;
214214
uint32_t adc_temp, adc_press;
215215
uint16_t adc_hum, adc_gas_res;
216+
uint8_t status;
216217
int size = BME680_LEN_FIELD;
218+
int cnt = 0;
217219
int ret;
218220

219221
__ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL);
220222

223+
/* Trigger the measurement */
224+
ret = bme680_reg_write(dev, BME680_REG_CTRL_MEAS, BME680_CTRL_MEAS_VAL);
225+
if (ret < 0) {
226+
return ret;
227+
}
228+
229+
do {
230+
/* Wait for a maximum of 250ms for data.
231+
* Initial delay after boot has been measured at 170ms.
232+
* Subequent triggers are < 1ms.
233+
*/
234+
if (cnt++ > 250) {
235+
return -EAGAIN;
236+
}
237+
k_sleep(K_MSEC(1));
238+
ret = bme680_reg_read(dev, BME680_REG_FIELD0, &status, 1);
239+
if (ret < 0) {
240+
return ret;
241+
}
242+
} while (!(status & BME680_MSK_NEW_DATA));
243+
LOG_DBG("New data after %d ms", cnt);
244+
221245
ret = bme680_reg_read(dev, BME680_REG_FIELD0, buff, size);
222246
if (ret < 0) {
223247
return ret;
224248
}
225249

226-
data->new_data = buff[0] & BME680_MSK_NEW_DATA;
250+
data->new_data = true;
227251
data->heatr_stab = buff[14] & BME680_MSK_HEATR_STAB;
228252

229253
adc_press = (uint32_t)(((uint32_t)buff[2] << 12) | ((uint32_t)buff[3] << 4)
@@ -240,14 +264,6 @@ static int bme680_sample_fetch(const struct device *dev,
240264
bme680_calc_humidity(data, adc_hum);
241265
bme680_calc_gas_resistance(data, gas_range, adc_gas_res);
242266
}
243-
244-
/* Trigger the next measurement */
245-
ret = bme680_reg_write(dev, BME680_REG_CTRL_MEAS,
246-
BME680_CTRL_MEAS_VAL);
247-
if (ret < 0) {
248-
return ret;
249-
}
250-
251267
return 0;
252268
}
253269

0 commit comments

Comments
 (0)