Advertisement
LeventeDaradici

Rotary encoder with push button

Oct 2nd, 2021
1,479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #define CLK 2
  2. #define DT 3
  3. #define SW 4
  4.  
  5. int currentStateCLK;
  6. int lastStateCLK;
  7. int counter = 0;
  8.  
  9. String currentDir ="";
  10. unsigned long lastButtonPress = 0;
  11.  
  12. void setup()
  13.      {
  14.           pinMode(CLK,INPUT);
  15.           pinMode(DT,INPUT);
  16.           pinMode(SW, INPUT_PULLUP);
  17.           Serial.begin(9600);
  18.           lastStateCLK = digitalRead(CLK);
  19.         Serial.print("Direction: ");
  20.           Serial.print(currentDir);
  21.           Serial.println(counter);
  22.      }
  23.  
  24. void loop()
  25.      {
  26.             currentStateCLK = digitalRead(CLK);
  27.           if (currentStateCLK != lastStateCLK  && currentStateCLK == 1)
  28.            {
  29.               if (digitalRead(DT) != currentStateCLK)
  30.                  {
  31.                           counter = counter + 1;
  32.                     if (counter > 100)
  33.                        {
  34.                          counter = 0;
  35.                        }
  36.                           currentDir ="UP";
  37.                      } else
  38.                       {
  39.                                 counter = counter - 1;
  40.                           if (counter < 0)
  41.                              {
  42.                                 counter = 100;
  43.                              }
  44.                           currentDir ="DOWN";
  45.                           }
  46.                   Serial.print("Direction: ");
  47.                   Serial.print(currentDir);
  48.                   Serial.print(" - Counter: ");
  49.                   Serial.println(counter);
  50.             }
  51.    
  52.   lastStateCLK = currentStateCLK;
  53.   int btnState = digitalRead(SW);
  54.     if (btnState == LOW)
  55.         {
  56.                if (millis() - lastButtonPress > 50)
  57.               {
  58.                        Serial.println("Button pressed!");
  59.                   }
  60.                lastButtonPress = millis();
  61.           }
  62.     delay(1);
  63.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement