Read a Rotary Encoder (KY-040 + Arduino)
Count clicks and direction from an endless-turn rotary encoder, and reset with its button.
Beginner20 min
What you need
Wiring
Hover a pin or a wire to trace the connection.
Code
rotary_encoder.ino
// Count direction from a KY-040 rotary encoder; button resets to 0.
const int CLK = 2, DT = 3, SW = 4;
int lastClk;
long counter = 0;
void setup() {
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
pinMode(SW, INPUT_PULLUP);
lastClk = digitalRead(CLK);
Serial.begin(9600);
}
void loop() {
int clk = digitalRead(CLK);
if (clk != lastClk && clk == LOW) { // one detent
counter += (digitalRead(DT) != clk) ? 1 : -1; // CW vs CCW
Serial.println(counter);
}
lastClk = clk;
if (digitalRead(SW) == LOW) { // press to reset
counter = 0;
Serial.println("reset");
delay(200);
}
}
Steps
- Wire: + to 5V, GND to GND, CLK to D2, DT to D3, SW to D4.
- Upload and open the Serial Monitor.
- Turn the knob — the count goes up one way, down the other. Press to reset.