Rotary Encoder with Arduino

Description
    
      A Rotary Encoder is an electromechanical device that converts angular movement of the shaft to analog or digital code. Rotary Encoders can be found in radio equipment like amateur radio or hand held, where non-stop or continuous 3600 rotation is required for tuning to right frequency. In this project, the working of  Rotary Encoder is explained with the help of Arduino. Okey, let's see how it works.

Components Required

 1. Arduino UNO      * 1
 2. Rotary Encoder(KY-040)   * 1
 3. LCD(16*2)  * 1
 4.  Potentiometer(10K ohm)  * 1
 5. Bread Board  * 1
 6. Jumper Wires    * 1

Circuit Diagram












Program

/*
 * Power LCD and Rotary encoder from the +5V pin of Arduino
 * LCD RS -> pin 7
 * LCD EN -> pin 6
 * LCD D4 -> pin 5
 * LCD D5 -> pin 4
 * LCD D6 -> pin 3
 * LCD D7 -> pin 2
 * Encoder Switch -> pin 10
 * Encoder Output A -> pin 9
 * Encoder Output B -> pin 8
 */

int Encoder_OuputA  = 9;
int Encoder_OuputB  = 8;
int Encoder_Switch = 10;

int Previous_Output;
int Encoder_Count;

#include <LiquidCrystal.h>  //Default Arduino LCD Librarey is included 

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //Mention the pin number for LCD connection
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  lcd.begin(16, 2); //Initialise 16*2 LCD

  lcd.print(" Rotary Encoder "); //Intro Message line 1
  lcd.setCursor(0, 1);
  lcd.print("  With Arduino  "); //Intro Message line 2

  delay(2000);
  lcd.clear();

//pin Mode declaration 
  pinMode (Encoder_OuputA, INPUT);
  pinMode (Encoder_OuputB, INPUT);
  pinMode (Encoder_Switch, INPUT);

  Previous_Output = digitalRead(Encoder_OuputA); //Read the inital value of Output A
}

void loop() {
   //aVal = digitalRead(pinA);
   
   if (digitalRead(Encoder_OuputA) != Previous_Output)
   { 
     if (digitalRead(Encoder_OuputB) != Previous_Output) 
     { 
       Encoder_Count ++;
       lcd.clear();  
       lcd.print(Encoder_Count);
       lcd.setCursor(0, 1);  
       lcd.print("Clockwise");
     } 
     else 
     {
       Encoder_Count--;
       lcd.clear();  
       lcd.print(Encoder_Count);
       lcd.setCursor(0, 1);  
       lcd.print("Anti - Clockwise");
     }
   }

   Previous_Output = digitalRead(Encoder_OuputA);

   if (digitalRead(Encoder_Switch) == 0)
   {
     lcd.clear();  
     lcd.setCursor(0, 1);  
     lcd.print("Switch pressed");
   }
}