/* read rotary encoder in a loop */ // defines #define outputA 6 // rotary a #define outputB 7 // rotary b #define outputC 5 // rotary button #define next 4 // pin out next #define prev 3 // pin out prev #define play 2 // pin out play int detentN = 3; // clicks before next int detentP = -3; // clicks before prev int counter = 0; int aState; int Button = 0; int aLastState; int initDelay = 5; int DelayCounter = 0; // start void setup() { /* hold play, init outputs & pause then release play */ pinMode (outputA,INPUT); pinMode (outputB,INPUT); pinMode (outputC,INPUT); digitalWrite(play,LOW); digitalWrite(next,HIGH); digitalWrite(prev,HIGH); // press play button pinMode (prev,OUTPUT); pinMode (next,OUTPUT); pinMode (play,OUTPUT); // Serial.begin (9600); while (DelayCounter != initDelay) { DelayCounter++; } digitalWrite(play,HIGH); // release play button aLastState = digitalRead(outputA); Button = digitalRead(outputC); } /* main loop */ void loop() { Button = digitalRead(outputC); /* button is pressed? */ aState = digitalRead(outputA); /* 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 != aLastState) { /* If the outputB state is different to the outputA state, that means the encoder is rotating clockwise */ if (digitalRead(outputB) != aState) { counter ++; if (counter == detentN) { /* clockwise -> next track */ digitalWrite(next, LOW); while (DelayCounter != initDelay) { DelayCounter++; } digitalWrite(next, HIGH); } } else { counter --; if (counter == detentP) { /* anticlockwise <- prev track */ digitalWrite(prev, LOW); while (DelayCounter != initDelay) { DelayCounter++; } digitalWrite(prev, HIGH); } } // Serial.print("Position: "); // Serial.println(counter); } aLastState = aState; // Updates the previous state of the outputA with the current state }