Built-in project · Arduino Uno R3

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 Runs in your browser. Free, and no account needed.

Step by step, with the wiring and the common mistakes: Arduino Rotary Encoder (KY-040): Wiring and Code

Rotary encoder · Arduino Uno R3live0.000 s 0.00x
Hold the button
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · Arduino Uno R3
// 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);
  }
}

Parts list

5 parts, plus the jumper wires. Every one is in the editor's parts bin.

How it is wired

7 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.

  • Arduino Uno R3 pin 9; Resistor, 220 Ω pin 1
  • Arduino Uno R3 pin 4; Rotary encoder, KY-040 pin SW
  • Arduino Uno R3 pin 3; Rotary encoder, KY-040 pin DT
  • Arduino Uno R3 pin 2; Rotary encoder, KY-040 pin CLK
  • Arduino Uno R3 pin 5V; Rotary encoder, KY-040 pin VCC
  • Ground: Arduino Uno R3 pin GND; Rotary encoder, KY-040 pin GND; LED, yellow pin C
  • Resistor, 220 Ω pin 2; LED, yellow pin A

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.