Arduino Nano - 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://newbiely.com/tutorials/arduino-nano/arduino-nano-rotary-encoder
This build reads a rotary encoder with an Arduino Nano: turning the knob increases or decreases a counter depending on direction, and pressing the knob's built-in button is detected separately. The encoder outputs two offset pulse signals (CLK and DT) instead of an analog voltage, which makes it useful for counting turns, menu navigation, or controlling things like LED brightness, servo position, or stepper speed.
Supplies
Everything below is what the build uses. The links go to the parts we make and test.
- Official Arduino Nano
- DIYables Nano V3.0 Development Board
- USB A to Mini-B USB cable
- Rotary Encoder
- Jumper Wires
- Breadboard
- Screw Terminal Expansion Board for Arduino Nano
- Breakout Expansion Board for Arduino Nano
- Power Splitter for Arduino Nano
- DIYables Sensor Kit (18 sensors/displays)
Wiring
Connect the encoder's CLK pin to Nano pin 2, DT pin to pin 3, and SW pin to pin 4. Connect VCC to the Nano's 3.3V or 5V and GND to GND. The SW pin is normally open and relies on a pull-up so it reads HIGH when the knob is not pressed and LOW when pressed.
How It Works
Inside the encoder a disc connects pins A and B to a common ground pin as you turn the knob, and A and B touch ground in a different order depending on direction - this is quadrature encoding, with the two signals 90 degrees out of phase. The code watches the CLK pin: when it changes from LOW to HIGH, it checks DT. If DT is HIGH the knob turned anticlockwise and the counter decreases; if DT is LOW it turned clockwise and the counter increases.
Code
The sketch configures CLK and DT as inputs and uses the ezButton library to debounce the SW pin with a 50ms debounce time. In the main loop it reads CLK, compares it to its previous state, and on a LOW-to-HIGH edge reads DT to decide direction, updating and printing the counter over serial. It also checks button.isPressed() to report presses. A second version of the sketch does the same detection using interrupts instead of constantly polling the CLK pin, which avoids missing a turn while other code is running and frees up the Nano.
arduino-nano-rotary-encoder.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://newbiely.com/tutorials/arduino-nano/arduino-nano-rotary-encoder