MyRoboPathOpen Robotics Lab
Arduino Uno #16 of 35
Est. 0.75 Hours
Budget: $2 - $4
Beginner

KY-040 Quadrature Rotary Encoder & Push Dial

Decode 90°-shifted quadrature CLK/DT pulses with hardware interrupts for endless rotational menus and dials.

Unlike a potentiometer limited to 270°, a rotary encoder spins endlessly in either direction with crisp tactile detents and an integrated push switch. Wire the KY-040 module to Arduino Uno interrupt pins, decode clockwise vs. counter-clockwise phase order, and drive a live position counter.

Arduino Uno R3KY-040 EncoderQuadrature DecodingHardware InterruptsMenu Interface
KY-040 Quadrature Rotary Encoder & Push Dial Blueprint
KY-040 Quadrature Rotary Encoder & Push DialCAD Blueprint

Key Learning Objectives & Robotics Concepts

By building and programming this project, you will master the following core engineering skills:

1Understand 90° out-of-phase quadrature signals (CLK leads DT clockwise; DT leads CLK counter-clockwise).
2Use attachInterrupt() on D2 with volatile variables for zero-missed-click responsiveness.
3Apply microsecond ISR debounce filtering to reject mechanical contact chatter.
4Map encoder counts cleanly to real-world actuators such as PWM LED dimming or OLED menus.

Power Architecture & Voltage Staging

5V / 3.3V Regulated Power

The KY-040 draws less than 2mA from the Arduino Uno 5V pin via its onboard 10kΩ pull-up resistors. All signal lines operate cleanly at 5V TTL. Onboard 10kΩ pull-ups stabilize CLK and DT; hardware interrupt on D2 prevents missed detents during fast spins.

KY-040 Quadrature Rotary Encoder & Push Dial Power Architecture Schematic
Figure: Regulated Arduino Uno supply rails, current budget, and component protection.Power Schematic

Bill of Materials (BOM) & Hardware Components

Bill of Materials for KY-040 Quadrature Rotary Encoder & Push Dial
ComponentSpecifications & AlternativeQtyApprox Cost
Arduino Uno R3ATmega328P with INT0 (D2) & INT1 (D3)1$8.00
KY-040 Rotary Encoder Module20 detents/rev + integrated shaft push switch1$1.80
5mm LED + 220Ω ResistorVisual PWM dial feedback1$0.15
Breadboard & Jumper Wires7× breadboard jumpers1$2.00

Electrical & System Architecture

Connect KY-040 + (VCC) to 5V, GND to GND, CLK to D2 (INT0), DT to D3 (INT1), and SW (pushbutton) to D4. Optional brightness LED (+220Ω) connects to PWM pin D9.

Figure: Complete Arduino Uno R3 pin-to-pin wiring schematic for KY-040 Quadrature Rotary Encoder & Push Dial.
Figure: Complete Arduino Uno R3 pin-to-pin wiring schematic for KY-040 Quadrature Rotary Encoder & Push Dial.Wiring Schematic

Autonomous Behavior & Finite State Machine (FSM)

Deterministic Arduino loop handling KY-040 20-Detent Rotary Encoder Module acquisition, filtering, and real-time output updates.

Figure: Firmware execution flow and state transitions for KY-040 Quadrature Rotary Encoder & Push Dial.
Figure: Firmware execution flow and state transitions for KY-040 Quadrature Rotary Encoder & Push Dial.Control Algorithm

Step-by-Step Physical Assembly & Wiring Tutorial

Follow each of the 5 sequential milestone stages with technical photos, wiring checks, and pre-flight tests.

1

Inspect KY-040 5-Pin Header

Duration: 5 Mins

Identify CLK, DT, SW, +, and GND on the small blue/black KY-040 PCB.

KY-040 Quadrature Rotary Encoder & Push Dial hardware layout diagram
Stage 1: KY-040 20-Detent Rotary Encoder Module hardware inspection & pinout overview.Stage 1 Diagram
Step Action Checklist:
  • Press the plastic knob onto the D-shaped metal shaft.
  • Feel the 20 tactile detents per full rotation and click the shaft inward to test SW.
  • Confirm header labels: CLK, DT, SW, +, GND.
Engineering & Tuning Tip: Some KY-040 boards omit the pull-up resistor on SW—always enable INPUT_PULLUP on D4 in firmware!
2

