#pragma once #include 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); } };