旋转编码开关模块
2023年5月28日大约 2 分钟
概述
旋转编码开关又称小型旋转编码器,是指具有一组有规律且严格时序脉冲的开关电子元器件。
产品实拍
产品参数
- 工作电压:3.3V~5V
- 接口类型:ph2.0 5P
- 尺寸:24mm*40mm
引脚说明
序号 | 名称 | 功能描述 |
---|---|---|
1 | VCC | 3V3~5V电源正极 |
2 | GND | 电源负极 |
3 | D | 按钮开关的输出(低电平有效),当按下旋钮时,电压变低 |
4 | A | 用于确定旋转量的主要输出脉冲 |
5 | B | 用于确定旋转方向 |
硬件连接
旋转编码开关 | UNO主控板 |
---|---|
G | GND |
V | 5V |
A | 2 |
B | 3 |
D | 4 |
示例代码
Arduino
// 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);
}
结果
打开串口监视器,会看到类似以下图片的输出,每当旋钮旋转一档时,变量就会有变化,顺时针旋转数值减小,逆时针旋转数值增大;按下时,会返回Button pressed!
疑难解答
更多问题及有趣的应用,请访问论坛 或加入QQ技术交流群:522420541