Decode fix for #3
[EVA-2020-02-2.git] / examples / compensated-temperature.py
CommitLineData
a155e335
SM
1#!/usr/bin/env python
2
3import time
4from bme280 import BME280
5from subprocess import PIPE, Popen
6
7try:
8 from smbus2 import SMBus
9except ImportError:
10 from smbus import SMBus
11
ec075941
SM
12print("""compensated-temperature.py - Use the CPU temperature
13to compensate temperature readings from the BME280 sensor.
14Method adapted from Initial State's Enviro pHAT review:
15https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441
a155e335
SM
16
17Press Ctrl+C to exit!
18
19""")
20
21bus = SMBus(1)
22bme280 = BME280(i2c_dev=bus)
23
ec075941 24
9d2c6929 25# Get the temperature of the CPU for compensation
a155e335
SM
26def get_cpu_temperature():
27 process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
28 output, _error = process.communicate()
870b67fb 29 output = output.decode()
a155e335
SM
30 return float(output[output.index('=') + 1:output.rindex("'")])
31
ec075941 32
9d2c6929
SM
33# Tuning factor for compensation. Decrease this number to adjust the
34# temperature down, and increase to adjust up
87417b92 35factor = 0.8
a155e335 36
9d2c6929
SM
37cpu_temps = [0] * 5
38
a155e335
SM
39while True:
40 cpu_temp = get_cpu_temperature()
9d2c6929
SM
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))
a155e335 44 raw_temp = bme280.get_temperature()
9d2c6929 45 comp_temp = raw_temp - ((avg_cpu_temp - raw_temp) / factor)
a155e335
SM
46 print("Compensated temperature: {:05.2f} *C".format(comp_temp))
47 time.sleep(1.0)