Wire Encoder to Interrupt Pins D2/D3

Duration: 5 Mins

Connect CLK to D2, DT to D3, SW to D4, and a demo PWM LED to D9.

KY-040 Quadrature Rotary Encoder & Push Dial breadboard wiring check diagram
Stage 2: Breadboard layout & Arduino Uno pin-to-pin wiring audit.Stage 2 Diagram
Step Action Checklist:
  • Connect KY-040 + → 5V and GND → GND.
  • Connect CLK → D2, DT → D3, and SW → D4.
  • Wire D9 → 220Ω resistor → LED anode → cathode to GND.
Engineering & Tuning Tip: Wiring CLK to D2 lets us attach hardware interrupt INT0 so fast twists never drop clicks.
3

Verify Raw Quadrature Transitions

Duration: 5 Mins

Run the quick pin diagnostic to see CLK and DT toggle out of phase as you twist slowly.

KY-040 Quadrature Rotary Encoder & Push Dial power rail protection diagram
Stage 3: Supply rail check (USB 5.0V Regulated Rail (<2mA)) and circuit protection verification.Stage 3 Diagram
Step Action Checklist:
  • Upload the diagnostic snippet and open Serial Monitor.
  • Rotate the knob slowly one click CW and watch CLK/DT change sequentially.
  • Press the shaft inward and verify SW drops to 0.
Engineering & Tuning Tip: Notice how CLK and DT never change at the exact same instant—that phase lag encodes rotation direction!
4

Upload Interrupt-Driven Dial Dimmer Firmware

Duration: 10 Mins

Flash the debounced quadrature decoder and watch the LED dim smoothly as you turn the knob.

KY-040 Quadrature Rotary Encoder & Push Dial serial telemetry verification diagram
Stage 4: Firmware upload & 115200 baud Serial Monitor verification.Stage 4 Diagram
Step Action Checklist:
  • Upload the production sketch below.
  • Rotate clockwise to climb 0% → 100% brightness; rotate counter-clockwise to dim.
  • Press the encoder knob (SW) to reset dial cleanly back to 50%.
Engineering & Tuning Tip: If clockwise decrements instead of incrementing, simply swap the CLK and DT wires!
5

Test Fast-Spin Accuracy

Duration: 5 Mins

Spin the knob briskly CW and CCW to verify crisp direction tracking without jitter.

KY-040 Quadrature Rotary Encoder & Push Dial live operational logic diagram
Stage 5: Live operational logic flow & calibration verification.Stage 5 Diagram
Step Action Checklist:
  • Spin one full revolution CW and verify Serial count increases by ~20 steps.
  • Spin back CCW and confirm smooth return toward 0.
  • Confirm zero phantom counts while the knob sits untouched.
Engineering & Tuning Tip: Adding two 0.1µF ceramic capacitors from CLK→GND and DT→GND provides ultra-clean hardware debouncing for industrial dials.

Subsystem Benchtop Verification Scripts

Test each hardware subsystem independently before deploying the full autonomous firmware.

1Bench Diagnostic: KY-040 20-Detent Rotary Encoder Module Hardware Check

Subsystem Diagnostic

Minimal standalone sketch to verify pin wiring and signal response for KY-040 20-Detent Rotary Encoder Module before running the full project firmware.

Arduino IDE Diagnostic ScriptC++ / Arduino
// Diagnostic: Live KY-040 Pin State Monitor
void setup() { pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); pinMode(4, INPUT_PULLUP); Serial.begin(115200); }
void loop() {
  Serial.print("CLK:"); Serial.print(digitalRead(2));
  Serial.print(" DT:"); Serial.print(digitalRead(3));
  Serial.print(" SW:"); Serial.println(digitalRead(4));
  delay(120);
}
Expected Output: Shows live 0/1 states for CLK, DT, and SW as you turn and click the knob.

Complete Production Firmware

Full working C++ source code with pin mappings, non-blocking timers, and FSM avoidance routines.

arduino_uno_ky040_rotary_encoder.ino
arduino_uno_ky040_rotary_encoder.inoArduino C++
/**
 * Project 16: KY-040 Interrupt-Driven Rotary Encoder & PWM Dimmer
 * Board: Arduino Uno R3 | Pins: CLK=D2(INT0), DT=D3, SW=D4, LED=D9
 */
