To sanity-check the filtered result, also plot the raw value alongside it each time.
51 lines
1.1 KiB
Python
51 lines
1.1 KiB
Python
import math
|
|
import time
|
|
from cs1237 import CS1237
|
|
from machine import Pin
|
|
|
|
clock = Pin(2)
|
|
data = Pin(4)
|
|
|
|
ADC_RATE = 40
|
|
|
|
cs1237 = CS1237(clock, data)
|
|
cs1237.config(gain=1, rate=ADC_RATE)
|
|
|
|
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 = 100
|
|
FILTER_A = 1 / ADC_RATE / (FILTER_RC / 1 / ADC_RATE)
|
|
|
|
temperature_filtered = -1
|
|
# Ignore the first 5 seconds
|
|
last_report = time.ticks_ms() + 5000
|
|
while True:
|
|
raw_value = cs1237.read()
|
|
value = float(raw_value) / (2**24 - 1)
|
|
|
|
if value > 0.9999:
|
|
value = 0
|
|
else:
|
|
value = 10e3 * 1 / (1 / value - 1)
|
|
|
|
temperature = THERMISTOR_BETA / math.log(value / THERMISTOR_RINF) - 273.15
|
|
|
|
if temperature_filtered == -1:
|
|
temperature_filtered = temperature
|
|
|
|
temperature_filtered = (
|
|
temperature_filtered * (1 - FILTER_A) + temperature * FILTER_A
|
|
)
|
|
|
|
now = time.ticks_ms()
|
|
elapsed = now - last_report
|
|
if elapsed >= 200 or elapsed < 0:
|
|
print(f"{temperature:.6f},{temperature_filtered:.6f}")
|
|
last_report = now
|