048eb804fde2096a7c170bef086a94d8258ec4d0
4 from bme280
import BME280
5 from subprocess
import PIPE
, Popen
8 from smbus2
import SMBus
10 from smbus
import SMBus
12 print("""compensated-temperature.py - Use the CPU temperature
13 to compensate temperature readings from the BME280 sensor.
14 Method adapted from Initial State's Enviro pHAT review:
15 https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441
22 bme280
= BME280(i2c_dev
=bus
)
25 # Get the temperature of the CPU for compensation
26 def get_cpu_temperature():
27 process
= Popen(['vcgencmd', 'measure_temp'], stdout
=PIPE
)
28 output
, _error
= process
.communicate()
29 output
= output
.decode()
30 return float(output
[output
.index('=') + 1:output
.rindex("'")])
33 # Tuning factor for compensation. Decrease this number to adjust the
34 # temperature down, and increase to adjust up
40 cpu_temp
= get_cpu_temperature()
41 # Smooth out with some averaging to decrease jitter
42 cpu_temps
= cpu_temps
[1:] + [cpu_temp
]
43 avg_cpu_temp
= sum(cpu_temps
) / float(len(cpu_temps
))
44 raw_temp
= bme280
.get_temperature()
45 comp_temp
= raw_temp
- ((avg_cpu_temp
- raw_temp
) / factor
)
46 print("Compensated temperature: {:05.2f} *C".format(comp_temp
))