bounce_multiple.ino 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Detect the falling edge of multiple buttons.
  2. // Eight buttons with internal pullups.
  3. // Toggles a LED when any button is pressed.
  4. // Buttons on pins 2,3,4,5,6,7,8,9
  5. // Include the Bounce2 library found here :
  6. // https://github.com/thomasfredericks/Bounce2
  7. #include <Bounce2.h>
  8. #define LED_PIN 13
  9. #define NUM_BUTTONS 8
  10. const uint8_t BUTTON_PINS[NUM_BUTTONS] = {2, 3, 4, 5, 6, 7, 8, 9};
  11. int ledState = LOW;
  12. Bounce * buttons = new Bounce[NUM_BUTTONS];
  13. void setup() {
  14. for (int i = 0; i < NUM_BUTTONS; i++) {
  15. buttons[i].attach( BUTTON_PINS[i] , INPUT_PULLUP ); //setup the bounce instance for the current button
  16. buttons[i].interval(25); // interval in ms
  17. }
  18. // Setup the LED :
  19. pinMode(LED_PIN, OUTPUT);
  20. digitalWrite(LED_PIN, ledState);
  21. }
  22. void loop() {
  23. bool needToToggleLed = false;
  24. for (int i = 0; i < NUM_BUTTONS; i++) {
  25. // Update the Bounce instance :
  26. buttons[i].update();
  27. // If it fell, flag the need to toggle the LED
  28. if ( buttons[i].fell() ) {
  29. needToToggleLed = true;
  30. }
  31. }
  32. // if a LED toggle has been flagged :
  33. if ( needToToggleLed ) {
  34. // Toggle LED state :
  35. ledState = !ledState;
  36. digitalWrite(LED_PIN, ledState);
  37. }
  38. }