Rotary encoder on an Arduino Uno
A KY-040 on an Uno counts clicks both ways and sets a lamp. Press the knob to swap to the falling-edge method and watch its bouncing contacts add extra counts. The whole build, an Arduino Uno and 3 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner About 20 minutes to build and run. Runs in your browser. Free, and no account needed.
The parts retail for about $31. On Mokxi they're free.
Step by step, with the wiring and the common mistakes: Arduino Rotary Encoder (KY-040): Wiring and Code
What you'll learn
- How a quadrature encoder signals direction with two contacts
- Reading an encoder with a state table
- Why contact bounce causes extra counts
- Setting an LED's brightness from a count with analogWrite
- Difficulty: Beginner
- Time: About 20 minutes
- Board: Arduino Uno R3
- Parts: 5
How it works
A KY-040 encoder has two switches, CLK on pin 2 and DT on pin 3, that open and close a quarter of a turn apart. The sketch reads the pair as one of four states. The order of the states tells which way the knob turns, and four quarter steps make one click.
The count rises clockwise and falls the other way, and it sets the brightness of a lamp on pin 9. The knob's button on pin 4 switches between two methods of reading: a state table, and a simple falling-edge read. The second can count a single click more than once, because of contact bounce.
Parts list
5 parts, plus the jumper wires. They retail for about $31; on Mokxi they're free.
- 1 × Arduino Uno R3In Starter Kit, Claw Machine Kit, Vending Machine Kit.
- 1 × Half breadboard
- 1 × Rotary encoder, KY-040In MIDI Controller Kit.
- 1 × Resistor, 220 ΩIn Starter Kit, Claw Machine Kit, Halloween Prop Kit.
- 1 × LED, yellowIn Starter Kit, Halloween Prop Kit, Logic Lab Kit.
Kits that can build it
This starter kit has every part in the circuit. Each kit's page lists what else it can build.
Wiring table
Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.
| Part and pin | Connects to |
|---|---|
| Resistor, 220 Ω pin 1 | Arduino Uno R3 pin 9 |
| Rotary encoder, KY-040 pin SW | Arduino Uno R3 pin 4 |
| Rotary encoder, KY-040 pin DT | Arduino Uno R3 pin 3 |
| Rotary encoder, KY-040 pin CLK | Arduino Uno R3 pin 2 |
| Rotary encoder, KY-040 pin VCC | Arduino Uno R3 pin 5V |
| Rotary encoder, KY-040 pin GND | Arduino Uno R3 pin GND |
| LED, yellow pin C | Arduino Uno R3 pin GND |
| LED, yellow pin A | Resistor, 220 Ω pin 2 |
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Rotary encoder: a KY-040 counts clicks, and the count sets a lamp.
//
// pin 2 the encoder's CLK pin 3 its DT pin 4 its SW
// + -> 5 V, GND -> GND
// pin 9 the lamp, through 220 ohm to GND
//
// Turn the knob and the count goes up (clockwise) or down, and the lamp on
// pin 9 gets brighter or dimmer with it. Press the knob to switch between two
// ways of reading the encoder, and watch one of them go wrong.
//
// # Two contacts, a quarter of a click apart
//
// CLK and DT are two switches to ground. As the shaft turns they open and
// close a quarter of a cycle apart, so the pair walks around four states:
//
// clockwise 11 -> 01 -> 00 -> 10 -> 11
// counterclockwise 11 -> 10 -> 00 -> 01 -> 11
//
// (each pair is CLK then DT, and 1 is an open contact). The knob rests at 11,
// and one click is the whole cycle.
//
// # Method 1, the state table: counts clicks
//
// Every time the pair changes, look up the step from the old state to the new
// one in a table of all sixteen. A real quarter step is +1 or -1. A jump of two
// states at once, which is what a bouncing contact looks like, is 0 and does
// nothing. Four quarter steps back at 11 make one click.
//
// # Method 2, the falling edge: counts bounces too
//
// The sketch in most tutorials: when CLK falls, read DT, and count one click
// that way. It is short and it works on a clean encoder. The KY-040's
// contacts bounce, and each bounce on CLK is another falling edge, so a
// single click can count as more than one. Press the knob and turn it to see.
const int CLK = 2;
const int DT = 3;
const int SW = 4;
const int LAMP = 9;
const int8_t STEP[16] = {
0, -1, 1, 0, // from 00
1, 0, 0, -1, // from 01
-1, 0, 0, 1, // from 10
0, 1, -1, 0, // from 11
};
bool tableMethod = true;
uint8_t state = 3;
int8_t quarters = 0;
int lastClk = HIGH;
bool lastSw = HIGH;
long count = 0;
long shown = 0;
uint8_t pair() {
return (uint8_t)((digitalRead(CLK) << 1) | digitalRead(DT));
}
void setup() {
pinMode(CLK, INPUT_PULLUP);
pinMode(DT, INPUT_PULLUP);
pinMode(SW, INPUT_PULLUP);
pinMode(LAMP, OUTPUT);
Serial.begin(115200);
Serial.println("Mokxi Uno: rotary encoder, state table method");
state = pair();
}
void loop() {
if (tableMethod) {
uint8_t now = pair();
if (now != state) {
quarters += STEP[(state << 2) | now];
state = now;
if (now == 3) {
if (quarters >= 4) count++;
if (quarters <= -4) count--;
quarters = 0;
}
}
} else {
int clk = digitalRead(CLK);
if (clk != lastClk && clk == LOW) {
if (digitalRead(DT) != clk) {
count++;
} else {
count--;
}
}
lastClk = clk;
}
bool sw = digitalRead(SW);
if (sw == LOW && lastSw == HIGH) {
tableMethod = !tableMethod;
count = 0;
shown = -1;
state = pair();
quarters = 0;
lastClk = digitalRead(CLK);
Serial.println(tableMethod ? "method: state table" : "method: falling edge");
delay(20);
}
lastSw = sw;
if (count != shown) {
shown = count;
Serial.print("count ");
Serial.println(count);
analogWrite(LAMP, (int)constrain(count, 0, 20) * 12);
}
}
Code walkthrough
The key functions of the sketch, and what each one does.
pair sketch.ino
Reads CLK and DT and combines them into a two-bit number from 0 to 3. The loop compares this state with the last one to find out what the knob did.
uint8_t pair() {
return (uint8_t)((digitalRead(CLK) << 1) | digitalRead(DT));
}setup sketch.ino
Sets the three encoder pins to INPUT_PULLUP, makes the lamp pin an output, starts serial, and reads the starting state with pair, so the first loop does not see a false turn.
void setup() {
pinMode(CLK, INPUT_PULLUP);
pinMode(DT, INPUT_PULLUP);
pinMode(SW, INPUT_PULLUP);
pinMode(LAMP, OUTPUT);
Serial.begin(115200);
Serial.println("Mokxi Uno: rotary encoder, state table method");
state = pair();
}loop sketch.ino
Counts clicks with the chosen method. The table method looks up each move in STEP, so a bounce that jumps two states adds nothing. The edge method reads DT when CLK falls. A press of the button swaps methods and resets the count. A changed count is printed and sets the lamp.
void loop() {
if (tableMethod) {
uint8_t now = pair();
if (now != state) {
quarters += STEP[(state << 2) | now];
state = now;
if (now == 3) {
if (quarters >= 4) count++;
if (quarters <= -4) count--;
quarters = 0;
}
}
} else {
int clk = digitalRead(CLK);
if (clk != lastClk && clk == LOW) {
if (digitalRead(DT) != clk) {
count++;
} else {
count--;
}
}
lastClk = clk;
}
bool sw = digitalRead(SW);
if (sw == LOW && lastSw == HIGH) {
tableMethod = !tableMethod;
count = 0;
// ... 16 more lines in the editorTroubleshooting
The usual mistakes with this circuit, and the fix for each.
- The count goes down when you turn clockwise This project
Check CLK is on pin 2 and DT on pin 3. Swapping them reverses the direction. - One click counts several times This project
That is the falling-edge method. Press the knob to switch back to the state table. - Turning the knob counts twice, skips, or goes the wrong way. The contacts bounce and polling is too slow. Rotary encoder
Use interrupts or a proper encoder library on pins CLK and DT. Use INPUT_PULLUP, since the contacts are open and shut to ground. Swap CLK and DT to flip direction. - The KY-040 pins read wrong or noisy. The board has pull-ups to its + pin, so + must be powered, and its switch needs debounce. Rotary encoder
Connect + to 5 V or 3.3 V to match your board's logic level and GND to ground. Debounce SW for about 20 ms. One click often equals four state changes. - The LED is dim, burns out, or the pin reads wrong because the resistor value is off. Resistor
Read the color bands again. A 220 ohm to 330 ohm resistor suits a typical LED on 5 V. 10k is a common pull-up or pull-down value. Check with a multimeter if unsure. - A pull-up or pull-down resistor is missing, so the input floats and reads random values. Resistor
Tie the input to 5 V or ground through about 10k. Or use INPUT_PULLUP and wire the switch to ground. - The LED does not light, or it lights once and then dies. LED
LEDs have polarity. The longer leg (anode) goes toward the positive side. Always add a series resistor, about 220 ohms to 1 k ohm on a 5 V pin. - A blue or white LED stays dark on 3.3 V. LED
Blue and white LEDs drop about 3 V, so 3.3 V leaves almost nothing for the resistor. Use a 5 V supply, or a smaller resistor and a red or green LED.
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.