Advertisement
DrAungWinHtut

button_click_options.ino

Jun 29th, 2025
650
-1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const int buttonPin = 2;
  2. bool lastButtonState = false;
  3. unsigned long pressStartTime = 0;
  4. unsigned long lastReleaseTime = 0;
  5.  
  6. bool mode1 = false;
  7. bool mode2 = false;
  8.  
  9. int option1 = 0;
  10. int option2 = 0;
  11.  
  12. const unsigned long longPressThreshold = 3000;        // 3 seconds to enter Mode 1
  13. const unsigned long veryLongPressThreshold = 5000;    // 5 seconds to exit Mode 1
  14. const unsigned long doubleClickThreshold = 300;       // ms between double clicks
  15.  
  16. void setup() {
  17.   pinMode(buttonPin, INPUT);
  18.   Serial.begin(9600);
  19. }
  20.  
  21. void loop() {
  22.   bool reading = digitalRead(buttonPin);
  23.  
  24.   if (reading != lastButtonState) {
  25.     if (reading == HIGH) {
  26.       pressStartTime = millis();
  27.  
  28.       // Check for double click
  29.       if ((millis() - lastReleaseTime) < doubleClickThreshold) {
  30.         if (!mode1 && !mode2) {
  31.           mode2 = true;
  32.           Serial.println("Entered Mode 2");
  33.         } else if (mode2) {
  34.           mode2 = false;
  35.           Serial.println("Exited Mode 2");
  36.         }
  37.       }
  38.  
  39.     } else {
  40.       // Button released
  41.       unsigned long pressDuration = millis() - pressStartTime;
  42.  
  43.       Serial.print("Press duration: ");
  44.       Serial.println(pressDuration);
  45.  
  46.       // Exiting Mode 1
  47.       if (mode1 && pressDuration >= veryLongPressThreshold) {
  48.         mode1 = false;
  49.         Serial.println("Exited Mode 1 (via long press)");
  50.       }
  51.       // Entering Mode 1
  52.       else if (!mode1 && !mode2 && pressDuration >= longPressThreshold) {
  53.         mode1 = true;
  54.         Serial.println("Entered Mode 1");
  55.       }
  56.       // Normal click in Mode 1
  57.       else if (mode1 && pressDuration < longPressThreshold) {
  58.         option1 = (option1 + 1) % 5;
  59.         Serial.print("Mode 1 Option: ");
  60.         Serial.println(option1 + 1);
  61.       }
  62.       // Normal click in Mode 2
  63.       else if (mode2 && pressDuration < longPressThreshold) {
  64.         option2 = (option2 + 1) % 5;
  65.         Serial.print("Mode 2 Option: ");
  66.         Serial.println(option2 + 1);
  67.       }
  68.  
  69.       lastReleaseTime = millis();
  70.     }
  71.  
  72.     lastButtonState = reading;
  73.   }
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement