How to interface KY-040 Rotary encoder with Arduino

What is a Rotary encoder, how rotary encoder work, and how to use a rotary encoder with Arduino are some questions that may arise in your mind when programming an Arduino.
Hello, guys welcome back to my blog today we are going to see about the 360 Degree KY 040 Rotary Encoder Module.

What is a rotary encoder??

The rotary encoder is a position sensor to determine the angular position of a rotating object and generate an equivalent signal depending upon the rotational moment. The rotary encoder is an electro-mechanical device that converts physical motion to electrical analog and digital output signals.
rotary encoder with push button

Rotary encoder measures movement and displacements. Rotary encoders translate the mechanical rotational motion into an electronic signal. A rotary encoder provides accurate or precise information about movement, position & rotation direction.

Suppose you have an RC car and you want to measure how much distance your car travels from point A to point B.

optical encoder Arduino

So here we will use an optical rotary encoder, on one side there is optical light and on another side of the wheel there is a light detector. We know that there are four dark sides we will count how many times the dark side occurred i.e. how many times we see light in our case we have four dark sides so we will see 5 times light which means 1 revolution. Therefore by calculating such many revolutions we can come to know the distance covered. Note we cannot use the time concept here to calculate the distance because the speed of the motor depends upon the voltage applied. If the battery is drained then the motor will rotate at a slower speed.

Another example where the rotary encoder is used is our mouse scroll button, there we have an optical encoder to detect the revolution of the scroll.

In this chapter, we are going to learn about the quadrature encoder and how it works.

How Rotary encoder Works??


rotary encoder module

The rotary encoder consists of a disk with evenly spaced contact zones that are connected to the three pins, pins A, B, and C where pin C is the ground pin. Inside this encoder, there are slotted disks connected to common ground and two contact pins A & B. when we rotate the knob then the pins A and pin B come in contact with the disk. When this contact occurs current flows through that pin, thus giving outputs 1 & 0. This generates square wave waveforms both at pin A and pins B. by analyzing both waveforms we can determine in which direction the knob is rotating.

Rotary encoder working principle

When you turn the knob clockwise direction then pin A comes in contact first then pin B. when they come in contact with the common ground then they produce signals. As pin A is connected first then pin b. the signal produced is 90 ° out of phase with each other.

When you turn the knob in an anticlockwise direction then pin B will make first contact with the disk than point A, therefore, both signals will differ from each other as shown below diagram.

Parts Required

  • KY-040 (Rotary encoder module Arduino)
  • Jumper wires
  • Breadboard 

Schematic Diagram

rotary encoder Arduino

Connect the ground pin of the rotary encoder to the ground pin, VCC pin to 5v, CLK pin to 12, DT to 11, and (SW) Switch to 10 pins of Arduino.

Code -

int point_A = 12;                   // Set CLK pin at Arduino pin 12
int point_B = 11;                   // Set DT pin at Arduino pin 11
int Switch = 10;                    // Set switch pin at Arduino pin 10
int button;                         // initialize variable to store data
int old_Position;                   // initialize variable to store data
int Output_A;                      //  initialize variable to store point A data
int Output_B;                      //  initialize variable to store point B data
int i=0;                           //  initialize value of i=0 for increment and decrement counter
void setup() 

pinMode(point_A,INPUT);            // CLK pin pin set to INPUT           
pinMode(point_B,INPUT);            // DT pin pin set to INPUT
pinMode(Switch,INPUT_PULLUP);      // Switch pin set to INPUT (in-built input pull reistor)
Serial.begin(115200);             // set baudrate for Serial communication
}
void loop() 
{
 Output_A = digitalRead(point_A);    // read values from CLK pin and store in variable
 Output_B = digitalRead(point_B);    // read values from DT pin and store in variable
 button   = digitalRead(Switch);     // read values from Switch pin and store in variable
 if(button == LOW)                   // checking condition whether button is pressed or not
 {
  Serial.println("Button pressed");  
  delay(200);
 } 
  
 if (Output_A != old_Position)       // checking condition if shaft moved or not
 {
  if(Output_A != Output_B)           // if shaft has moment then again checking condition if A is not equal to B
  {
    i--;
    Serial.print("counter:");       // if condition satisfies then value of i will increment
    Serial.println(i);
    }
 else if(Output_A == Output_B)      // checking another condition if A equal to B
 {
  i++;
  Serial.print("counter:");         // if condition satisfies then value of i will decrement
  Serial.println(i); 
  } 
 } 
     old_Position = Output_A;       // value to previous rotation is store in variable for comparsion with new movement
}

