65 lines
1.1 KiB
C
Raw Permalink Normal View History

2022-07-13 14:30:59 +02:00
#pragma once
#include <Arduino.h>
static float alpha = 0.2;
static int baseline_fluctuation = 75;
static int max_s = 3000;
typedef struct SENSOR_t {
int PIN, base, num_base, max_c, v, prev;
int dv;
unsigned long timestamp_calib;
SENSOR_t(int& pin) {
PIN = pin;
max_c = max_s;
num_base = 0;
}
void baseline(int n, int d) {
int cum = 0;
for (int i = 0; i < n; i++){
update(false, false);
if(abs(dv) < baseline_fluctuation){
cum += v;
}
delay(d);
}
base = (int)(cum / n);
}
void calibrate() {
if(abs(dv) < baseline_fluctuation) {
num_base++;
if (num_base > 25)
base = (int) (alpha * (float)v + (1.0 - alpha) * (float)base);
} else {
num_base = 0;
}
if(v > max_c) max_c = v;
timestamp_calib = millis();
}
void update(bool calib = true, bool filt = true) {
int d = touchRead(PIN);
if(filt)
v = filter(d);
else
v = d;
dv = v - prev;
prev = v;
if(calib) calibrate();
}
int map_range(int min_v, int max_v) {
return map(v, base, max_c, min_v, max_v);
}
int filter(int n) {
return (int) (alpha * n + (1.0 - alpha) * prev);
}
};