Skip to content

Commit a2d13f1

Browse files
committed
refactor pressure property to handle ZeroDivision case
Recap: in the `pressure` property there is a test `if var1 == 0:` in order to avoid a division-by-zero exception. Current code return a pressure of 0 in that case. It was suggested that my PR makes this a little more pythonic by usage of exception raise. Analysis of the root cause: because last calculation is ```var1 = (1.0 + var1 / 32768.0) * self._pressure_calib[0]``` the only reason for `var1` to be 0 is `self._pressure_calib[0]` is 0. Calibration values are read at init time from registers in the chip. So the root cause probably relates to a register read problem. Analysis of other similar codes Bosch bme280.c (Github): if var1 == 0, return minimum valid pressure (300hPa). Adafruit CiPy BMP280 driver: => initially, no tests were performed => In Feb, jraber implemeted return 0 in a commit named "Adopt changes from the BME280 library" => In Mar, jraber implemeted return minimum value in a commit named "Remove unnecessary 'if' and 'else' in the pressure property" Adafruit CiPy BMP680 driver: not tested => ZeroDivisionError I feel that returning silently the minimun valid pressure is not correct to draw attention on a possible hardware reliability problem. Returning 0 could make sense only if we were sure that the user was testing the return value against 0. Alternatively, letting the ZeroDivisionError occur will not provide proper clue to the user as to the root cause of the problem and will probably lead to this issue to be raised again as a bug in GitHub. Proposed solution: Test against 0 and raise a ArithmeticError with message "Invalid calculation possibly related to error while reading the calibration registers"
1 parent cf74245 commit a2d13f1

File tree

2 files changed

+4
-2
lines changed

2 files changed

+4
-2
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
__pycache__
22
_build
33
*.pyc
4+
*.mpy
45
.env
56
build*
67
bundles

adafruit_bme280.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -344,8 +344,9 @@ def pressure(self):
344344
var3 = self._pressure_calib[2] * var1 * var1 / 524288.0
345345
var1 = (var3 + self._pressure_calib[1] * var1) / 524288.0
346346
var1 = (1.0 + var1 / 32768.0) * self._pressure_calib[0]
347-
if var1 == 0: # avoid exception caused by division by zero (as per Arduino lib)
348-
return 0
347+
if not var1: # avoid exception caused by division by zero
348+
raise ArithmeticError("Invalid result possibly related to error while \
349+
reading the calibration registers")
349350
pressure = 1048576.0 - adc
350351
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
351352
var1 = self._pressure_calib[8] * pressure * pressure / 2147483648.0

0 commit comments

Comments
 (0)