Commit | Line | Data |
---|---|---|
a155e335 SM |
1 | #!/usr/bin/env python |
2 | ||
3 | import time | |
4 | from bme280 import BME280 | |
5 | from subprocess import PIPE, Popen | |
6 | ||
7 | try: | |
8 | from smbus2 import SMBus | |
9 | except ImportError: | |
10 | from smbus import SMBus | |
11 | ||
10b73e18 CM |
12 | import logging |
13 | ||
14 | logging.basicConfig( | |
15 | format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s', | |
16 | level=logging.INFO, | |
17 | datefmt='%Y-%m-%d %H:%M:%S') | |
18 | ||
19 | logging.info("""compensated-temperature.py - Use the CPU temperature | |
ec075941 SM |
20 | to compensate temperature readings from the BME280 sensor. |
21 | Method adapted from Initial State's Enviro pHAT review: | |
22 | https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441 | |
a155e335 SM |
23 | |
24 | Press Ctrl+C to exit! | |
25 | ||
26 | """) | |
27 | ||
28 | bus = SMBus(1) | |
29 | bme280 = BME280(i2c_dev=bus) | |
30 | ||
ec075941 | 31 | |
9d2c6929 | 32 | # Get the temperature of the CPU for compensation |
a155e335 | 33 | def get_cpu_temperature(): |
e2d010e2 | 34 | process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE, universal_newlines=True) |
a155e335 SM |
35 | output, _error = process.communicate() |
36 | return float(output[output.index('=') + 1:output.rindex("'")]) | |
37 | ||
ec075941 | 38 | |
9d2c6929 SM |
39 | # Tuning factor for compensation. Decrease this number to adjust the |
40 | # temperature down, and increase to adjust up | |
87417b92 | 41 | factor = 0.8 |
a155e335 | 42 | |
27156d25 | 43 | cpu_temps = [get_cpu_temperature()] * 5 |
9d2c6929 | 44 | |
a155e335 SM |
45 | while True: |
46 | cpu_temp = get_cpu_temperature() | |
9d2c6929 SM |
47 | # Smooth out with some averaging to decrease jitter |
48 | cpu_temps = cpu_temps[1:] + [cpu_temp] | |
49 | avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps)) | |
a155e335 | 50 | raw_temp = bme280.get_temperature() |
9d2c6929 | 51 | comp_temp = raw_temp - ((avg_cpu_temp - raw_temp) / factor) |
10b73e18 | 52 | logging.info("Compensated temperature: {:05.2f} *C".format(comp_temp)) |
a155e335 | 53 | time.sleep(1.0) |