What it is: The KY-040 is a rotary encoder — a knob you can turn endlessly in either direction, plus a built-in push button. It's the input device for menus, volume controls and setting values.
How it works: Turning the knob produces two square waves (CLK and DT) 90° out of phase. By checking DT at the moment CLK changes, you know the direction. The shaft also presses down as a button (SW). All digital.
Wiring:
KY-040 CLK -> GPIO10
KY-040 DT -> GPIO6
KY-040 SW -> GPIO7 (push button)
KY-040 + -> 3V3
KY-040 GND -> GND
OLED VCC=3V3, GND=GND, SDA=GPIO4, SCL=GPIO5
Libraries: only "Adafruit SSD1306" and "Adafruit GFX Library".
On screen / Serial: a counter that goes up when you turn one way and down the other. Press the knob to reset to 0.
Gotchas: Cheap encoders bounce; this sketch reads on the CLK falling edge to reduce it, but for heavy use add small capacitors or use an interrupt-based library. The internal button needs a pull-up (enabled in code).