#include <Arduino.h>
#include <Stepper.h>
const uint8_t CLK_PIN = 2;
const uint8_t DT_PIN = 3;
const uint8_t SWITCH_PIN = 4;
Stepper motor(32, 8, 10, 9, 11);  // Same rotor-step units as Lesson 32.
// volatile tells the compiler these values are changed by an interrupt outside loop().
volatile int8_t pendingTurns = 0;
volatile unsigned long lastEdgeMicros = 0;
int32_t commandedSteps = 0;  // A software count, not a measurement of physical shaft position.
bool switchWasDown = false;
void encoderEdge() {
  const unsigned long now = micros();
  if (now - lastEdgeMicros < 4000UL) return;  // Reject close contact-bounce edges without waiting.
  lastEdgeMicros = now;
  // On a falling CLK edge, the source's !DT rule makes HIGH request +50 steps.
  const int8_t direction = digitalRead(DT_PIN) ? 1 : -1;
  if ((direction > 0 && pendingTurns < 20) || (direction < 0 && pendingTurns > -20))
    pendingTurns += direction;  // Bounded queue: turn slowly while the blocking motor catches up.
}
void releaseMotor() {
  for (uint8_t pin = 8; pin <= 11; ++pin) digitalWrite(pin, LOW);
}
void setup() {
  pinMode(CLK_PIN, INPUT_PULLUP); pinMode(DT_PIN, INPUT_PULLUP); pinMode(SWITCH_PIN, INPUT_PULLUP);
  // Ask the board mapping for the interrupt instead of assuming a hardware interrupt number.
  attachInterrupt(digitalPinToInterrupt(CLK_PIN), encoderEdge, FALLING);
  motor.setSpeed(700);  // Internal-rotor RPM; about 10.9 nominal geared-output RPM.
}
void loop() {
  const bool switchDown = digitalRead(SWITCH_PIN) == LOW;
  if (switchDown && !switchWasDown) {
    // Return in int-sized chunks; Stepper.step accepts a 16-bit int on the Mega.
    while (commandedSteps != 0) {
      const int chunk = commandedSteps > 2048 ? 2048 : (commandedSteps < -2048 ? -2048 : int(commandedSteps));
      motor.step(-chunk); commandedSteps -= chunk;
    }
    noInterrupts(); pendingTurns = 0; interrupts();  // Discard turns arriving during the return.
  } else if (!switchDown) {
    // Copy and consume ONE queued event atomically, then let interrupts run during stepping.
    noInterrupts();
    const int8_t direction = pendingTurns > 0 ? 1 : (pendingTurns < 0 ? -1 : 0);
    pendingTurns -= direction;
    interrupts();
    if (direction != 0) {
      const int steps = direction * 50;
      motor.step(steps); commandedSteps += steps;
    }
  }
  switchWasDown = switchDown;
  releaseMotor();  // Released coils do not hold position; slip invalidates the software origin.
}
