|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import time |
| 4 | +import bme680 |
| 5 | +from subprocess import PIPE, Popen |
| 6 | + |
| 7 | +try: |
| 8 | + from smbus2 import SMBus |
| 9 | +except ImportError: |
| 10 | + from smbus import SMBus |
| 11 | + |
| 12 | +print("""compensated-temperature.py - Use the CPU temperature to compensate temperature |
| 13 | +readings from the BME680 sensor. Method adapted from Initial State's Enviro pHAT |
| 14 | +review: https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441 |
| 15 | +
|
| 16 | +Press Ctrl+C to exit! |
| 17 | +
|
| 18 | +""") |
| 19 | + |
| 20 | +try: |
| 21 | + sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY) |
| 22 | +except IOError: |
| 23 | + sensor = bme680.BME680(bme680.I2C_ADDR_SECONDARY) |
| 24 | + |
| 25 | +# These oversampling settings can be tweaked to |
| 26 | +# change the balance between accuracy and noise in |
| 27 | +# the data. |
| 28 | + |
| 29 | +sensor.set_humidity_oversample(bme680.OS_2X) |
| 30 | +sensor.set_pressure_oversample(bme680.OS_4X) |
| 31 | +sensor.set_temperature_oversample(bme680.OS_8X) |
| 32 | +sensor.set_filter(bme680.FILTER_SIZE_3) |
| 33 | + |
| 34 | +# Gets the CPU temperature in degrees C |
| 35 | +def get_cpu_temperature(): |
| 36 | + process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) |
| 37 | + output, _error = process.communicate() |
| 38 | + return float(output[output.index('=') + 1:output.rindex("'")]) |
| 39 | + |
| 40 | +factor = 1.0 # Smaller numbers adjust temp down, vice versa |
| 41 | +smooth_size = 10 # Dampens jitter due to rapid CPU temp changes |
| 42 | + |
| 43 | +cpu_temps = [] |
| 44 | + |
| 45 | +while True: |
| 46 | + if sensor.get_sensor_data(): |
| 47 | + cpu_temp = get_cpu_temperature() |
| 48 | + cpu_temps.append(cpu_temp) |
| 49 | + |
| 50 | + if len(cpu_temps) > smooth_size: |
| 51 | + cpu_temps = cpu_temps[1:] |
| 52 | + |
| 53 | + smoothed_cpu_temp = sum(cpu_temps) / float(len(cpu_temps)) |
| 54 | + raw_temp = sensor.data.temperature |
| 55 | + comp_temp = raw_temp - ((smoothed_cpu_temp - raw_temp) / factor) |
| 56 | + |
| 57 | + print("Compensated temperature: {:05.2f} *C".format(comp_temp)) |
| 58 | + |
| 59 | + time.sleep(1.0) |
0 commit comments