ESP32 - Rotary Encoder LED
by DIYables in Circuits > Microcontrollers
7 Views, 0 Favorites, 0 Comments
ESP32 - 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://esp32io.com/tutorials/esp32-rotary-encoder-led
This build uses a rotary encoder to control the brightness of an LED on an ESP32. Turning the encoder clockwise increases brightness, turning it counter-clockwise decreases it. The sketch reads the encoder's CLK and DT pins to determine direction and adjusts the LED's PWM output accordingly.
Supplies
Everything below is what the build uses. The links go to the parts we make and test.
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Narrow
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- 30-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- ESP32 Uno-form board
- ESP32 S3 Uno-form board
- USB Cable Type-A to Type-C (for USB-A PC)
- USB Cable Type-C to Type-C (for USB-C PC)
- Rotary Encoder
- LED Kit
- LED (red)
- LED Module
- Button and LED Kit
- 220Ω Resistor
- Breadboard
- Jumper Wires
- Screw Terminal Expansion Board for ESP32
- Breakout Expansion Board for ESP32
- Power Splitter for ESP32
- DIYables ESP32 Starter Kit (ESP32 included)
- DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
- DIYables Sensor Kit (18 sensors/displays)
Wiring
Connect the rotary encoder's CLK pin to ESP32 GPIO25, DT pin to GPIO26, and SW pin to GPIO27. Connect the LED to GPIO22 through a 220Ω resistor. Build the circuit on a breadboard, and power the ESP32 and encoder as needed.
How It Works
The ESP32 continuously reads the CLK pin of the rotary encoder. When CLK changes from LOW to HIGH, the code checks the DT pin to determine rotation direction: if DT is HIGH, the encoder turned counter-clockwise and brightness decreases; otherwise it turned clockwise and brightness increases. The brightness value is clamped between 0 and 255, then written to the LED pin with analogWrite so the LED dims or brightens as you turn the knob.
Code
The sketch defines pins for CLK, DT, SW and the LED, and keeps track of a brightness variable starting at 125. In the main loop it detects the rising edge of the CLK signal, updates a counter and the brightness value based on direction, keeps brightness within the 0-255 range, applies it to the LED with analogWrite, and prints the counter and brightness to the serial monitor for debugging.
esp32-rotary-encoder-led.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://esp32io.com/tutorials/esp32-rotary-encoder-led