#include "ExponentialFilter.h"

#define BUTTON_PIN A0

#define MIN_INPUT 0.0
#define MAX_INPUT 1.0

const float lowerThreshold = 0.293 * (MAX_INPUT - MIN_INPUT);
const float upperThreshold = 0.707 * (MAX_INPUT - MIN_INPUT);

ExponentialFilter expButton;

bool trigger;
bool toggle;

void setup() {
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);

  expButton.expMode(AUTO);             // Exponential Filter in Auto Mode
  expButton.expCutoffTime(MS2S(10));   // Debounce Period = 20 milliseconds
  expButton.expInit(1.0);              // INPUT = 0.0, INPUT_PULLUP = 1.0
}

void loop() {
  bool prevTrigger = trigger;
  float returnValue = expButton.expFilter(digitalRead(BUTTON_PIN));
  Trigger(returnValue, &trigger);
  if (trigger & !prevTrigger) {
    toggle = !toggle;
    digitalWrite(LED_BUILTIN, toggle);
  }
  SerialPlot();
}

void Trigger(float value, bool *trigger) {
  if (value < upperThreshold) *trigger = true;
  if (value > upperThreshold) *trigger = false;
}

void SerialPlot() {
  static unsigned long startTime;
  unsigned long currTime = millis();
  if (currTime - startTime < 10UL) return;
  startTime = currTime;
  Serial.println(
    "Trigger:" + String(trigger, 2)
    + ", Toggle:" + String(toggle, 2)
    //+ ", Input:" + String(expButton.output, 2)
    //+ ", Output:" + String(expButton.output, 2)
  );
}