temp: Actually calculate temperature values

Do the monster math to convert ADC readings into appropriate temperature
values.  The absolute result is way off but it seems to respond sanely
in relative terms.

Additionally, apply a low pass filter with f=1Hz to smoothen the noise a
tiny bit.
This commit is contained in:
Rahix 2025-08-24 02:33:22 +02:00
parent 25ce0ebdff
commit f481e4de38

View file

@ -1,20 +1,40 @@
import time
import math
from cs1237 import CS1237
from machine import Pin
clock = Pin(2)
data = Pin(4)
cs1237 = CS1237(clock, data)
cs1237.config(gain=1)
ADC_RATE = 40
cs1237 = CS1237(clock, data)
cs1237.config(gain=1, rate=ADC_RATE)
print(repr(cs1237.get_config()))
THERMISTOR_BETA = 3950.0
THERMISTOR_R25 = 10e3
THERMISTOR_RINF = THERMISTOR_R25 * math.exp(-THERMISTOR_BETA / 298.15)
# Filter constant in seconds
FILTER_RC = 1
FILTER_A = 1 / ADC_RATE / (FILTER_RC / 1 / ADC_RATE)
temperature_filtered = 25
while True:
raw_value = cs1237.read()
value = float(raw_value) / (2**23 - 1)
value = float(raw_value) / (2**24 - 1)
if value > 0.9999:
value = 0
else:
value = 1 / (1 / value - 1)
temperature = 25 - value
if abs(temperature) < 50:
print(temperature)
value = 10e3 * 1 / (1 / value - 1)
temperature = THERMISTOR_BETA / math.log(value / THERMISTOR_RINF) - 273.15
temperature_filtered = (
temperature_filtered * (1 - FILTER_A) + temperature * FILTER_A
)
print(temperature_filtered)