Arduino - Rotary Encoder LED
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-led
This build uses a rotary encoder to control the brightness of an LED. Turning the knob clockwise increases brightness, turning it counter-clockwise decreases it, and the current counter and brightness values are printed to the Serial Monitor so you can follow along while you turn the encoder.
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
- LED Kit
- LED (red)
- LED Module
- Button and LED Kit
- 220Ω Resistor
- Breadboard
- 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 pin 2, the DT pin to pin 3, and the SW pin to pin 4. Connect the LED to pin 9. Using an LED Module is recommended since it has a built-in resistor, which simplifies the wiring. If you use a plain LED instead, wire it through a 220 ohm resistor on the breadboard.
How It Works
The Arduino continuously reads the CLK pin of the encoder. When CLK changes from LOW to HIGH, a pulse has occurred. At that rising edge, the code checks the DT pin: if DT is HIGH the encoder turned counter-clockwise, if DT is LOW it turned clockwise. Each pulse changes the brightness value by 10, clockwise increases it and counter-clockwise decreases it. The brightness is clamped between 0 and 255 and then written to the LED pin with analogWrite, which uses PWM to dim or brighten the LED.
Code
The sketch sets CLK and DT as inputs and LED_PIN as an output, then reads the initial CLK state. In the loop it compares the current CLK state to the previous one, reacting only on the rising edge to avoid counting the same pulse twice. Depending on the DT pin it updates a direction variable and a counter, adjusts the brightness variable by plus or minus 10, clamps it to the 0-255 range, writes it to the LED with analogWrite, and prints the counter and brightness to the Serial Monitor.
arduino-rotary-encoder-led.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://arduinogetstarted.com/tutorials/arduino-rotary-encoder-led