The KY-040 Rotary Encoder is an electro-mechanical device manufactured by GIAK, designed to convert the angular position or rotation of a shaft into digital signals. Rotary encoders are widely used in various applications such as volume controls, scrolling through menus, and as input devices in user interfaces. The KY-040 is particularly popular among hobbyists and is often used with microcontroller platforms like Arduino due to its simplicity and ease of use.
Pin Number | Description |
---|---|
1 | Ground (GND) |
2 | +5V (VCC) |
3 | Signal A (CLK) |
4 | Signal B (DT) |
5 | Push Button (SW) |
To use the KY-040 Rotary Encoder with an Arduino UNO, connect the pins as follows:
// Define the connections to the Arduino
const int pinCLK = 2; // Connected to CLK on KY-040
const int pinDT = 3; // Connected to DT on KY-040
const int pinSW = 4; // Connected to SW on KY-040
// Variables to hold the current and last encoder position
volatile int encoderPos = 0;
int lastEncoderPos = 0;
boolean buttonPressed = false;
// Interrupt service routine for encoder CLK pin
void isr() {
if (digitalRead(pinDT) != digitalRead(pinCLK)) {
encoderPos++; // Clockwise
} else {
encoderPos--; // Counterclockwise
}
}
// Setup function
void setup() {
pinMode(pinCLK, INPUT_PULLUP);
pinMode(pinDT, INPUT_PULLUP);
pinMode(pinSW, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pinCLK), isr, CHANGE);
Serial.begin(9600);
}
// Main loop
void loop() {
if (encoderPos != lastEncoderPos) {
Serial.println(encoderPos);
lastEncoderPos = encoderPos;
}
if (digitalRead(pinSW) == LOW && !buttonPressed) {
Serial.println("Button Pressed");
buttonPressed = true;
} else if (digitalRead(pinSW) == HIGH && buttonPressed) {
buttonPressed = false;
}
}
Serial.println()
statements to debug and monitor the encoder's output in real-time.Q: Can I use the KY-040 Rotary Encoder with a 3.3V system? A: Yes, but the output signal levels will be lower, which may require level shifting for some 5V systems.
Q: How can I increase the resolution of the encoder? A: The KY-040 has a fixed resolution of 20 pulses per revolution. To increase the effective resolution, you can use gear ratios or employ software algorithms to interpolate between pulses.
Q: Is it possible to use the encoder without an interrupt? A: Yes, but using interrupts is recommended to ensure all pulses are captured, especially at higher rotation speeds.