pimoroni / bme680-python

Python library for the BME680 gas, temperature, humidity and pressure sensor.
https://shop.pimoroni.com/products/bme680
MIT License
260 stars 93 forks source link

added set_temp_offset function and example #13

Closed ayeks closed 6 years ago

ayeks commented 6 years ago

The BME680 sensor is not factory calibrated. As discussed in issue #11 temperature offsets must be added to t_fine because that variable is used for pressure and humidity calculations too. I added the function set_temp_offset that accepts positive and negative offsets in Celsius.

Output from examples/temp-offset.py:

Display Temperature, Pressure and Humidity with different offsets.

Initial readings
27.84 C,982.50 hPa,46.917 %RH
SET offset 4 degrees celsius
31.84 C,988.91 hPa,47.433 %RH
SET offset -1.87 degrees celsius
25.99 C,979.44 hPa,46.683 %RH
SET offset -100 degrees celsius
-72.14 C,827.25 hPa,42.236 %RH
SET offset 0 degrees celsius
27.87 C,982.49 hPa,46.940 %RH
Gadgetoid commented 6 years ago

Nice work! Thank you for this. I'll get it tested and merged as soon as I can.

To avoid the duplication of the degrees C to t_fine conversion, I believe you could use math.copysign to copy the sign of value back to the result of the calculation after performing the calculation unsigned.

EG something like this:

if value == 0:
    self.offset_temp_in_t_fine = 0
else:
    self.offset_temp_in_t_fine = int(math.copysign((((int(abs(value) * 100)) << 8) - 128) / 5, value))

A quick test suggests this is sane:

>>> value = -5
>>> int(math.copysign((((int(abs(value) * 100)) << 8) - 128) / 5, value))
-25574
>>> value = 5
>>> int(math.copysign((((int(abs(value) * 100)) << 8) - 128) / 5, value))
25574
ayeks commented 6 years ago

Thanks for the hint! I disliked the prior solution too, but was unaware of the copysign function. It works like a charm:

Display Temperature, Pressure and Humidity with different offsets.

Initial readings
28.42 C,981.80 hPa,51.559 %RH
SET offset 4 degrees celsius
28.42 C,981.79 hPa,51.551 %RH
SET offset -1.87 degrees celsius
26.56 C,978.82 hPa,51.314 %RH
SET offset -100 degrees celsius
-71.56 C,826.78 hPa,46.533 %RH
SET offset 0 degrees celsius
28.44 C,981.77 hPa,51.567 %RH
Gadgetoid commented 6 years ago

Merged! There was a small bug in your code where you didn't change the "elif" to "else" so it wasn't calculating the offset for positive offsets, but I fixed it.

Thank you for taking the time to figure this out and make a contribution!

ayeks commented 6 years ago

Whoops thanks for spotting that. If I had read the stdout one post above more carefully I would have seen that!

Best regards Lars