retrigger.ino 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. DESCRIPTION
  3. ====================
  4. Example of the bounce library that shows how to retrigger an event when a button is held down.
  5. In this case, the debug LED will blink every 500 ms as long as the button is held down.
  6. Open the Serial Monitor (57600 baud) for debug messages.
  7. */
  8. // Include the Bounce2 library found here :
  9. // https://github.com/thomasfredericks/Bounce2
  10. #include <Bounce2.h>
  11. #define BUTTON_PIN 2
  12. #define LED_PIN 13
  13. // Instantiate a Bounce object
  14. Bounce debouncer = Bounce();
  15. int buttonState;
  16. unsigned long buttonPressTimeStamp;
  17. int ledState;
  18. void setup() {
  19. Serial.begin(57600);
  20. // Setup the button
  21. pinMode(BUTTON_PIN,INPUT);
  22. // Activate internal pull-up
  23. digitalWrite(BUTTON_PIN,HIGH);
  24. // After setting up the button, setup debouncer
  25. debouncer.attach(BUTTON_PIN);
  26. debouncer.interval(5);
  27. //Setup the LED
  28. pinMode(LED_PIN,OUTPUT);
  29. digitalWrite(LED_PIN,ledState);
  30. }
  31. void loop() {
  32. // Update the debouncer and get the changed state
  33. boolean changed = debouncer.update();
  34. if ( changed ) {
  35. // Get the update value
  36. int value = debouncer.read();
  37. if ( value == HIGH) {
  38. ledState = LOW;
  39. digitalWrite(LED_PIN, ledState );
  40. buttonState = 0;
  41. Serial.println("Button released (state 0)");
  42. } else {
  43. ledState = HIGH;
  44. digitalWrite(LED_PIN, ledState );
  45. buttonState = 1;
  46. Serial.println("Button pressed (state 1)");
  47. buttonPressTimeStamp = millis();
  48. }
  49. }
  50. if ( buttonState == 1 ) {
  51. if ( millis() - buttonPressTimeStamp >= 500 ) {
  52. buttonPressTimeStamp = millis();
  53. if ( ledState == HIGH ) ledState = LOW;
  54. else if ( ledState == LOW ) ledState = HIGH;
  55. digitalWrite(LED_PIN, ledState );
  56. Serial.println("Retriggering button");
  57. }
  58. }
  59. }