Rotary encoder counter
Count clicks of a KY-040 rotary encoder in both directions, and reset with its push button.
Input · Intermediate
In a real product: Car infotainment knob (Automotive): An encoder turns volume and scrolls menus.
A rotary encoder turns forever in either direction, clicking as it goes. Unlike a potentiometer it reports movement, not position, so it suits volume knobs and menus. This project counts the clicks.
What you'll learn
- Quadrature: telling direction from two signals that change one after the other
- Detecting an edge (a falling CLK) by remembering the last reading
- The encoder's push switch
How it works
Each click takes CLK and DT low and back, one slightly after the other. Turning clockwise, CLK falls first, while DT is still high. Turning counter-clockwise, DT has already fallen.
So on each falling edge of CLK, the code reads DT: if it differs from CLK the knob turned clockwise (count up), otherwise counter-clockwise (count down). Pressing the knob connects SW to GND, and resets the count.
The module has its own pull-ups on CLK and DT.
Try this
- Turn the knob with the arrows on the part (or click it to press) while the simulation runs.
- Use interrupts (
attachInterrupton pin 2) so no click is missed while the loop is busy. - Use the count to set an LED's brightness in steps of 10.
sketch.ino
// A KY-040 rotary encoder: CLK on pin 2, DT on pin 3, the push switch (SW) on pin 4.
const int CLK = 2, DT = 3, SW = 4;
int count = 0;
int lastClk;
void setup() {
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
pinMode(SW, INPUT_PULLUP);
Serial.begin(9600);
lastClk = digitalRead(CLK);
Serial.println("Turn the knob; press it to reset");
}
void loop() {
int clk = digitalRead(CLK);
if (clk != lastClk && clk == LOW) { // a falling edge on CLK: one click
if (digitalRead(DT) != clk) count++; // DT still high: clockwise
else count--;
Serial.print("Count: ");
Serial.println(count);
}
lastClk = clk;
if (digitalRead(SW) == LOW && count != 0) {
count = 0;
Serial.println("Reset to 0");
}
}