Rotary Encoder Usage Tutorial#
What is a Rotary Encoder?#
Rotary Encoder is a sensor that converts rotational position or rotational motion into digital signals. Common incremental rotary encoders provide position feedback by detecting rotation direction and rotation amount. Commonly used for:
Volume adjustment knob
Menu navigation control
Precise position control
Speed and direction detection
Industrial automation equipment
K230 supports connecting incremental rotary encoders, reading the encoder’s CLK (clock), DT (data), and SW (button) signals through GPIO pins, achieving:
Rotation direction detection (clockwise/counterclockwise)
Rotation count (delta value and total count)
Button state detection (encoders usually come with a press switch)
Example Overview#
The following example demonstrates how to use the K230’s ENCODER module to complete the following operations:
Initialize the rotary encoder
Read rotation data and button state
Reset encoder count
Release encoder resources
Import Module and Initialize Encoder#
from machine import ENCODER
# Initialize encoder 0, connect CLK to pin 42, DT to pin 43, SW to pin 5
encoder = ENCODER(id=0, pin_clk=42, pin_dt=43, pin_sw=5)
id: Encoder instance number (required, different ids are used to distinguish multiple encoder instances, such as id=0,1,2,3…)pin_clk: Clock signal pin (required)pin_dt: Data signal pin (required)pin_sw: Button signal pin (optional, can be set to -1 when not in use)
Read Encoder Data#
# Blocking read, wait for encoder event
data = encoder.read()
if data:
print(f"Delta change: {data.delta}")
print(f"Total count: {data.total_count}")
print(f"Rotation direction: {data.direction}")
print(f"Button state: {data.button_state}")
print(f"Timestamp: {data.timestamp}")
# Read with timeout (unit: milliseconds)
data = encoder.read(timeout_ms=1000)
if data is None:
print("No encoder event within 1 second")
The returned data object contains the following properties:
delta: Delta change value for this eventtotal_count: Total count value since initializationdirection: Rotation direction (DIR_CW clockwise / DIR_CCW counterclockwise / DIR_NONE none)button_state: Button state (0 released / 1 pressed)timestamp: Event timestamp
Reset Encoder Count#
# Reset the encoder's total count value to 0
encoder.reset()
Release Encoder Resources#
# Release encoder resources
del encoder
# Or explicitly call
encoder.__del__()
Direction Constants Description#
The ENCODER class provides the following direction constants:
Constant |
Value |
Description |
|---|---|---|
DIR_NONE |
0 |
No rotation |
DIR_CW |
1 |
Clockwise rotation |
DIR_CCW |
2 |
Counterclockwise rotation |
Usage example:
if data.direction == ENCODER.DIR_CW:
print("Clockwise rotation")
elif data.direction == ENCODER.DIR_CCW:
print("Counterclockwise rotation")
Complete Usage Example#
from machine import ENCODER
import time
# Initialize encoder
encoder = ENCODER(id=0, pin_clk=42, pin_dt=43, pin_sw=5)
# Menu selection example
menu_items = ["Option 1", "Option 2", "Option 3", "Option 4"]
current_index = 0
print("Rotate to select menu item, press to confirm")
while True:
# Read encoder event, 100ms timeout
data = encoder.read(100)
if data:
# Update menu index based on rotation direction
if data.direction == ENCODER.DIR_CW:
current_index = (current_index + 1) % len(menu_items)
elif data.direction == ENCODER.DIR_CCW:
current_index = (current_index - 1) % len(menu_items)
# Display current selected item
print(f"Current selection: {menu_items[current_index]}")
# Detect button press
if data.button_state == 1:
print(f"Confirmed selection: {menu_items[current_index]}")
break
# Clean up resources
del encoder
Application Scenarios#
User interface control (menu navigation, parameter adjustment)
Volume/brightness adjustment (precise value adjustment)
Position control (stepper motor control, robotic arm positioning)
Measurement instruments (angle measurement, length measurement)
Game controllers (steering wheel, knob control)
Notes#
CLK and DT pins are required, SW pin is optional
It is recommended to connect pull-up resistors to CLK and DT pins (usually built into the encoder module)
During fast rotation, more frequent reading may be needed to avoid missing events
Compilation Switch#
The rotary encoder is disabled by default. To enable it, execute
make menuconfigand turn on the following corresponding compilation option:
> RT-Smart Configuration > RT-Thread Smart System Features
[*] Enable Rotary Encoder Support
