All wiring guides

Free wiring guides

Wire the KY-040 rotary encoder to the ESP32-C3

Rotary encoder module, KY-040. A knob that turns forever and clicks when pressed.

Which pin goes where

On the partOn the ESP32-C3
GNDGND
+3V3
SWGPIO 3
DTGPIO 1
CLKGPIO 0

Wire it with the USB cable unplugged. Follow the names printed on your own part: makers sometimes reorder the pins.

In 3D

Example sketch

// Rotary encoder module, KY-040
// on the ESP32-C3 Super Mini
// https://stem.manusignal.com/en/parts/ky-040-rotary-encoder-esp32-c3

const int PIN_CLK = 0;
const int PIN_DT = 1;
const int PIN_SW = 3;

int count = 0;
int lastClk = HIGH;

void setup() {
  Serial.begin(115200);
  pinMode(PIN_CLK, INPUT_PULLUP);
  pinMode(PIN_DT, INPUT_PULLUP);
  pinMode(PIN_SW, INPUT_PULLUP);
  lastClk = digitalRead(PIN_CLK);
}

void loop() {
  int clk = digitalRead(PIN_CLK);
  if (clk != lastClk && clk == LOW) {
    count += digitalRead(PIN_DT) == HIGH ? 1 : -1;
    Serial.println(count);
  }
  lastClk = clk;
  if (digitalRead(PIN_SW) == LOW) {
    Serial.println("pressed");
    delay(250);
  }
  delay(1);
}
  • Tools > Board > ESP32C3 Dev Module (USB CDC On Boot: Enabled), then Tools > Port and choose the board's port.

This sketch is compiled for the board before the page is published. It has not been run on real hardware by us.

What you should see

Open the Serial Monitor at 115200. The count goes up one way and down the other, and “pressed” prints when you push the knob.

If it does not work

Turning the knob counts the wrong way.
Swap the CLK and DT wires.

The same part on the ESP32-S3

More parts on the ESP32-C3