How to use a Rotary Encoder with Arduino

How to use a Rotary Encoder with Arduino

Rotary Encoder Arduino

 

INTRODUCTION

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.

APPLICATIONS

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.

WIRING DIAGRAM

GND – GND

VCC – 5V

CLK – Digital Pin 6

DT – Digital Pin 7

Rotary encoder arduino connections

 

CODE - Courtesy of Danny Van

 

/* Author: Danny van den Brande, Arduinosensors.nl
 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;
       RotPosition--;
     }
     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.   
       Serial.println("counterclockwise");
       digitalWrite (RedLed, LOW);
       digitalWrite (GreenLed, HIGH);
     }
     Serial.print("Encoder RotPosition: ");
     Serial.println(RotPosition);
     // this will print in the serial monitor.
     
   } 
   rotation = value;
 } 

END RESULT

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

ADDITIONAL RESOURCES

https://howtomechatronics.com/tutorials/arduino/rotary-encoder-works-use-arduino/

https://playground.arduino.cc/Main/RotaryEncoders/