Skip to content

Commit 9d2c692

Browse files
Improvements to compensated temperature code
1 parent d7b32da commit 9d2c692

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

examples/all-in-one.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from bme280 import BME280
1111
from pms5003 import PMS5003
1212
from enviroplus import gas
13+
from subprocess import PIPE, Popen
1314
from PIL import Image
1415
from PIL import ImageDraw
1516
from PIL import ImageFont
@@ -76,6 +77,18 @@ def display_text(variable, data, unit):
7677
draw.text((0, 0), message, font=font, fill=(0, 0, 0))
7778
st7735.display(img)
7879

80+
# Get the temperature of the CPU for compensation
81+
def get_cpu_temperature():
82+
process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
83+
output, _error = process.communicate()
84+
return float(output[output.index('=') + 1:output.rindex("'")])
85+
86+
# Tuning factor for compensation. Decrease this number to adjust the
87+
# temperature down, and increase to adjust up
88+
factor = 0.8
89+
90+
cpu_temps = [0] * 5
91+
7992
delay = 0.5 # Debounce the proximity tap
8093
mode = 0 # The starting mode
8194
last_page = 0
@@ -113,7 +126,12 @@ def display_text(variable, data, unit):
113126
if mode == 0:
114127
variable = "temperature"
115128
unit = "C"
116-
data = bme280.get_temperature()
129+
cpu_temp = get_cpu_temperature()
130+
# Smooth out with some averaging to decrease jitter
131+
cpu_temps = cpu_temps[1:] + [cpu_temp]
132+
avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps))
133+
raw_temp = bme280.get_temperature()
134+
data = raw_temp - ((avg_cpu_temp - raw_temp) / factor)
117135
display_text(variable, data, unit)
118136

119137
if mode == 1:

examples/compensated-temperature.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,24 @@
2020
bus = SMBus(1)
2121
bme280 = BME280(i2c_dev=bus)
2222

23+
# Get the temperature of the CPU for compensation
2324
def get_cpu_temperature():
2425
process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
2526
output, _error = process.communicate()
2627
return float(output[output.index('=') + 1:output.rindex("'")])
2728

29+
# Tuning factor for compensation. Decrease this number to adjust the
30+
# temperature down, and increase to adjust up
2831
factor = 0.8
2932

33+
cpu_temps = [0] * 5
34+
3035
while True:
3136
cpu_temp = get_cpu_temperature()
37+
# Smooth out with some averaging to decrease jitter
38+
cpu_temps = cpu_temps[1:] + [cpu_temp]
39+
avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps))
3240
raw_temp = bme280.get_temperature()
33-
comp_temp = raw_temp - ((cpu_temp - raw_temp) / factor)
41+
comp_temp = raw_temp - ((avg_cpu_temp - raw_temp) / factor)
3442
print("Compensated temperature: {:05.2f} *C".format(comp_temp))
3543
time.sleep(1.0)

0 commit comments

Comments
 (0)