Skip to content

Commit 91e006c

Browse files
JordanYateskartben
authored andcommitted
sensor: bme280: bme280_wait_until_ready timeout
Add a timeout to the `bme280_wait_until_ready` loop to ensure that we never get stuck in this loop even if the bus enters an error condition. Signed-off-by: Jordan Yates <[email protected]>
1 parent ba5330e commit 91e006c

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

drivers/sensor/bosch/bme280/bme280.c

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ LOG_MODULE_REGISTER(BME280, CONFIG_SENSOR_LOG_LEVEL);
2626
#warning "BME280 driver enabled without any devices"
2727
#endif
2828

29+
/* Maximum oversampling rate on each channel is 16x.
30+
* Maximum measurement time is given by (Datasheet appendix B 9.1):
31+
* 1.25 + [2.3 * T_over] + [2.3 * P_over + 0.575] + [2.3 * H_over + 0.575]
32+
* = 112.8 ms
33+
*/
34+
#define BME280_MEASUREMENT_TIMEOUT_MS 150
35+
2936
struct bme280_config {
3037
union bme280_bus bus;
3138
const struct bme280_bus_io *bus_io;
@@ -116,8 +123,9 @@ static uint32_t bme280_compensate_humidity(struct bme280_data *data,
116123
return (uint32_t)(h >> 12);
117124
}
118125

119-
static int bme280_wait_until_ready(const struct device *dev)
126+
static int bme280_wait_until_ready(const struct device *dev, k_timeout_t timeout)
120127
{
128+
k_timepoint_t end = sys_timepoint_calc(timeout);
121129
uint8_t status;
122130
int ret;
123131

@@ -130,6 +138,10 @@ static int bme280_wait_until_ready(const struct device *dev)
130138
if (!(status & (BME280_STATUS_MEASURING | BME280_STATUS_IM_UPDATE))) {
131139
break;
132140
}
141+
/* Check if waiting has timed out */
142+
if (sys_timepoint_expired(end)) {
143+
return -EAGAIN;
144+
}
133145
k_sleep(K_MSEC(3));
134146
}
135147

@@ -163,7 +175,7 @@ int bme280_sample_fetch_helper(const struct device *dev,
163175
}
164176
#endif
165177

166-
ret = bme280_wait_until_ready(dev);
178+
ret = bme280_wait_until_ready(dev, K_MSEC(BME280_MEASUREMENT_TIMEOUT_MS));
167179
if (ret < 0) {
168180
return ret;
169181
}
@@ -336,7 +348,8 @@ static int bme280_chip_init(const struct device *dev)
336348
LOG_DBG("Soft-reset failed: %d", err);
337349
}
338350

339-
err = bme280_wait_until_ready(dev);
351+
/* The only mention of a soft reset duration is 2ms from the self test timeouts */
352+
err = bme280_wait_until_ready(dev, K_MSEC(100));
340353
if (err < 0) {
341354
return err;
342355
}

0 commit comments

Comments
 (0)