Description
Arduino rotary encoder module KY-040
Operating voltage: 5V
Circle pulse count: 20
By rotating the rotary encoder can be counted in the positive direction and the reverse direction during rotation of the output pulse frequency, unlike rotary Potentiometer count, this rotation counts are not limited. With the buttons on the rotary encoder can be reset to its initial state, that starts counting from 0.
Getting started with the KY-040 Rotary Encoder Module Brick Sensor
In this Tutorials we are going to deal with KY-040 Rotary Encoder Module Brick Sensor this is simple and easy to connect with arduino.
Rotary Encoders are useful for counting operations, it converts the angle of rotation to the counting digital signal, it can rotate 360º without any limits and gives pulse output. This article will give a basic Arduino Rotary Encoder Interfacing details and operation of conventional rotary encoders.
When the shaft is rotated in clock wise then the output pulse generated at encoder pin A with 90º out of phase from encoder pin B.
By the way when the shaft rotated in counter clock wise then the output generated at the encoder output pins A & B are inverted.
Step1: Hardware required
Step2: Connecting the Hardware
Connect the power supply pins of Rotary Encoder to Arduino board as + to 5V and Gnd to Gnd. Then connect CLK (Encoder out A) Pin to Arduino digital Pin D2 and DT (Encoder out B) pin to digital pin D1.
Step3: Upload the sample sketch
After completing the hookup upload the following Sketch to get the angle and position of rotary encoder in serial monitor.
#define encoderOutA 2 // CLK pin of Rotary Enocoder
#define encoderOutB 1 // DT pin of Rotary Enocoder
int counter = 0;
int presentState;
int previousState;
void setup() {
pinMode (encoderOutA,INPUT);
pinMode (encoderOutB,INPUT);
Serial.begin (9600);
previousState = digitalRead(encoderOutA); // Get current state of the encoderOutA
}
void loop() {
presentState = digitalRead(encoderOutA);
if (presentState != previousState)
{
if (digitalRead(encoderOutB) != presentState)
{
counter ++;
}
else {
counter –;
}
Serial.print(“Position: “);
Serial.println(counter);
}
previousState = presentState; // Replace previous state of the encoderOutA with the current state
}
In Arduino Code first define the output pins and initialize the count as 0, then declare the present & previous state variables. By using “IF” condition loop, get the present state of rotary encoder and compare with previous state. If there is no change then the count remains same, else the count value increases for clock wise rotation and decreases for counter clock wise rotation.
Step4: Testing the circuit
open your serial monitor by clicking on the icon in the right top corner(like search icon).