bounce_button.ino 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. DESCRIPTION
  3. ====================
  4. This is an example of the Bounce2::Button class.
  5. When the user presses a physical button, it toggles a LED on or off.
  6. The Button class matches an electrical state to a physical action.
  7. Use .setPressedState(LOW or HIGH) to set the detection state for when the button is pressed.
  8. INSCRUCTIONS
  9. ====================
  10. Set BUTTON_PIN to the pin attached to the button.
  11. Set LED_PIN to the pin attached to a LED.
  12. */
  13. // WE WILL attach() THE BUTTON TO THE FOLLOWING PIN IN setup()
  14. #define BUTTON_PIN 2
  15. // DEFINE THE PIN FOR THE LED :
  16. // 1) SOME BOARDS HAVE A DEFAULT LED (LED_BUILTIN)
  17. //#define LED_PIN LED_BUILTIN
  18. // 2) OTHERWISE SET YOUR OWN PIN
  19. #define LED_PIN 13
  20. // Include the Bounce2 library found here :
  21. // https://github.com/thomasfredericks/Bounce2
  22. #include <Bounce2.h>
  23. // INSTANTIATE A Button OBJECT FROM THE Bounce2 NAMESPACE
  24. Bounce2::Button button = Bounce2::Button();
  25. // SET A VARIABLE TO STORE THE LED STATE
  26. int ledState = LOW;
  27. void setup() {
  28. // BUTTON SETUP
  29. // SELECT ONE OF THE FOLLOWING :
  30. // 1) IF YOUR BUTTON HAS AN INTERNAL PULL-UP
  31. // button.attach( BUTTON_PIN , INPUT_PULLUP ); // USE INTERNAL PULL-UP
  32. // 2) IF YOUR BUTTON USES AN EXTERNAL PULL-UP
  33. button.attach( BUTTON_PIN, INPUT ); // USE EXTERNAL PULL-UP
  34. // DEBOUNCE INTERVAL IN MILLISECONDS
  35. button.interval(5);
  36. // INDICATE THAT THE LOW STATE CORRESPONDS TO PHYSICALLY PRESSING THE BUTTON
  37. button.setPressedState(LOW);
  38. // LED SETUP
  39. pinMode(LED_PIN,OUTPUT);
  40. digitalWrite(LED_PIN,ledState);
  41. }
  42. void loop() {
  43. // UPDATE THE BUTTON
  44. // YOU MUST CALL THIS EVERY LOOP
  45. button.update();
  46. // <Button>.pressed() RETURNS true IF THE STATE CHANGED
  47. // AND THE CURRENT STATE MATCHES <Button>.setPressedState(<HIGH or LOW>);
  48. // WHICH IS LOW IN THIS EXAMPLE AS SET WITH button.setPressedState(LOW); IN setup()
  49. if ( button.pressed() ) {
  50. // TOGGLE THE LED STATE :
  51. ledState = !ledState; // SET ledState TO THE OPPOSITE OF ledState
  52. digitalWrite(LED_PIN,ledState); // WRITE THE NEW ledState
  53. }
  54. }