#include <Arduino.h>
#line 1 "/home/arduino/ArduinoApps/demo_10_stepper_motor/sketch/sketch.ino"
/*
 * Experiment 10: Stepper Motor Control
 * Function: Forward, reverse, and stop control
 * Hardware: EP-0257 Shield + 28BYJ-48 + ULN2003
 */

#define IN1 8
#define IN2 9
#define IN3 10
#define IN4 11

// 4-phase 8-step sequence (half-step mode, higher precision)
const int stepSequence[8][4] = {
  {1, 0, 0, 0},
  {1, 1, 0, 0},
  {0, 1, 0, 0},
  {0, 1, 1, 0},
  {0, 0, 1, 0},
  {0, 0, 1, 1},
  {0, 0, 0, 1},
  {1, 0, 0, 1}
};

void setup() {
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  
  Serial.begin(115200);
  Serial.println("Experiment 10: Stepper Motor");
  Serial.println("Commands: F=Forward, B=Backward, S=Stop");
}

void loop() {
  if (Serial.available()) {
    char cmd = Serial.read();
    if (cmd == 'F' || cmd == 'f') {
      Serial.println("Forward...");
      rotate(4096, true, 2);   // 4096 steps = ~1 rotation, 2ms per step
    }
    else if (cmd == 'B' || cmd == 'b') {
      Serial.println("Backward...");
      rotate(4096, false, 2);
    }
    else if (cmd == 'S' || cmd == 's') {
      stopMotor();
      Serial.println("Stopped");
    }
  }
}

void setStep(int w1, int w2, int w3, int w4) {
  digitalWrite(IN1, w1);
  digitalWrite(IN2, w2);
  digitalWrite(IN3, w3);
  digitalWrite(IN4, w4);
}

void rotate(int steps, bool clockwise, int delayMs) {
  for (int i = 0; i < steps; i++) {
    int idx = clockwise ? (i % 8) : (7 - (i % 8));
    setStep(stepSequence[idx][0], stepSequence[idx][1], 
            stepSequence[idx][2], stepSequence[idx][3]);
    delay(delayMs);
  }
  stopMotor();
}

void stopMotor() {
  setStep(0, 0, 0, 0);
}

