#include <Arduino.h>
#line 1 "/home/arduino/ArduinoApps/demo_9_rotary_encoder/sketch/sketch.ino"
/*
 * Experiment 9: Rotary Encoder
 * Function: Read rotation direction and count, with button reset
 * Hardware: EP-0257 Shield + Incremental Encoder
 */

#define CLK_PIN 2   // Must connect to pin supporting external interrupt (D2 or D3)
#define DT_PIN  3
#define SW_PIN  4

volatile int counter = 0;
volatile byte lastState = 0;
bool swLastState = HIGH;

void setup() {
  pinMode(CLK_PIN, INPUT);
  pinMode(DT_PIN, INPUT);
  pinMode(SW_PIN, INPUT_PULLUP);
  
  // Enable external interrupt, trigger on CLK pin change
  attachInterrupt(digitalPinToInterrupt(CLK_PIN), readEncoder, CHANGE);
  
  Serial.begin(115200);
  Serial.println("Experiment 9: Encoder Test");
  Serial.println("Rotate encoder to observe count changes");
}

void loop() {
  // Button detection (debounced)
  bool swState = digitalRead(SW_PIN);
  if (swState == LOW && swLastState == HIGH) {
    counter = 0;
    Serial.println("Counter reset!");
    delay(200);  // Debounce
  }
  swLastState = swState;
  
  static int lastCounter = -1;
  if (counter != lastCounter) {
    Serial.print("Count: ");
    Serial.println(counter);
    lastCounter = counter;
  }
}

// Interrupt Service Routine
void readEncoder() {
  byte clkState = digitalRead(CLK_PIN);
  byte dtState = digitalRead(DT_PIN);
  
  // Determine rotation direction
  if (clkState != lastState) {
    if (dtState != clkState) {
      counter++;  // Clockwise
    } else {
      counter--;  // Counter-clockwise
    }
  }
  lastState = clkState;
}

