Skip to content

Instantly share code, notes, and snippets.

@archmangler
Created May 23, 2020 17:31
Show Gist options
  • Save archmangler/8e2adfabd5279b605e61f703df48af0f to your computer and use it in GitHub Desktop.
Save archmangler/8e2adfabd5279b605e61f703df48af0f to your computer and use it in GitHub Desktop.
rotary-encoder-example
/*     Arduino Rotary Encoder Tutorial
 *      
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *  
 */
 
 #define outputA 6
 #define outputB 7

 int counter = 0; 
 int aState;
 int aLastState;  

 void setup() { 
   pinMode (outputA,INPUT);
   pinMode (outputB,INPUT);
   
   Serial.begin (9600);
   // Reads the initial state of the outputA
   aLastState = digitalRead(outputA);   
 } 

 void loop() { 
   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 ++;
     } else {
       counter --;
     }
     Serial.print("Position: ");
     Serial.println(counter);
   } 
   aLastState = aState; // Updates the previous state of the outputA with the current state
 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment