All articles

    The KY-040 Rotary Encoder: A Knob That Turns Forever

    The rotary encoder explained: how it differs from a potentiometer, the A and B signals and finding the direction from the sequence of states, wiring and the button, reading it by polling, with interrupts, with a state table or with a library, short and long presses, an on-screen menu, acceleration, bounce and missed steps, and motor encoders.

    Updated 6 min read

    The volume knob in modern cars, or the menu knob on a 3D printer: it turns endlessly, and each small turn is a click. That's a rotary encoder. It isn't a potentiometer measuring a position; it tells you how many steps it turned and in which direction.

    The A and B signals are offset from each other, and whichever changes first sets the direction
    The A and B signals are offset from each other, and whichever changes first sets the direction

    Encoder or potentiometer?

    EncoderPotentiometer
    TurnsEndlesslyAbout 270° and stops
    Gives youSteps and directionA position (a voltage)
    After a power cutDoesn't remember its positionIts position is the value
    ReadingTwo digital pinsOne analog pin
    Suited toMenus, and numbers without limitsVolume, brightness, a fixed threshold

    How does it work?

    Inside are two contacts that close and open as you turn, producing two signals, A and B, shifted from each other by a quarter cycle (quadrature):

    • A changed first → clockwise.
    • B changed first → anticlockwise.

    The KY-040 module usually has 20 clicks per turn, plus a button when you press the shaft.

    The sequence of states

    If you write A and B side by side as two digits, turning one way they go like this: 11 → 01 → 00 → 10 → 11, and the other way in reverse. At each step only one digit changes. So if you know the old state and the new one, you know the direction. And if both changed together, that's bounce or a lost step, so you ignore it. That's the idea behind the best reading methods below.

    On most KY-040 modules, one click = a full cycle of the four states, which explains why the counter can rise by 4 per click if you count every change.

    Wiring

    KY-040Arduino
    CLK (A)2
    DT (B)3
    SW4
    +5V
    GNDGND

    The module has pull-ups on CLK and DT (the + pin must be connected for them to work), and the button may need INPUT_PULLUP. With an ESP32, power it from 3.3 V so the signals don't reach 5 V.

    The simplest code

    const int CLK = 2, DT = 3;
    int last;
    long pos = 0;
    
    void setup() {
      pinMode(CLK, INPUT);
      pinMode(DT, INPUT);
      last = digitalRead(CLK);
      Serial.begin(9600);
    }
    
    void loop() {
      int now = digitalRead(CLK);
      if (now != last && now == LOW) {
        if (digitalRead(DT) != now) pos++;
        else pos--;
        Serial.println(pos);
      }
      last = now;
    }

    It works well as long as the loop is fast. If it contains a delay or heavy work, you'll miss steps.

    Better: interrupts or a library

    • Put A and B on the interrupt pins (2 and 3 on the Uno). See interrupts, which includes a full encoder example.
    • Or use a ready-made library such as Encoder or RotaryEncoder, which handle direction and bounce properly.

    The state table (the most accurate method)

    Instead of looking at a single edge, keep the old and new state (4 bits), and a table tells you +1, −1 or zero:

    const int8_t STEP[16] = {0,-1,1,0, 1,0,0,-1, -1,0,0,1, 0,1,-1,0};
    volatile uint8_t st = 0;
    volatile long ticks = 0;
    
    void readEnc() {
      st = ((st << 2) | (digitalRead(CLK) << 1) | digitalRead(DT)) & 0x0F;
      ticks += STEP[st];
    }
    
    void setup() {
      pinMode(CLK, INPUT_PULLUP); pinMode(DT, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(CLK), readEnc, CHANGE);
      attachInterrupt(digitalPinToInterrupt(DT), readEnc, CHANGE);
    }
    // clicks = ticks / 4

    The impossible states (both digits changing together) are zero in the table, so bounce cancels itself out almost entirely. If the direction comes out reversed, swap CLK and DT.

    The button: short and long presses

    unsigned long tDown = 0;
    bool wasDown = false;
    
    void loop() {
      bool down = digitalRead(SW) == LOW;
      if (down && !wasDown) tDown = millis();
      if (!down && wasDown) {
        if (millis() - tDown > 800) { /* long press: back */ }
        else if (millis() - tDown > 30) { /* short press: select */ }
      }
      wasDown = down;
    }

    The 30 ms ignores the button's bounce, as in the debouncing article.

    An on-screen menu

    Turning selects, pressing confirms:

    const char* items[] = {"Temp", "Fan", "Light", "Back"};
    const int N = 4;
    int sel = ((pos % N) + N) % N;     // correct even if pos is negative
    lcd.setCursor(0, 0); lcd.print(">"); lcd.print(items[sel]); lcd.print("     ");

    The + N) % N matters: in C the remainder of a negative number is negative, so without it the menu breaks if you turn left from the start. The display itself is covered in the displays article.

    Acceleration

    If you're setting a number from 0 to 1000, 1000 clicks is a lot. Measure the time between clicks: if it's under 50 ms (fast turning), add 10 instead of 1. That's what many devices do.

    Bounce and wrong steps

    The contacts are mechanical, so they bounce like buttons:

    • A 10–100 nF capacitor from each line to ground helps.
    • The most accurate method is to track the state of both signals together (a state machine) instead of a single edge, which is what good libraries do.
    • If your number rises by 2 or 4 per click, divide by the number of changes per click.

    Recurring problems

    ProblemUsual cause
    It doesn't count at allThe + pin isn't connected, so the pull-ups don't work
    It counts both ways while turning one wayBounce; use the state table or capacitors
    It rises by 2 or 4 per clickYou're counting every change; divide
    It misses steps when turned fastA delay in the loop; use interrupts
    The direction is reversedSwap CLK and DT

    Uses

    • Menus on a display: turn to choose, press to confirm.
    • Setting a number (temperature, time, speed) without limits. Save the value in the EEPROM, because the encoder itself doesn't remember.
    • Measuring a wheel's rotation (there are dedicated encoders for this with higher resolution).

    Motor encoders

    Many DC motors come with an encoder on the shaft: optical (a slotted disc) or magnetic with Hall sensors. Exactly the same A and B signals, but without clicks, and with more pulses (for example 11, 360 or more per turn). That's what lets you control the speed and position of a DC motor precisely.

    FAQ

    Why does it go back to zero after a power cut? The encoder says "how far I moved", not "where I am". If you need an absolute position at start-up, there are absolute encoders, or save the last value.

    Does it work on any pins? With polling, yes. With interrupts, only 2 and 3 on the Uno, and almost any pin on the ESP32.

    Circuits Nerd
    © 2026 Circuits Nerd. All rights reserved.