音量旋钮一拧就走、鼠标滚轮一圈一格——这些手感干脆的部件,多半就是旋转编码器。KY-040模块把它们做成了几块钱的标准件,五个引脚,Arduino接上就能用。这次把它的原理、基础计数、中断写法到控制舵机一次过完,代码都可直接搬去用。

它凭什么能"认出"正反转
编码器内部是一张带均匀缺口的圆盘,跟着旋钮一起转,公共脚C始终接地。A、B两个引脚随盘面转动反复接触地线,但两者的接触时机错开四分之一周期,也就是常说的"90度相位差"。
判向的诀窍是盯住A相翻转那一瞬:此刻B相若是低电平(与A不同),说明在顺时针转,计数加一;B相若与A相同,就是逆时针,计数减一。这套机制叫正交编码,转动方向和圈数都能还原出来。
引脚与接线
KY-040模块共五个脚:+(VCC)接5V供电,GND接地,SW是模块自带的按压开关,按下时被拉到低电平,平时靠内部上拉保持高;CLK和DT就是两路正交输出。
接线安排:CLK接数字2脚,DT接数字3脚,SW接数字4脚,5V和GND照常。2、3脚选在支持外部中断的位置,后面用中断写法时不用改线。

例程一:轮询读出方向与计数
第一个例程在loop里轮询CLK。只在CLK出现上升沿时才做判断,可以避免单圈被重复计数;SW按键用50毫秒间隔做软件消抖。
// 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);
}烧录后打开串口监视器(9600波特),拧一格打印一行,方向和计数一目了然,按下旋钮还会报一句"Button pressed!"。

轮询写法的问题也很直白:loop里塞了延时,主程序一忙起来脉冲就可能漏计。这时把读数搬到中断里更稳。
例程二:中断版本不漏脉冲
把CLK脚的每次电平变化都交给中断处理,主循环可以腾出手干别的事。接线不变,SW脚可以不接。

// Rotary Encoder Inputs
#define CLK 2
#define DT 3
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir = "";
void setup() {
// Set encoder pins as inputs
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
// Setup Serial Monitor
Serial.begin(9600);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
// Call updateEncoder() when a change is seen on CLK pin
attachInterrupt(digitalPinToInterrupt(CLK), updateEncoder, CHANGE);
}
void loop() {
//Do some useful stuff here
}
void updateEncoder() {
// 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;
}关键就一行:attachInterrupt把updateEncoder挂到CLK的中断上,CHANGE触发。中断里别做串口打印太多、也别用delay,这段代码的打印只在中断里出现一次,量不大,实测没有问题。
例程三:拧旋钮直接控舵机
把计数限制到0到179,正好映射舵机的角度行程。接线在编码器侧不变,舵机信号接9脚,供电最好单独给5V。

// Include the Servo Library
#include "Servo.h"
// Rotary Encoder Inputs
#define CLK 2
#define DT 3
Servo servo;
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir = "";
void setup() {
// Set encoder pins as inputs
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
// Setup Serial Monitor
Serial.begin(9600);
// Attach servo on pin 9 to the servo object
servo.attach(9);
servo.write(counter);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
// Call updateEncoder() when a change is seen on CLK pin
attachInterrupt(digitalPinToInterrupt(CLK), updateEncoder, CHANGE);
}
void loop() {
//Do some useful stuff here
}
void updateEncoder() {
// 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--;
if (counter < 0)
counter = 0;
} else {
// Encoder is rotating CW so increment
counter++;
if (counter > 179)
counter = 179;
}
// Move the servo
servo.write(counter);
Serial.print("Position: ");
Serial.println(counter);
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
}逆时针拧到头停在0度,顺时针最多到179度,中断里每来一个脉冲就更新一次舵机角度,手感跟音量旋钮几乎一样。
几句提醒
一是旋转编码器不是电位器,可以无限圈拧,程序里要自己设定数值上下限;二是机械触点有抖动,中断版本靠"只认上升沿"已经滤掉大半,串口里偶发跳一格属于正常现象;三是SW脚务必接上拉,悬空会出现乱报按键。
有了计数、中断、按压三件事,KY-040就足以承担菜单翻页、数值步进这类交互角色,配合舵机或者步进电机能很快搭出一台手动定位的装置。











上个月刚好用KY-040做了功放音量旋钮,正交编码这段原理讲得比_datasheet明白多了。
#include "Servo.h"这个写法细节很关键,之前照抄尖括号版本死活编不过还以为是库问题。
这种轮询改中断的对比讲得挺实在,之前我主循环一加display刷新就漏计数,换了attachInterrupt才稳。
问一下SW那个按压开关做菜单确认键,长按识别是在loop里另计时间吧?