#define ENCODER_CLK 34
#define ENCODER_DT 32
int lastClk=HIGH;
int SW = 26;
bool lastButtonStatus = false;
int count = 0;
int current_stateCLK;
int last_stateCLK;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(SW, INPUT);
digitalWrite(SW, HIGH);//连接按钮的引脚设为上拉
// Serial.begin(9600);
// 读取inputCLK的初始状态
// 赋值给 previousStateCLK 变量
last_stateCLK = digitalRead(ENCODER_CLK);
Serial.println(last_stateCLK);
}
void loop() {
// put your main code here, to run repeatedly:
// delay(10); // this speeds up the simulation
int newClk = digitalRead(ENCODER_CLK);
if (newClk != lastClk) {
// There was a change on the CLK pin
lastClk = newClk;
int dtValue = digitalRead(ENCODER_DT);
if (newClk == LOW && dtValue == HIGH) {
Serial.println("Rotated clockwise ⏩");
}
if (newClk == LOW && dtValue == LOW) {
Serial.println("Rotated counterclockwise ⏪");
}
}
current_stateCLK = digitalRead(ENCODER_CLK); //读取CLK的当前状态
// 如果CLK 的先前状态和当前状态不同,则发生脉冲
if (current_stateCLK != last_stateCLK && current_stateCLK == 1) {
// 如果 inputDT 状态与 inputCLK 状态不同,则
// 编码器逆时针旋转
if (digitalRead(ENCODER_DT) != current_stateCLK) {
count --;
if (count < 0)
count = 0;
} else {
// 编码器顺时针旋转
count ++;
if (count > 179)
count = 179;
}
Serial.print("角度位置: ");
Serial.println(count);
}
last_stateCLK = current_stateCLK; // 用当前状态更新 last_stateCLK
// bool buttonStatus = !digitalRead(SW);//高电平时未按下,状态为false
// if (buttonStatus != lastButtonStatus)
// {
// Serial.println(buttonStatus ? "按下SW" : "松开SW");
// lastButtonStatus = buttonStatus; //保存当前状态
// }
}