Back to Sensors & Actuators Series

Position Sensor: Rotary Encoder

July 21, 2025 Wasil Zafar 7 min read

Rotary encoder deep dive — quadrature principle, interrupt-driven decoding, debouncing, complete code, and real-world applications.

Contents

  1. Working Principle
  2. Electrical Characteristics
  3. Interfacing with MCU
  4. Calibration
  5. Code Example
  6. Real-World Applications
  7. Absolute Encoders (AS5600)
  8. Optical Encoders
  9. Encoder Comparison
  10. Limitations

Working Principle

An incremental rotary encoder generates two square-wave signals (Channel A and Channel B) that are 90° out of phase — called quadrature encoding. By detecting which channel leads, the MCU determines rotation direction. Counting pulses gives angular displacement.

Analogy: Imagine two turnstiles side by side, offset so one always clicks a half-step before the other. Which one clicks first tells you which direction someone is walking.

Electrical Characteristics

ParameterValue (KY-040 module)
Supply Voltage3.3 V – 5 V
Pulses per Revolution20 (detents)
Output2 digital channels (A, B) + push button
Bounce Time~5 ms (requires debouncing)

Code Example

/*
 * Rotary Encoder with Interrupt — Arduino
 * Wiring: CLK → Pin 2 (INT0), DT → Pin 3, SW → Pin 4
 */
#define CLK_PIN 2   /* Must be interrupt-capable pin */
#define DT_PIN  3
#define SW_PIN  4

volatile int position = 0;

void encoderISR() {
    /* Read DT at the moment CLK fires */
    if (digitalRead(DT_PIN) == HIGH) {
        position++;   /* Clockwise */
    } else {
        position--;   /* Counter-clockwise */
    }
}

void setup() {
    Serial.begin(9600);
    pinMode(CLK_PIN, INPUT_PULLUP);
    pinMode(DT_PIN, INPUT_PULLUP);
    pinMode(SW_PIN, INPUT_PULLUP);

    attachInterrupt(digitalPinToInterrupt(CLK_PIN), encoderISR, FALLING);
    Serial.println("Rotate encoder. Press button to reset.");
}

void loop() {
    static int lastPos = 0;

    if (position != lastPos) {
        Serial.print("Position: ");
        Serial.println(position);
        lastPos = position;
    }

    if (digitalRead(SW_PIN) == LOW) {
        position = 0;
        Serial.println("Reset to 0");
        delay(300);  /* Simple debounce */
    }
}

Real-World Applications

Industrial

CNC Machine Axis Positioning

High-resolution optical encoders (1000+ PPR) on CNC stepper motors provide closed-loop position feedback, detecting missed steps and achieving micron-level precision on milling machines.

CNCManufacturingPrecision

Absolute Encoders: No Homing Required

Absolute encoders retain their position even after power loss — no homing sequence needed at startup. The AS5600 is a 12-bit (4096 positions/revolution) magnetic absolute encoder that reads a diametrically magnetised magnet via a Hall-effect sensor array. It outputs position over I²C, analog voltage, or PWM. Other options include Gray-code optical absolute encoders and SSI (Synchronous Serial Interface) industrial types.

Optical Encoders: High Resolution

Optical encoders use a slotted disc and photointerrupter pairs to achieve resolutions of 100 to 10,000+ PPR — orders of magnitude higher than the KY-040’s 20 PPR. They have no contact bounce (non-mechanical) and extremely long lifespans. Industrial optical encoders (CUI AMT103, Omron E6B2) are standard in CNC machines, robotics, and servo motor feedback loops.

Encoder Technology Comparison

FeatureKY-040 (Mechanical)Optical IncrementalAS5600 (Magnetic Absolute)
Resolution20 PPR100–10,000 PPR4096 positions (12-bit)
Position TypeIncremental (relative)Incremental (relative)Absolute (survives power-off)
OutputQuadrature A/B + switchQuadrature A/B + Z indexI²C, Analog, PWM
Contact BounceYes (needs debounce)No (optical, non-contact)No (magnetic, non-contact)
Max RPM~1206,000+~4,500
Cost~$1$10–50~$3–5
Best ForUI knobs, menusCNC, servo, roboticsGimbal, robot joint, valve position

Limitations

  • No absolute position (incremental): The KY-040 and optical incremental encoders reset to 0 at power-up; use an AS5600 or other absolute encoder if power-off position retention is needed.
  • Contact bounce (mechanical): KY-040 needs hardware (RC filter) or software debouncing; optical and magnetic types are bounce-free.
  • Low resolution (KY-040): 20 PPR is fine for UI controls but insufficient for precision positioning; choose optical or magnetic for >100 PPR.
  • AS5600 magnetic interference: External magnets or ferrous materials near the encoder chip can corrupt readings.