Arduino Encoder Library Rotary Knob: Wiring, Code and Simulator

To build this Arduino Encoder Library Rotary Knob project you need an Arduino Uno and a KY-040 rotary encoder. The PJRC Encoder library counts a KY-040 knob on interrupt pins 2 and 3. Make the 5 connections in the wiring table, upload the Arduino C++ code, and turn the knob both ways and watch the count go up and down.

Open this circuit in the free Arduino Uno simulator

Parts list

QtyPartWhat it does
1Arduino Unothe microcontroller board
1KY-040 rotary encoderCLK and DT are switches to GND with pull-ups: clockwise, CLK falls before DT. SW is a push button to GND (use INPUT_PULLUP).

Wiring

#FromTo
1Arduino Uno pin 2KY-040 rotary encoder CLK
2Arduino Uno pin 3KY-040 rotary encoder DT
3Arduino Uno pin 4KY-040 rotary encoder SW
4Arduino Uno 5VKY-040 rotary encoder VCC
5Arduino Uno GNDKY-040 rotary encoder GND

Step by step

  1. Open the simulator. Open the BitForBytes Embedded Lab in your browser and start from the Arduino Uno. No install or account is needed.
  2. Add the parts. Add a KY-040 rotary encoder from the parts palette.
  3. Wire 1. Connect Arduino Uno pin 2 to KY-040 rotary encoder CLK.
  4. Wire 2. Connect Arduino Uno pin 3 to KY-040 rotary encoder DT.
  5. Wire 3. Connect Arduino Uno pin 4 to KY-040 rotary encoder SW.
  6. Wire 4. Connect Arduino Uno 5V to KY-040 rotary encoder VCC.
  7. Wire 5. Connect Arduino Uno GND to KY-040 rotary encoder GND.
  8. Paste the Arduino C++ code. Paste the Arduino C++ code below into the code editor.
  9. Run it. Press Run. Turn the knob both ways and watch the count go up and down.

Arduino C++ code

// Encoder (PJRC): read a KY-040 rotary encoder on interrupt pins 2 and 3.
#include <Encoder.h>

Encoder knob(2, 3);
long last = -999;

void setup() {
  Serial.begin(9600);
}

void loop() {
  long now = knob.read();
  if (now != last) {
    last = now;
    Serial.print("Count: ");
    Serial.println(now);
  }
}

What to try

Turn the knob both ways and watch the count go up and down.

Frequently asked questions

How do I wire the Encoder Library Rotary Knob project on an Arduino Uno?

Make 5 connections: Arduino Uno pin 2 to KY-040 rotary encoder CLK; Arduino Uno pin 3 to KY-040 rotary encoder DT; Arduino Uno pin 4 to KY-040 rotary encoder SW; Arduino Uno 5V to KY-040 rotary encoder VCC; Arduino Uno GND to KY-040 rotary encoder GND.

What parts do I need for this Arduino project?

An Arduino Uno and a KY-040 rotary encoder.

Can I simulate this Arduino project online for free?

Yes. The BitForBytes Embedded Lab runs this exact circuit and Arduino C++ code in your browser for free, with no install and no hardware. The sketch is compiled with the real Arduino toolchain and runs on an emulated ATmega328P.

What does the code do?

The PJRC Encoder library counts a KY-040 knob on interrupt pins 2 and 3.

More Arduino Uno projects