
音响上的音量旋钮、微波炉的定时旋钮、鼠标滚轮,背后都是同一个东西——旋转编码器。创客圈最常见的就是KY-040模块:几块钱一颗,能无限圈旋转、能判方向、轴心还藏着一个按压开关。这篇把它拆到脉冲级,看完你就知道为什么调参数的活儿都该交给它,而不是电位器。
内部结构:一张带缺口的光栅盘
KY-040是机械式编码器。轴心连着一块带均匀缺口的圆盘,盘体接公共地。旋钮转动时,两个触点A和B会反复接通、断开公共地。关键在缺口排布:A和B不会同时接地,而是错开一个固定相位。这个“错开”就是全部秘密——当A脚状态跳变的那一瞬间看一眼B脚的状态,就能判断旋钮往哪边转。这套机制叫正交编码(Quadrature Encoding),工业编码器玩的也是同一套逻辑,只是精度和工艺档次不同。
和电位器比,编码器优势明显:旋转无上限,读出来的是“增量”而不是绝对位置,数字接口直连IO口,不会像电位器那样受模拟噪声干扰。缺点是不能告诉你“绝对角度”,断电重启后计数从零开始。
五个引脚各管一摊
KY-040引出五个脚:VCC接5V或3.3V供电;GND接地;CLK输出正交信号的第一路;DT输出第二路,与CLK相位差90度;SW接轴心内置的按压开关,平时被上拉电阻拉高,按下拉低。旋转一周通常有20个定位格,每格在CLK和DT上各产生一个完整的脉冲周期,方向不同时两路信号的先后次序相反。
接线三根信号线

以Arduino UNO为例:VCC接5V,GND接GND,CLK接D2,DT接D3,SW接D4。D2、D3在UNO上恰好是两个外部中断脚,为后面升级中断读法留了路。接线就这么多,不需要任何外围元件,模块板载了上拉电阻。
完整代码:轮询读方向与计数
先跑轮询版本,逻辑最直白:
// Rotary Encoder Inputs
#define CLK 2
#define DT 3
#define SW 4
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir = "";
unsigned long lastButtonPress = 0;
void setup() {
// Set encoder pins as inputs
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
pinMode(SW, INPUT_PULLUP);
// Setup Serial Monitor
Serial.begin(9600);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
}
void loop() {
// Read the current state of CLK
currentStateCLK = digitalRead(CLK);
// If last and current state of CLK are different, then pulse occurred
// React to only 1 state change to avoid double count
if (currentStateCLK != lastStateCLK && currentStateCLK == 1) {
// If the DT state is different than the CLK state then
// the encoder is rotating CCW so decrement
if (digitalRead(DT) != currentStateCLK) {
counter--;
currentDir = "CCW";
} else {
// Encoder is rotating CW so increment
counter++;
currentDir = "CW";
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
// Read the button state
int btnState = digitalRead(SW);
//If we detect LOW signal, button is pressed
if (btnState == LOW) {
//if 50ms have passed since last LOW pulse, it means that the
//button has been pressed, released and pressed again
if (millis() - lastButtonPress > 50) {
Serial.println("Button pressed!");
}
// Remember last button press event
lastButtonPress = millis();
}
// Put in a slight delay to help debounce the reading
delay(1);
}要点两个。第一,只在CLK从低变高的那个沿上动作,其余状态变化直接忽略,否则一格会被数成两次。第二,按压开关的判定加了50毫秒时间窗做软件消抖,机械触点的抖动不会再被当成连按。
轮询的极限与中断方案

轮询版有个隐患:loop里塞了别的耗时逻辑后,脉冲沿容易被错过,计数就丢格。正路子是把CLK接到中断脚,沿触发读数,主程序再忙也不丢脉冲:
把attachInterrupt(digitalPinToInterrupt(2), 读数函数, RISING)挂上,中断服务程序里做方向判断和计数,loop只管干活。实测对比明显:快速旋转时,轮询版偶发丢格,中断版一格不落。
中断服务程序里不要print,置个标志位让loop去打印,这是惯例也是底线,否则串口的慢速会把中断系统拖死。
选型小结
KY-040适合调参数、翻菜单、控音量这类增量操作,成本低到可以每块板子都塞一颗。要绝对位置就老实用电位器,要高精度大扭矩的手感就上工业编码器。对绝大多数Arduino和ESP32项目,KY-040就是那个“正确答案”,截至2026年12月6日它仍是各主流渠道默认推荐的入门编码器模块。











正交编码讲明白了,以前只知道用不知道为啥
音量旋钮那个例子好,瞬间理解了什么叫增量操作
中断里不print这条铁律,踩过的人才会懂
丢格这个坑轮询必踩,直接上中断吧别犹豫