CNAP

KY-040 Rotary Encoder Reference

A quadrature rotary encoder with a built-in push button — reports relative rotation (clockwise/counter-clockwise steps) rather than an absolute position like a potentiometer.

Pin names

NameDescription
CLKQuadrature output A
DTQuadrature output B
SWPush-button — momentary switch to GND when pressed
VCCPower (5V)
GNDGround

Attributes

This component has no configurable attributes.

Usage

Connect VCC to 5V, GND to GND, and CLK/DT/SW each to a GPIO configured with INPUT_PULLUP. Determine rotation direction by comparing CLK to DT on each CLK transition.

const int CLK_PIN = 2;
const int DT_PIN  = 3;
const int SW_PIN  = 4;

int lastClk;

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

void loop() {
  int clk = digitalRead(CLK_PIN);
  if (clk != lastClk) {
    if (digitalRead(DT_PIN) != clk) {
      Serial.println("Clockwise");
    } else {
      Serial.println("Counter-clockwise");
    }
  }
  lastClk = clk;

  if (digitalRead(SW_PIN) == LOW) {
    Serial.println("Button pressed");
    delay(200); // simple debounce
  }
}

Examples

DescriptionAttrs
Default KY-040 encoder{}

See also

  • Potentiometer — absolute-position alternative for simple analog control
  • Pushbutton — same debounce/press pattern as the encoder's SW pin