// original code from https://lastminuteengineers.com/rotary-encoder-arduino-tutorial/ // minor modifications by Paradox 11/3/2024 // encoder_test.ino // Rotary Encoder Inputs #define CLK 2 // when connecting, connect CLK on the encoder to pin 3 but leave this in place #define DT 3 // connect DT on the encoder to pin 4 but leave this in place #define SW 4 // pin where button is located HIGH when not pushed int counter = 0; // rotation variable int currentStateCLK; // state of CLK needed to determine if encoder rotated int lastStateCLK; // state of CLK last time it was read needed to determine if encoder rotatied String currentDir =""; // string that will print CW or CWW depending on rotation direction unsigned long lastButtonPress = 0; // state of button last time read void setup() { // Set encoder pins as inputs pinMode(CLK,INPUT); pinMode(DT,INPUT); pinMode(SW, INPUT_PULLUP); // switch is high when not pushed // Setup Serial Monitor Serial.begin(115200); // Read the initial state of CLK lastStateCLK = digitalRead(CLK); // set lastStateCLK to current reading of CLK to start with delay(1000); // A bit of time to settle down Serial.println("all done innitializing: spin the encoder and push the button "); } void loop() { // Read the current state of CLK each time through the loop currentStateCLK = digitalRead(CLK); // get the current state of 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"; } if(counter<0){counter=0;} // set minimum counter reading if(counter>99){counter=99;} // set maximum counter reading 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 less than 50ms have passed, the Arduino is reading switch bounce so don't react 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); }