int midPoint = 1023 / 2;
int state = 0;
int delta = 100;
int thresholdHigh = (midPoint + delta);
int thresholdLow = (midPoint - delta);
int maxPeak = 0;
int minPeak = 1023;
int val;
const int Pot = A0;
uint32_t now;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
static uint32_t lastObsMs = 0;
now = millis();
if (now - lastObsMs > 20) {
val = analogRead(Pot);
switch (state) {
case 0: // low
if (val < minPeak) minPeak = val;
if (val > thresholdHigh) {
state = 1;
reportChange();
updateLimits();
maxPeak = 0;
}
break;
case 1: // high
if (val > maxPeak) maxPeak = val;
if (val < thresholdLow) {
state = 0;
reportChange();
updateLimits();
minPeak = 1023;
}
break;
}
lastObsMs = now;
}
report();
}
void reportChange() {
return;
Serial.print(val); Serial.print(state == 1 ? "^" : "v");
Serial.print("[");
Serial.print(minPeak);
Serial.print(",");
Serial.print(maxPeak);
Serial.print("] ");
if (state == 0 )Serial.println();
}
void updateLimits() {
long weight = 5;
switch (state) {
case 0: // low, so shift towards maxPeak
midPoint = (midPoint * weight + maxPeak) / (1 + weight);
break;
case 1: // high, so shift towards minPeak
midPoint = (midPoint * weight + minPeak) / (1 + weight);
break;
}
thresholdHigh = midPoint + delta;
thresholdLow = midPoint - delta;
}
void report() {
static uint32_t last = -1000;
char buff[80];
if (now - last > 100) {
last = now;
snprintf(buff, 80, "val:%d low:%d high:%d", val, thresholdLow, thresholdHigh );
Serial.println(buff);
}
}