Description:
A rotary encoder is a sort of position sensor that translates the angular position (rotation) of a handle into a voltage that may be used to identify which way the knob is moved. Rotary encoders can rotate a full 360 degrees without stopping, They are utilized when you need to know the change in position rather than the exact location. it comes with an operating voltage of 5V and a steps width of 20 positions/revolution. Rotary encoders are found in a wide range of everyday gadgets. Rotary encoders are more common than we realize, appearing in everything from printers and photography lenses to CNC machines and robots. The volume control knob on a vehicle radio is the most common application of a rotary encoder in everyday life.Â
Package Includes:
- 1 x Rotary Encoder Module for Arduino
Features:
- steps width of 20 positions/revolution
-
It has a switch included in the Encoder
-
Rotates a full 360 degrees
-
Operating voltage range of 5V
PROJECT – ARDUINO ROTATION INDICATOR:
After learning about the KY-040 module and the Incremental Rotary Encoder, it is now time to build a project using the module. Our project will get digital signals from the KY-040 module, and display it on the serial monitor.
Â
PROJECT COMPONENTS:
For this project, we need the following components:
- Arduino Uno board (1 pc.)
- KY-040 Rotary Encoder Module (1 pc.)
- Jumper wires
Â
WIRING DIAGRAM:
Figure 2 shows the connection between the Arduino Uno and the KY-040 Rotary Encoder Module.
The KY-040 module pins are connected to the Arduino Uno board as follows:
COMPONENT PIN | UNO BOARD PIN |
---|---|
G | GND |
(+) | +5V |
SW | 10 |
DT | 9 |
CLK | 8 |
Â
CODE:
Below is the Arduino sketch for our project. I have added comments to explain important parts of the code. Save the code as KY-040.ino and upload it to your Arduino board.
// Arduino and KY-040 module
int encoderPinA = 8; // CLK pin
int encoderPinB = 9; // DT pin
int encoderBtn = 10; // SW pin
int count = 0;
int encoderPinA_prev;
int encoderPinA_value;
boolean bool_CW;
void setup() {
Serial.begin (9600);
pinMode (encoderPinA, INPUT);
pinMode (encoderPinB, INPUT);
pinMode(encoderBtn, INPUT_PULLUP);
encoderPinA_prev = digitalRead(encoderPinA);
}
void loop() {
encoderPinA_value = digitalRead(encoderPinA);
if (encoderPinA_value != encoderPinA_prev) { // check if knob is rotating
// if pin A state changed before pin B, rotation is clockwise
if (digitalRead(encoderPinB) != encoderPinA_value) {
count ++;
bool_CW = true;
} else {
// if pin B state changed before pin A, rotation is counter-clockwise
bool_CW = false;
count--;
}
if (bool_CW) {
Serial.print("Clockwise | ");
} else {
Serial.print("Counter-Clockwise | ");
}
Serial.print(count);
Serial.print(" | ");
}
encoderPinA_prev = encoderPinA_value;
// check if button is pressed (pin SW)
if (digitalRead(encoderBtn) == LOW) Serial.println("Button Pressed");
else Serial.println("Button Released");
}