const uint8_t PIN_CLK = 2;
const uint8_t PIN_DT  = 3;
const uint8_t PIN_SW  = 4;
const uint8_t PIN_LED = 9;

volatile int encoderPos = 10; // Range 0..20 (5% steps)
volatile unsigned long lastIsrUs = 0;

void onClockFall() {
  unsigned long nowUs = micros();
  if (nowUs - lastIsrUs < 4000UL) return; // 4ms contact bounce reject
  lastIsrUs = nowUs;

  if (digitalRead(PIN_DT) == HIGH) {
    if (encoderPos < 20) encoderPos++;
  } else {
    if (encoderPos > 0) encoderPos--;
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(PIN_CLK, INPUT_PULLUP);
  pinMode(PIN_DT,  INPUT_PULLUP);
  pinMode(PIN_SW,  INPUT_PULLUP);
  pinMode(PIN_LED, OUTPUT);

  attachInterrupt(digitalPinToInterrupt(PIN_CLK), onClockFall, FALLING);
  Serial.println(F("KY-040 Rotary Encoder Ready (Turn to dim, Click to reset)"));
}

void loop() {
  static int lastReported = -1;
  noInterrupts();
  int pos = encoderPos;
  interrupts();

  if (digitalRead(PIN_SW) == LOW) {
    noInterrupts(); encoderPos = 10; interrupts();
    pos = 10;
    Serial.println(F("[SW CLICK] Dial Reset to 50%"));
    delay(250);
  }

  if (pos != lastReported) {
    lastReported = pos;
    int pwm = map(pos, 0, 20, 0, 255);
    analogWrite(PIN_LED, pwm);
    Serial.print(F("Dial Step: ")); Serial.print(pos);
    Serial.print(F("/20 | PWM: ")); Serial.println(pwm);
  }
}

Firmware Architecture Explanation:

  • Uses hardware interrupt INT0 (FALLING edge on D2) so rapid twists are never missed by Serial printing.
  • Protects shared volatile encoderPos with brief noInterrupts()/interrupts() atomic reads.
  • Applies a 4ms micros() guard inside the ISR to filter mechanical detent bounce cleanly.

Operational Verification & Pin State Matrix

1Double-check all 5 Arduino Uno pin connections against the wiring schematic before plugging in USB.
2Upload the Bench Diagnostic sketch first and confirm Serial Monitor at 115200 baud matches: Shows live 0/1 states for CLK, DT, and SW as you turn and click the knob.
3Upload the complete production sketch and verify every condition in the operational truth table below.

Input Signal vs. System Output Truth Table:

Operational truth table for KY-040 Quadrature Rotary Encoder & Push Dial
Input / StatePin / SignalDetected ConditionExpected Output
CLK Fall + DT=HIGHD2 ISR TriggerClockwise DetentIncrement Dial (+5% PWM)
CLK Fall + DT=LOWD2 ISR TriggerCounter-ClockwiseDecrement Dial (-5% PWM)
SW PressedD4 = LOWCenter ClickReset Dial to 50%

Engineering Troubleshooting Matrix

Engineering troubleshooting matrix for KY-040 Quadrature Rotary Encoder & Push Dial
ProblemLikely CauseDiagnostic CheckEngineering Solution
Turning clockwise lowers the number instead of raising itCLK and DT phase polarity reversedTurn CW and watch count directionSwap CLK and DT wires (or invert DT == LOW in ISR).
Single click jumps by 2 or 3 countsMechanical switch bounce exceeding 4msTwist slowly one click at a timeIncrease ISR guard from 4000UL to 8000UL microseconds.
Center button never resetsMissing INPUT_PULLUP on SW pinCheck D4 voltage with DMMEnsure pinMode(PIN_SW, INPUT_PULLUP) is active.

Engineering Challenges & Upgrades

Take your build to the next level with these progressive engineering upgrades:

Level 1LightWave 5-LED Bar Controller

Move a glowing LED left and right across 5 digital pins as you twist the encoder.

Level 2OLED Scrollable Settings Menu

Use the rotary knob to highlight items on Project 4 OLED and click SW to select.

Level 3Precision Stepper Jog Wheel

Drive Project 15 (28BYJ-48) directly like a CNC manual handwheel.