/*
    Rotary Encoder - Interrupt Example
    
    The circuit:
    * encoder pin A to Arduino pin 2
    * encoder pin B to Arduino pin 3
    * encoder ground pin to ground (GND)
*/

#include "Rotary.h"

Rotary r = Rotary(PIN_PE5, PIN_PE6);

int counter = 0;
const int pushButton = PIN_PE4;

const int DEBOUNCE_DELAY = 50;

// Variables will change:
int lastSteadyState = LOW;       // the previous steady state from the input pin
int lastFlickerableState = LOW;  // the previous flickerable state from the input pin
int currentState;                // the current reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled

void setup() {
  Serial.begin(115200);
  r.begin();
  pinMode(PIN_PE4, INPUT);
}

void loop() {
  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("CW");
  }
  else if (result == DIR_CCW) {
    Serial.println("CCW");
  }


  currentState = digitalRead(PIN_PE4);

  if (currentState != lastFlickerableState) {
    lastDebounceTime = millis();
    lastFlickerableState = currentState;
  }

  if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
    if (lastSteadyState == HIGH && currentState == LOW)
      Serial.println("The button is pressed");
    else if (lastSteadyState == LOW && currentState == HIGH)
      Serial.println("The button is released");
    lastSteadyState = currentState;
  }
  
}
