How to use a Rotary Encoder with Arduino

How to use a Rotary Encoder with Arduino

Rotary Encoder Arduino



A rotary encoder is an electromechanical device that converts the angular position or motion of a shaft or axle to analog or digital output signals. It is also known as a shaft encoder.


The rotary encoder can be used in Industrial controls, photographic lenses, computer input devices such as optomechanical mice and trackballs, rheometers and rotating radar platforms.



VCC – 5V

CLK – Digital Pin 6

DT – Digital Pin 7

Rotary encoder arduino connections


CODE - Courtesy of Danny Van


/* Author: Danny van den Brande,
 This is a example on how to use the KY-040 Rotary encoder. 
 int CLK = 6;  // Pin 6 to clk on encoder
 int DT = 7;  // Pin 7 to DT on encoder
 int RedLed = 4;// You do not need to use the leds. 
                // you can take a look in the serial monitor if you dont have leds.
                // there it will display values. 
 int GreenLed = 5;
 int BlueLed = 6;
 int RotPosition = 0; 
 int rotation;  
 int value;
 boolean LeftRight;
 void setup() { 
   Serial.begin (9600);
   pinMode (CLK,INPUT);
   pinMode (DT,INPUT);
   pinMode (RedLed, OUTPUT);
   pinMode (GreenLed, OUTPUT);
   pinMode (BlueLed, OUTPUT);
   rotation = digitalRead(CLK);   
 void loop() { 
   value = digitalRead(CLK);
     if (value != rotation){ // we use the DT pin to find out which way we turning.
     if (digitalRead(DT) != value) {  // Clockwise
       RotPosition ++;
       LeftRight = true;
     } else { //Counterclockwise
       LeftRight = false;
     if (LeftRight){ // turning right will turn on red led.
       Serial.println ("clockwise");
       digitalWrite (RedLed, HIGH);
       digitalWrite (GreenLed, LOW);
     }else{        // turning left will turn on green led.   
       digitalWrite (RedLed, LOW);
       digitalWrite (GreenLed, HIGH);
     Serial.print("Encoder RotPosition: ");
     // this will print in the serial monitor.
   rotation = value;


Open the serial terminal and observe the position of the rotary encoder.