ESP8266 Peripherals: KY-040 Rotary Encoder

Lets get our hands dirty!

Now to a practical example. Wire up your encoder like this the following picture, make sure that you follow the labels and not the ordering, I might have turned something upside down:


Wiring of the KY-040 with the NodeMCU

  • GND to GND
  • + to 3.3V
  • SW to D3
  • DT to D2
  • CLK to D1


Installing the library

There are different libraries that might work. This library worked well for me: Download the ZIP and unpack it into your Arduino library directory. Restart the Arduino IDE and copy the code from here:

#include <Encoder.h>

Encoder myEnc(D1, D2);

long oldPosition  = -999;
boolean isButtonPressed = false;
long lastUpdateMillis = 0;

void handleKey() {
  isButtonPressed = true;  

void setup() {
  Serial.println("Basic Encoder Test:");
   pinMode(D3, INPUT_PULLUP);
   attachInterrupt(D3, handleKey, RISING);

void loop() {
  long newPosition =;
  if (newPosition != oldPosition) {
    oldPosition = newPosition;
  // software debounce
  if (isButtonPressed && millis() - lastUpdateMillis > 50) {
    isButtonPressed = false;
    lastUpdateMillis = millis();
    // Reset the counter

After uploading the sketch you can open the serial console, turn the knob up and down and press the axis to reset the counter. Your output might look something like this:

Basic Encoder Test:
0 <- Knob pressed
0<- Knob pressed


Suggested applications

  • WeatherStation Frame Controller: Some readers were asking me how they could control the currently displayed frame of the WeatherStation. Depending on the amount of the frames you are using it might take a while until the one that interests you the most comes around. The rotary encoder is a nice extension which allows you to quickly zap through the frames without having to implement a lot of code
  • Wifi Selector for unprotected APs: lets assume you have a setup with an ESP8266, a display and you want to quickly select an unprotected wifi to connect to without using the web interface: just implement some kind of menu and use the rotary encoder to move a cursor from one SSID to the next and the knob button to select the AP you actually want to connect to
Related:  Plenty of new tricks for Feederator


Where to buy?

You can find rotary encoders and the KY-040 in general all over the web at the usual electronic shops. If you liked this article and you plan to order a KY-040 consider following this link to Banggood and I will get a little reward for recommending you:



Now a beer! Did you like this post? It often takes me several hours of my free time to write one. If I was your neighbour would you offer me a beer for the hard work I did for you? The beauty is: beers can be teletransported with a painless donation using Paypal. A beer in a Swiss bar costs about USD $4.80. Or use this affiliate link if you order something on Banggood and I'll get a small kickback. Thank you!