Adding all-in-one example
[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
12print("""compensated-temperature.py - Use the CPU temperature to compensate temperature
13readings from the BME280 sensor. Method adapted from Initial State's Enviro pHAT
14review: https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441
15
16Press Ctrl+C to exit!
17
18""")
19
20bus = SMBus(1)
21bme280 = BME280(i2c_dev=bus)
22
23def get_cpu_temperature():
24 process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
25 output, _error = process.communicate()
26 return float(output[output.index('=') + 1:output.rindex("'")])
27
87417b92 28factor = 0.8
a155e335
SM
29
30while True:
31 cpu_temp = get_cpu_temperature()
32 raw_temp = bme280.get_temperature()
33 comp_temp = raw_temp - ((cpu_temp - raw_temp) / factor)
34 print("Compensated temperature: {:05.2f} *C".format(comp_temp))
35 time.sleep(1.0)