In this easy CircuitMagic tutorial you will build read rotary encoder direction with arduino and ky-040 using Arduino Uno and one simple sensor. The project needs only a few connections and a short Arduino IDE sketch.
What does the sensor do?
Unlike a potentiometer, an incremental rotary encoder reports relative rotation. Two signals, CLK and DT, shift in sequence as you turn the knob.
Required components
Arduino Uno, KY-040 module, five jumper wires, USB cable.
Connection diagram
The diagram below is a pin-to-pin connection map: each colored line shows one separate wire between labeled terminals, not a photograph of a particular board’s header layout.

Pin connections
Unplug USB power before wiring. The pin table is authoritative; always verify your board’s printed pin labels and your module’s pinout.
| Arduino Uno pin / connection | KY-040 rotary encoder module connection |
|---|---|
| 5V | KY-040 + |
| GND | KY-040 GND |
| D2 | KY-040 CLK |
| D3 | KY-040 DT |
| D4 | KY-040 SW (optional) |
Arduino IDE setup
No additional library needed. Select the matching board and serial port, then upload this sketch.
Complete Arduino code
const int clkPin = 2, dtPin = 3, swPin = 4;
int lastClk, count = 0;
void setup() {
Serial.begin(9600);
pinMode(clkPin, INPUT_PULLUP);
pinMode(dtPin, INPUT_PULLUP);
pinMode(swPin, INPUT_PULLUP);
lastClk = digitalRead(clkPin);
}
void loop() {
int now = digitalRead(clkPin);
if (now != lastClk && now == LOW) {
count += digitalRead(dtPin) == HIGH ? 1 : -1;
Serial.print("Count: ");
Serial.println(count);
}
lastClk = now;
delay(1);
}
Expected output
Rotate the knob clockwise or counterclockwise: the counter increases or decreases. Open Serial Monitor at the baud rate specified by Serial.begin().
Troubleshooting
Mechanical encoders bounce, so occasional skipped or double counts are possible with this short demo. Reverse the count sign if rotation direction is opposite.
If there is no output, double-check the board and port, USB data cable, common ground, sensor pin labels and Serial Monitor speed.
Try next
Once the basic example works, experiment with the sampling delay, add an LED indicator, or log the sensor output to a computer. See more CircuitMagic electronics projects for related beginner tutorials.










