Arduino - Rotary Encoder
This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://arduinogetstarted.com/tutorials/arduino-rotary-encoder
This project reads a rotary encoder with an Arduino Uno. As you turn the knob, the encoder's CLK and DT pins pulse out of phase with each other, letting the Arduino figure out how far and in which direction the knob moved, while a built-in pushbutton on the SW pin can be read separately. It's a direction-and-click input, useful anywhere you'd otherwise reach for a potentiometer.
Supplies
Everything below is what the build uses. The links go to the parts we make and test.
- Official Arduino Uno
- DIYables STEM V3, Fully Compatible with Arduino Uno R3
- USB 2.0 cable type A/B (for USB-A PC)
- USB 2.0 cable type C/B (for USB-C PC)
- Rotary Encoder
- Jumper Wires
- Screw Terminal Block Shield for Arduino Uno
- Sensors/Servo Expansion Shield for Arduino Uno
- Breadboard Shield for Arduino Uno
- Enclosure for Arduino Uno
- Prototyping Base Plate & Breadboard Kit for Arduino UNO
- DIYables STEM V3 Starter Kit (Arduino included)
- DIYables Sensor Kit (18 sensors/displays)
Wiring
Connect the rotary encoder's CLK pin to Arduino digital pin 2, the DT pin to digital pin 3, and the SW pin to digital pin 4. Connect the encoder's VCC pin to the Arduino's 5V (or 3.3V) pin and its GND pin to Arduino GND.
How It Works
Inside the encoder a slotted disc connects pins A and B to a common ground pin C as the knob turns. Because A and B touch ground at slightly different times, their signals (CLK and DT) are 90 degrees out of phase, a pattern called quadrature encoding. When CLK goes from LOW to HIGH, checking DT tells you direction: DT LOW means clockwise, DT HIGH means counter-clockwise. The SW pin is normally HIGH through a pull-up and goes LOW when the knob is pressed.
Code
The sketch sets CLK and DT as inputs and uses the ezButton library to debounce the SW pin. In the loop it reads CLK, and whenever it sees a LOW-to-HIGH transition it checks DT to decide direction, then increments or decrements a counter and prints the direction and count to the Serial Monitor. A separate version does the same thing using an interrupt on the CLK pin instead of continuously polling it, which avoids wasting Arduino cycles and prevents missed counts if other code is running.
arduino-rotary-encoder.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://arduinogetstarted.com/tutorials/arduino-rotary-encoder