26 #ifndef AnalogMonitor_h
27 #define AnalogMonitor_h
74 AnalogMonitor(
byte pin,
bool sleepEnable =
true,
float snapMultiplier = 0.01)
76 begin(pin, sleepEnable, snapMultiplier);
88 void begin(
byte pin,
bool sleepEnable =
true,
float snapMultiplier = 0.01)
91 digitalWrite(pin, LOW);
94 fSleepEnable = sleepEnable;
103 return fResponsiveValue;
119 return fResponsiveValueHasChanged;
134 fRawValue = analogRead(fPin);
135 fPrevResponsiveValue = fResponsiveValue;
136 fResponsiveValue = getResponsiveValue(fRawValue);
137 fResponsiveValueHasChanged = (fResponsiveValue != fPrevResponsiveValue);
143 (newMultiplier > 1.0) ? 1.0 :
144 (newMultiplier < 0.0) ? 0.0 : newMultiplier;
154 fSleepEnable =
false;
159 fEdgeSnapEnable =
true;
167 fEdgeSnapEnable =
false;
172 fActivityThreshold = newThreshold;
181 fAnalogResolution = resolution;
188 int fAnalogResolution = 4096;
191 int fAnalogResolution = 1024;
193 float fSnapMultiplier;
195 float fActivityThreshold = 4.0;
196 bool fEdgeSnapEnable =
true;
199 unsigned long fLastActivityMS;
200 float fErrorEMA = 0.0;
201 bool fSleeping =
false;
204 int fResponsiveValue;
205 int fPrevResponsiveValue;
206 bool fResponsiveValueHasChanged;
208 int getResponsiveValue(
int newValue)
213 if (fSleepEnable && fEdgeSnapEnable)
215 if (newValue < fActivityThreshold)
217 newValue = (newValue * 2) - fActivityThreshold;
219 else if (newValue > fAnalogResolution - fActivityThreshold)
221 newValue = (newValue * 2) - fAnalogResolution + fActivityThreshold;
226 unsigned int diff = abs(newValue - fSmoothValue);
231 fErrorEMA += ((newValue - fSmoothValue) - fErrorEMA) * 0.4;
237 fSleeping = abs(fErrorEMA) < fActivityThreshold;
243 if (fSleepEnable && fSleeping)
245 return (
int)fSmoothValue;
257 float snap = snapCurve(diff * fSnapMultiplier);
267 fSmoothValue += (newValue - fSmoothValue) * snap;
270 if (fSmoothValue < 0.0)
274 else if (fSmoothValue > fAnalogResolution - 1)
276 fSmoothValue = fAnalogResolution - 1;
280 return (
int)fSmoothValue;
283 static inline float snapCurve(
float x)
285 float y = 1.0 / (x + 1.0);
287 return (y > 1.0) ? 1.0: y;