Commit | Line | Data |
---|---|---|
a155e335 SM |
1 | #!/usr/bin/env python |
2 | ||
3 | import time | |
4 | from bme280 import BME280 | |
a155e335 SM |
5 | |
6 | try: | |
7 | from smbus2 import SMBus | |
8 | except ImportError: | |
9 | from smbus import SMBus | |
10 | ||
ec075941 SM |
11 | print("""compensated-temperature.py - Use the CPU temperature |
12 | to compensate temperature readings from the BME280 sensor. | |
13 | Method adapted from Initial State's Enviro pHAT review: | |
14 | https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441 | |
a155e335 SM |
15 | |
16 | Press Ctrl+C to exit! | |
17 | ||
18 | """) | |
19 | ||
20 | bus = SMBus(1) | |
21 | bme280 = BME280(i2c_dev=bus) | |
22 | ||
ec075941 | 23 | |
9d2c6929 | 24 | # Get the temperature of the CPU for compensation |
a155e335 | 25 | def get_cpu_temperature(): |
10d81356 PH |
26 | with open("/sys/class/thermal/thermal_zone0/temp", "r") as f: |
27 | temp = f.read() | |
28 | temp = int(temp) / 1000.0 | |
29 | return temp | |
a155e335 | 30 | |
ec075941 | 31 | |
9d2c6929 SM |
32 | # Tuning factor for compensation. Decrease this number to adjust the |
33 | # temperature down, and increase to adjust up | |
87417b92 | 34 | factor = 0.8 |
a155e335 | 35 | |
9d2c6929 SM |
36 | cpu_temps = [0] * 5 |
37 | ||
a155e335 SM |
38 | while True: |
39 | cpu_temp = get_cpu_temperature() | |
9d2c6929 SM |
40 | # Smooth out with some averaging to decrease jitter |
41 | cpu_temps = cpu_temps[1:] + [cpu_temp] | |
42 | avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps)) | |
a155e335 | 43 | raw_temp = bme280.get_temperature() |
9d2c6929 | 44 | comp_temp = raw_temp - ((avg_cpu_temp - raw_temp) / factor) |
a155e335 SM |
45 | print("Compensated temperature: {:05.2f} *C".format(comp_temp)) |
46 | time.sleep(1.0) |