/** stepper app controls the position and speed of stepper motor.
    position determined by the sensor num both + and -
    Pete Rogers 30/01/2009
    steps number is 400
**/
//constants pin declarations
int pinA =  9;
int pinB = 7;
int pinC = 10;
int pinD = 8;
int sensorPin = 0;
//stepper sequence at half step for higher resolution
int A[8] = {LOW,LOW,LOW,LOW,HIGH,HIGH,HIGH,LOW};
int B[8] = {LOW,LOW,HIGH,HIGH,HIGH,LOW,LOW,LOW};
int C[8] = {HIGH,HIGH,HIGH,LOW,LOW,LOW,LOW,LOW};
int D[8] = {HIGH,LOW,LOW,LOW,LOW,LOW,HIGH,HIGH};
//sketch variables
int cycle = 0; 
int stepperPos = 0;
int newPos = 0;
int mySpeed = 800;

void setup(){
  pinMode (pinA, OUTPUT);
  pinMode (pinB, OUTPUT);
  pinMode (pinC, OUTPUT);
  pinMode (pinD, OUTPUT);
  Serial.begin(9600);
}

void loop(){
    checkPosition();
    //moveStepper(800);
}

void checkPosition(){
  
   while (true){
   newPos = (analogRead(sensorPin) / 2.56f);
   //if in correct position turn stepper off (cools it down)
    if (newPos == stepperPos){
        digitalWrite(pinA, LOW);
        digitalWrite(pinB, LOW);
        digitalWrite(pinC, LOW);
        digitalWrite(pinD, LOW); 
        break;
       }
     // moves clockwise to new pos
     if (newPos > stepperPos){
        cycle ++;
        stepperPos ++;
        moveStepper(mySpeed);
        break;
     }
     // moves anticlockwise to new pos
     if (newPos < stepperPos){
       cycle --;
       stepperPos --;
       moveStepper(mySpeed);
       break;
     }
   }
 
}

void moveStepper(int delayTime){
  //sort cycle array ints
  if (cycle == 8){
       cycle = 0;
     }
     if (cycle == -1){
       cycle = 7;
  }
  //send to stepper
  digitalWrite(pinA, A[cycle]);
  digitalWrite(pinB, B[cycle]);
  digitalWrite(pinC, C[cycle]);
  digitalWrite(pinD, D[cycle]);
  delayMicroseconds(delayTime);
}