Merge pull request #56 from roscoe81/master
[EVA-2020-02-2.git] / examples / compensated-temperature.py
... / ...
CommitLineData
1#!/usr/bin/env python3
2
3import time
4from bme280 import BME280
5
6try:
7 from smbus2 import SMBus
8except ImportError:
9 from smbus import SMBus
10
11import logging
12
13logging.basicConfig(
14 format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
15 level=logging.INFO,
16 datefmt='%Y-%m-%d %H:%M:%S')
17
18logging.info("""compensated-temperature.py - Use the CPU temperature
19to compensate temperature readings from the BME280 sensor.
20Method adapted from Initial State's Enviro pHAT review:
21https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441
22
23Press Ctrl+C to exit!
24
25""")
26
27bus = SMBus(1)
28bme280 = BME280(i2c_dev=bus)
29
30
31# Get the temperature of the CPU for compensation
32def get_cpu_temperature():
33 with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
34 temp = f.read()
35 temp = int(temp) / 1000.0
36 return temp
37
38
39# Tuning factor for compensation. Decrease this number to adjust the
40# temperature down, and increase to adjust up
41factor = 2.25
42
43cpu_temps = [get_cpu_temperature()] * 5
44
45while True:
46 cpu_temp = get_cpu_temperature()
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))
50 raw_temp = bme280.get_temperature()
51 comp_temp = raw_temp - ((avg_cpu_temp - raw_temp) / factor)
52 logging.info("Compensated temperature: {:05.2f} *C".format(comp_temp))
53 time.sleep(1.0)