adafruit / Adafruit_BMP280_Library

Arduino Library for BMP280 sensors
250 stars 187 forks source link

Adafruit_BMP280 does not initialize config structure, can result in erroneous configuration for SPI 3-wire mode #60

Closed Telemattic closed 2 years ago

Telemattic commented 2 years ago

Arduino board: Wemos D1-mini (ESP8266) Arduino IDE version: 1.8.13 List the steps to reproduce the problem below:

Found after much debugging. The _configReg member of Adafruit_BMP280 is never initialized. This creates a problem when Adafruit_BMP280::setSampling is called, as that in turn sends the config register to the BMP280. The config register contains t_sb (initialized by calling setSampling), filter (initialized by calling setSampling) and spi3w_en (never initialized). Thus, if you're unlucky spi3w_en will be true and when setSampling is called the BMP280 will be reconfigured for 3-wire SPI mode.

Why does this usually work? Because the canonical usage is to create a global Adafruit_BMP280 object, and memory is zero'd by default.

Why does it break in my use case? Because I happen to be dynamically allocating the sensor, and (apparently) the memory returned by new doesn't happen to be zero in this case.

Trivial fix: include a constructor for Adafruit_BMP280::config Note: Adafruit_BMP280::ctrl_meas has the same defect, but when it is used (also in setSampling) it is completely initialized, so it doesn't create a defect

ladyada commented 2 years ago

nice debugging! please submit a PR if ya can, since you can reproduce the fix

caternuson commented 2 years ago

Hopefully fixed with #61