/*     Arduino Rotary Encoder Tutorial
 *      
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *  
 */
 int timer = 0;
 int timers = 0;
 int count = 0;

 int outputA[] {2,4,6,8};
 int outputB[] {3,5,7,9}; 

 int counter[] = {0,0,0,0}; 
 int aState[] = {0,0,0,0};
 int aLastState[]={0,0,0,0};  
 void setup() { 
  for (int i = 0; i<4; i++){
   pinMode (outputA[i],INPUT);
   pinMode (outputB[i],INPUT);
  }
  pinMode (A0, OUTPUT);
   Serial.begin (9600);
   // Reads the initial state of the outputA
   for(int i=0;i<4;i++){
        aLastState[i] = digitalRead(outputA[i]);   
   }
 } 
 void loop() { 
   timer = millis();
   for(int i=0;i<4;i++){
   aState[i] = digitalRead(outputA[i]); // Reads the "current" state of the outputA

 
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
   if (aState[i] != aLastState[i]){     
     // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(outputB[i]) != aState[i]) { 
       counter[i] ++;
     } else {
       counter[i] --;
     }
     Serial.print("Position for ");
     Serial.print(i);
     Serial.print(":  ");
     Serial.println(counter[i]);
     if(counter[0] > -4 && counter[0] < 4 && counter[1] > -4 && counter[1] < 4 && counter[2] > -4 && counter[2] < 4 && counter[3] > -4 && counter[3] < 4){
      Serial.println("yup");
      digitalWrite(A0,HIGH);
     }
     else{
      digitalWrite(A0,LOW);
     }
   } 
   aLastState[i] = aState[i]; // Updates the previous state of the outputA with the current state

 }
 }
