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.
Key Learning Objectives & Robotics Concepts
By building and programming this project, you will master the following core engineering skills:
Power Architecture & Voltage Staging
5V / 3.3V Regulated PowerThe 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.
Bill of Materials (BOM) & Hardware Components
| Component | Specifications & Alternative | Qty | Approx Cost |
|---|---|---|---|
| Arduino Uno R3 | ATmega328P with INT0 (D2) & INT1 (D3) | 1 | $8.00 |
| KY-040 Rotary Encoder Module | 20 detents/rev + integrated shaft push switch | 1 | $1.80 |
| 5mm LED + 220Ω Resistor | Visual PWM dial feedback | 1 | $0.15 |
| Breadboard & Jumper Wires | 7× breadboard jumpers | 1 | $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.
Autonomous Behavior & Finite State Machine (FSM)
Deterministic Arduino loop handling KY-040 20-Detent Rotary Encoder Module acquisition, filtering, and real-time output updates.
Step-by-Step Physical Assembly & Wiring Tutorial
Follow each of the 5 sequential milestone stages with technical photos, wiring checks, and pre-flight tests.
Inspect KY-040 5-Pin Header
Identify CLK, DT, SW, +, and GND on the small blue/black KY-040 PCB.
- 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.
Wire Encoder to Interrupt Pins D2/D3
Connect CLK to D2, DT to D3, SW to D4, and a demo PWM LED to D9.
- Connect KY-040 + → 5V and GND → GND.
- Connect CLK → D2, DT → D3, and SW → D4.
- Wire D9 → 220Ω resistor → LED anode → cathode to GND.
Verify Raw Quadrature Transitions
Run the quick pin diagnostic to see CLK and DT toggle out of phase as you twist slowly.
- 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.
Upload Interrupt-Driven Dial Dimmer Firmware
Flash the debounced quadrature decoder and watch the LED dim smoothly as you turn the knob.
- 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%.
Test Fast-Spin Accuracy
Spin the knob briskly CW and CCW to verify crisp direction tracking without jitter.
- 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.
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 DiagnosticMinimal standalone sketch to verify pin wiring and signal response for KY-040 20-Detent Rotary Encoder Module before running the full project firmware.
// 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);
}Complete Production Firmware
Full working C++ source code with pin mappings, non-blocking timers, and FSM avoidance routines.
/**
* 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
Input Signal vs. System Output Truth Table:
| Input / State | Pin / Signal | Detected Condition | Expected Output |
|---|---|---|---|
| CLK Fall + DT=HIGH | D2 ISR Trigger | Clockwise Detent | Increment Dial (+5% PWM) |
| CLK Fall + DT=LOW | D2 ISR Trigger | Counter-Clockwise | Decrement Dial (-5% PWM) |
| SW Pressed | D4 = LOW | Center Click | Reset Dial to 50% |
Engineering Troubleshooting Matrix
| Problem | Likely Cause | Diagnostic Check | Engineering Solution |
|---|---|---|---|
| Turning clockwise lowers the number instead of raising it | CLK and DT phase polarity reversed | Turn CW and watch count direction | Swap CLK and DT wires (or invert DT == LOW in ISR). |
| Single click jumps by 2 or 3 counts | Mechanical switch bounce exceeding 4ms | Twist slowly one click at a time | Increase ISR guard from 4000UL to 8000UL microseconds. |
| Center button never resets | Missing INPUT_PULLUP on SW pin | Check D4 voltage with DMM | Ensure pinMode(PIN_SW, INPUT_PULLUP) is active. |
Engineering Challenges & Upgrades
Take your build to the next level with these progressive engineering upgrades:
Move a glowing LED left and right across 5 digital pins as you twist the encoder.
Use the rotary knob to highlight items on Project 4 OLED and click SW to select.
Drive Project 15 (28BYJ-48) directly like a CNC manual handwheel.