97 lines
1.8 KiB
C
97 lines
1.8 KiB
C
|
|
#pragma once
|
||
|
|
|
||
|
|
// #include <Arduino.h>
|
||
|
|
#include <FastTouch.h>
|
||
|
|
|
||
|
|
static float alpha = 0.2;
|
||
|
|
static int baseline_fluctuation = 5;
|
||
|
|
static int baseline_fluctuation_hits = 100;
|
||
|
|
static int max_s = 60;
|
||
|
|
|
||
|
|
typedef void(*toggle_cb)(bool, int);
|
||
|
|
|
||
|
|
struct SENSOR_t {
|
||
|
|
|
||
|
|
int PIN, base, num_base, max_c, v, prev, raw, cutoff_s;
|
||
|
|
int dv;
|
||
|
|
unsigned long timestamp_calib;
|
||
|
|
toggle_cb fn_toggle_cb;
|
||
|
|
bool call_toggle = false;
|
||
|
|
|
||
|
|
SENSOR_t(const int& pin, int cutoff) {
|
||
|
|
PIN = pin;
|
||
|
|
max_c = max_s;
|
||
|
|
num_base = 0;
|
||
|
|
cutoff_s = cutoff;
|
||
|
|
fn_toggle_cb = NULL;
|
||
|
|
}
|
||
|
|
|
||
|
|
void plug_toggle_cb(toggle_cb fn) {
|
||
|
|
fn_toggle_cb = fn;
|
||
|
|
}
|
||
|
|
|
||
|
|
void baseline(int n, int d) {
|
||
|
|
float cum = 0;
|
||
|
|
for (int i = 0; i < n; i++){
|
||
|
|
update(false, false);
|
||
|
|
if(abs(dv) < baseline_fluctuation){
|
||
|
|
cum += v;
|
||
|
|
}
|
||
|
|
delay(d);
|
||
|
|
|
||
|
|
}
|
||
|
|
base = (int)floor(cum / n);
|
||
|
|
}
|
||
|
|
|
||
|
|
void calibrate() {
|
||
|
|
// if(abs(dv) < baseline_fluctuation) {
|
||
|
|
// num_base++;
|
||
|
|
// if (num_base > baseline_fluctuation_hits)
|
||
|
|
// 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) {
|
||
|
|
raw = fastTouchRead(PIN);
|
||
|
|
if(filt)
|
||
|
|
v = filter(raw);
|
||
|
|
else
|
||
|
|
v = raw;
|
||
|
|
dv = v - prev;
|
||
|
|
if(calib) calibrate();
|
||
|
|
|
||
|
|
if(fn_toggle_cb) {
|
||
|
|
int m_v = map(v, base, max_c, 0, 100);
|
||
|
|
int m_prev = map(prev, base, max_c, 0, 100);
|
||
|
|
if(m_prev < cutoff_s && m_v >= cutoff_s)
|
||
|
|
fn_toggle_cb(true, PIN);
|
||
|
|
else if(m_prev > cutoff_s && m_v <= cutoff_s)
|
||
|
|
fn_toggle_cb(false, PIN);
|
||
|
|
}
|
||
|
|
|
||
|
|
prev = v;
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
int map_range(int min_v, int max_v) {
|
||
|
|
return map(v, base, max_c, min_v, max_v);
|
||
|
|
}
|
||
|
|
|
||
|
|
int map_range_raw(int min_v, int max_v) {
|
||
|
|
return map(raw, base, max_c, min_v, max_v);
|
||
|
|
}
|
||
|
|
|
||
|
|
int filter(int n) {
|
||
|
|
return (int) (alpha * n + (1.0 - alpha) * prev);
|
||
|
|
}
|
||
|
|
|
||
|
|
bool touch() {
|
||
|
|
return (v > cutoff_s);
|
||
|
|
}
|
||
|
|
|
||
|
|
};
|