Rotary encoder with Arduino: wiring, code and no missed steps

How a rotary encoder works, how to wire the KY-040 module to an Arduino UNO, and a sketch using interrupts that counts every click in the right direction, even when you turn fast.
  • Level:Intermediate
  • Duration: 30 min
  • Ages 10+
  • Platform: Arduino

Tools for this lesson

Helpful for this build. Open a tool to see tips and more projects that use it.

Rotary encoder with Arduino – EEMENTOR STEM™ guide

Quick answer: a rotary encoder is a knob that turns forever and sends two signals, CLK and DT. When you turn it, both signals switch on and off a quarter of a step apart, and whichever changes first tells the Arduino the direction. To count every click reliably, connect CLK and DT to pins 2 and 3 (the UNO's interrupt pins), let an interrupt read them on every change, and use a small table to ignore contact bounce. The full sketch is below.

What you need

Steps

How the encoder knows which way you turn

Inside the encoder are two switches, A (CLK) and B (DT), and a ring with bumps that opens and closes them as you turn. The bumps are placed so the two switches never change at the same moment: one is always a quarter of a step ahead. Turn clockwise and CLK changes first; turn anticlockwise and DT changes first. This trick is called quadrature. On many encoders, each click you feel passes through all four combinations of the two switches, which is why the sketch divides by 4. On some encoders a click is only half of that; the problems list below shows the fix.

The CLK and DT signals of a rotary encoder as square waves a quarter step apart: turning one way CLK changes first, turning the other way DT changes first.
Quadrature: the order of the changes gives the direction.

Build and test it

  1. Wire the encoder as in the table: CLK to pin 2, DT to pin 3, SW to pin 4, + to 5V, GND to GND.
  2. Upload the sketch and open the Serial Monitor at 9600 baud.
  3. Turn the knob one click at a time. Each click changes the position by exactly 1, and the line says which way you turned.
  4. Turn it fast. The count keeps up, because the interrupt reads the pins on every change instead of waiting for loop().
  5. Press the knob to reset the position to 0. If clockwise counts down on your module, swap the CLK and DT wires (or the two pin numbers in the sketch).

Full code

// Rotary encoder with interrupts: counts every click in the right direction.
const int CLK_PIN = 2;   // interrupt pin
const int DT_PIN = 3;    // interrupt pin
const int SW_PIN = 4;    // push button in the knob

volatile int steps = 0;              // signal changes counted by the interrupt
volatile byte lastState = 0;

// Every possible move from the old state to the new state of CLK and DT:
// +1 = one step one way, -1 = one step the other way, 0 = bounce or impossible jump
const int8_t MOVES[16] = { 0, -1,  1,  0,
                           1,  0,  0, -1,
                          -1,  0,  0,  1,
                           0,  1, -1,  0 };

void readEncoder() {                 // runs on every change of CLK or DT
  byte state = (digitalRead(CLK_PIN) << 1) | digitalRead(DT_PIN);
  steps += MOVES[(lastState << 2) | state];
  lastState = state;
}

int lastPosition = 0;

void setup() {
  Serial.begin(9600);
  pinMode(CLK_PIN, INPUT_PULLUP);
  pinMode(DT_PIN, INPUT_PULLUP);
  pinMode(SW_PIN, INPUT_PULLUP);     // the button pulls SW to GND when pressed
  lastState = (digitalRead(CLK_PIN) << 1) | digitalRead(DT_PIN);
  attachInterrupt(digitalPinToInterrupt(CLK_PIN), readEncoder, CHANGE);
  attachInterrupt(digitalPinToInterrupt(DT_PIN), readEncoder, CHANGE);
  Serial.println("Turn the knob. Press it to reset to 0.");
}

void loop() {
  noInterrupts();                    // copy the shared value safely
  int s = steps;
  interrupts();
  int position = s / 4;              // 4 signal changes per click

  if (position != lastPosition) {
    Serial.print(position > lastPosition ? "Clockwise      " : "Anticlockwise  ");
    Serial.print("position: ");
    Serial.println(position);
    lastPosition = position;
  }

  if (digitalRead(SW_PIN) == LOW) {  // knob pressed
    noInterrupts();
    steps = 0;
    interrupts();
    lastPosition = 0;
    Serial.println("Reset to 0");
    delay(300);                      // wait until the press is over
  }
}
Serial Monitor at 9600 baud: clockwise positions 1, 2 and 3, anticlockwise back to 2, reset to 0 when the knob is pressed, then position minus 1.
What the sketch prints as you turn and press the knob.

Wiring

Breadboard wiring diagram: KY-040 rotary encoder with CLK to UNO pin 2, DT to pin 3, SW to pin 4, plus to 5V and GND to GND.
Breadboard view. Check each connection against the wiring table below.
From To
Encoder CLK (A) UNO pin 2
Encoder DT (B) UNO pin 3
Encoder SW (button) UNO pin 4
Encoder + UNO 5V
Encoder GND UNO GND

On the UNO, only pins 2 and 3 can run interrupts, so keep CLK and DT on those two. Sensor modules from different makers can label and order their pins differently; always follow the labels printed on your module.

Why simple encoder code misses steps: contact bounce makes extra changes, a busy loop checks too late, and the moves table counts only real steps.
The two problems the sketch solves.
FREE

Build this circuit in EEMENTOR Lab

Wire it yourself in your browser before you touch a real wire. No sign-up, nothing to install.

The parts for this circuit laid out in EEMENTOR Lab, ready to wireBuild it yourself
  1. Wire the parts using the wiring table above. Pins with no wire show red.
  2. Press Run, press Turn left or Turn right under Selected, and watch the Serial monitor.
  3. Then try this lesson’s sketch: paste it into the Code tab and press Compile & Run.

EEMENTOR Lab is free and in beta. Results are a guide; a real build can differ slightly. About the Lab

Common problems

  • The count goes the wrong way: swap CLK and DT, either the wires or the pin numbers in the sketch.
  • Only every second click counts: on your encoder a click is half a cycle (2 signal changes, not 4). Change the 4 in s / 4 to 2.
  • Nothing changes when you turn: check CLK and DT really go to pins 2 and 3, and that + and GND are connected.
  • The button resets all the time: SW must go to pin 4 with INPUT_PULLUP; check it isn't touching GND.
  • It counted fine in a simple sketch but misses steps in your project: long delay() calls hide turns from code that only checks in loop(). With interrupts, the count stays right; your project just reads steps when it's ready.

FAQ

What's the difference between a rotary encoder and a potentiometer?

A potentiometer stops at both ends and tells you its position. An encoder turns forever and tells you each click and its direction, which is why volume knobs on modern radios and car stereos use encoders.

Why do I need interrupts for a rotary encoder?

You don't always, but they help. If loop() is busy (with an LCD, a delay or a sensor), it can miss a quick turn. An interrupt runs the moment a pin changes, so no click gets lost.

What is contact bounce?

Inside the encoder, metal contacts touch and separate. For a tiny moment they chatter, switching on and off several times. The table in the sketch only accepts moves that are possible, so most chatter adds nothing.

How many clicks does a rotary encoder have per turn?

It depends on the model. Many hobby encoders have about 20 clicks per full turn, and some have 30. Check yours: turn it once and count.

Can I use a rotary encoder with an ESP32?

Yes. On the ESP32 almost every pin can run an interrupt, so pick two free GPIOs for CLK and DT. It’s good practice to put IRAM_ATTR before the interrupt function on the ESP32.

Related lessons