Rotary Control
Jump to navigation
Jump to search
Rotory Pin | ESP32 Pin |
---|---|
Switch | GPIO 25 |
GND | GND |
Out A (CLK) | GPIO 27 |
GND | GND |
Out B (DT) | GPIO 26 |
Kodas:
#define CLK 27
#define DT 26
#define SW 25
int counter = 0;
int currentStateCLK;
int lastStateCLK;
bool buttonPressed = false;
void setup() {
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
pinMode(SW, INPUT_PULLUP); // Use internal pull-up for switch
Serial.begin(115200);
lastStateCLK = digitalRead(CLK);
}
void loop() {
currentStateCLK = digitalRead(CLK);
if (currentStateCLK != lastStateCLK && currentStateCLK == 1) {
if (digitalRead(DT) != currentStateCLK) {
counter++;
} else {
counter--;
}
Serial.print("Position: ");
Serial.println(counter);
}
lastStateCLK = currentStateCLK;
if (digitalRead(SW) == LOW && !buttonPressed) {
Serial.println("Button Pressed");
buttonPressed = true;
}
if (digitalRead(SW) == HIGH && buttonPressed) {
buttonPressed = false;
}
delay(1); // debouncing
}