-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSensor.cpp
More file actions
41 lines (37 loc) · 1021 Bytes
/
Copy pathSensor.cpp
File metadata and controls
41 lines (37 loc) · 1021 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "Sensor.h"
#include <math.h> // log()
Sensor::Sensor(int analogPin,
float rFixed,
float beta,
float t0Kelvin,
float alpha)
: pin(analogPin),
R_FIXED(rFixed),
B(beta),
T0(t0Kelvin),
alphaFilter(alpha),
firstRun(true),
filteredTemp(0.0f)
{
}
void Sensor::update() {
float rawTemp = readNTCTemp();
if (firstRun) {
filteredTemp = rawTemp;
firstRun = false;
} else {
// Exponential Moving Average
filteredTemp = alphaFilter * rawTemp + (1 - alphaFilter) * filteredTemp;
}
}
float Sensor::getTemperature() const {
return filteredTemp;
}
// Beta-Formel: ADC -> Spannung -> R_NTC -> Kelvin -> °C
float Sensor::readNTCTemp() {
int raw = analogRead(pin);
float rNtc = R_FIXED * (1023.0 / (float)raw - 1.0); // float rNtc = R_FIXED / (1023.0 / (float)raw - 1.0) if NTC between GND and fixed R
rNtc = (1.0f / T0) + (1.0f / B) * log(rNtc / R_FIXED);
float tKelvin = 1.0f / rNtc;
return (tKelvin - 273.15f);
}