First, initialize pins of rotary encoder and variable to store data. We initialize i=0 which will be increment or decrement. In the void setup, we configure pins as INPUT or OUTPUT. We want to read values from the rotary encoder so we will declare it as INPUT. Also, we configure the baud rate to 115200.

In the void loop, we read values from point A and point B and also from the switch pin which we store in a variable. Now we will check the condition of the rotary shaft is moved (rotated) or not. If we rotate the shaft then the condition is satisfied and we will enter if condition to check the output of point A and point B.

if point A is not equal to point B then the shaft is moved in the clockwise direction value of the counter i will decrement i-- and if point A is equal to point B then the shaft is moved in the anti-clockwise direction value of the counter i will increment i ++. After that, the position of the previous shaft is stored to variable name Old position which is then compared with the new value of shaft moment.


Output - 

ky040

Now we used the serial monitor to observe the output. . To open up the serial monitor, click on Tools > Serial Monitor or use the shortcut (SHIFT + CONTROL + M). You can see output on the Serial monitor. when we rotate the shaft clockwise counter gets increments & when we rotate the shaft in the anti-clockwise counter decrements and if we press the button it will show the button pressed in the serial monitor.

How to control LEDs with a rotary encoder?? 

ky-040 Arduino example

Connect the negative terminal of all LEDs to the GND pin of the Arduino
Connect positive pin of LED 1 to PIN no 1 of Arduino
Connect positive pin of LED 2 to PIN no 2 of Arduino
Connect positive pin of LED 3 to PIN no 3 of Arduino
Connect positive pin of LED 4 to PIN no 4 of Arduino
Connect the positive pin of LED 5 to PIN no 5 of Arduino
Connect positive pin of LED 6 to PIN no 6 of Arduino
Connect positive pin of LED 7 to PIN no 7 of Arduino
Connect positive pin of LED 8 to PIN no 8 of Arduino
Connect positive pin of LED 9 to PIN no 9 of Arduino
Connect positive pin of LED 10 to PIN no 10 of Arduino

Code 

int point_A = 12;                   // Set CLK pin at Arduino pin 12
int point_B = 11;                   // Set DT pin at Arduino pin 11
int button;                         // initialize variable to store data
int old_Position;                   // initialize variable to store data
int Output_A;                      //  initialize variable to store point A data
int Output_B;                      //  initialize variable to store point B data
int i=0;                           //  initialize value of i=0 for increment and decrement counter
int leds[]={1,2,3,4,5,6,7,8,9,10};  // initialize arrays of led pins of Arduino


void setup() 

pinMode(point_A,INPUT);            // CLK pin pin set to INPUT           
pinMode(point_B,INPUT);            // DT pin pin set to INPUT
Serial.begin(115200);             // set baudrate for Serial communication
for(int j=0;j<sizeof(leds);j++)   // set arrays of led pin to OUTPUT

  pinMode(leds[j],OUTPUT); 
  
  }  
}
void loop() 
{
 Output_A = digitalRead(point_A);    // read values from CLK pin and store in variable
 Output_B = digitalRead(point_B);    // read values from DT pin and store in variable
  
 if (Output_A != old_Position)       // checking condition if shaft moved or not
 {
  if(Output_A != Output_B)           // if shaft has moment then again checking condition if A is not equal to B
  {
    i--;
    Serial.print("counter:");       // if condition satisfies then value of i will increment
    Serial.println(i);
    digitalWrite(leds[i],LOW);      // turn led OFF
    }
 else if(Output_A == Output_B)      // checking another condition if A equal to B
 {
  i++;
  Serial.print("counter:");         // if condition satisfies then value of i will decrement
  Serial.println(i); 
  if(i>0)
  {
   digitalWrite(leds[i],HIGH);      // turn led ON
   }
 } 
     old_Position = Output_A;       // value to previous rotation is store in variable for comparsion with new movement
}
}

Conclusion - 

Today we learn about what is a rotary encoder, how to use a rotary encoder with Arduino, the application of a rotary encoder & working principle of the rotary encoder.


"I hope you find this IoT blog very helpful to you. In the upcoming lesson, we will see more about IoT sensors till then bye. See you all in my next blog."
Close Menu