bounce_basic.ino 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. DESCRIPTION
  3. ====================
  4. Simple example of the Bounce library that switches a LED when
  5. a state change (from HIGH to LOW) is triggered (for example when a button is pressed).
  6. Set BOUNCE_PIN to the pin attached to the input (a button for example).
  7. Set LED_PIN to the pin attached to a LED.
  8. */
  9. // WE WILL attach() THE Bounce INSTANCE TO THE FOLLOWING PIN IN setup()
  10. #define BOUNCE_PIN 2
  11. // DEFINE THE PIN FOR THE LED :
  12. // 1) SOME BOARDS HAVE A DEFAULT LED (LED_BUILTIN)
  13. #define LED_PIN LED_BUILTIN
  14. // 2) OTHERWISE SET YOUR OWN PIN
  15. // #define LED_PIN 13
  16. // Include the Bounce2 library found here :
  17. // https://github.com/thomasfredericks/Bounce2
  18. #include <Bounce2.h>
  19. // INSTANTIATE A Bounce OBJECT
  20. Bounce bounce = Bounce();
  21. // SET A VARIABLE TO STORE THE LED STATE
  22. int ledState = LOW;
  23. void setup() {
  24. // BOUNCE SETUP
  25. // SELECT ONE OF THE FOLLOWING :
  26. // 1) IF YOUR INPUT HAS AN INTERNAL PULL-UP
  27. bounce.attach( BOUNCE_PIN , INPUT_PULLUP ); // USE INTERNAL PULL-UP
  28. // 2) IF YOUR INPUT USES AN EXTERNAL PULL-UP
  29. //bounce.attach( BOUNCE_PIN, INPUT ); // USE EXTERNAL PULL-UP
  30. // DEBOUNCE INTERVAL IN MILLISECONDS
  31. bounce.interval(5); // interval in ms
  32. // LED SETUP
  33. pinMode(LED_PIN, OUTPUT);
  34. digitalWrite(LED_PIN, ledState);
  35. }
  36. void loop() {
  37. // Update the Bounce instance (YOU MUST DO THIS EVERY LOOP)
  38. bounce.update();
  39. // <Bounce>.changed() RETURNS true IF THE STATE CHANGED (FROM HIGH TO LOW OR LOW TO HIGH)
  40. if ( bounce.changed() ) {
  41. // THE STATE OF THE INPUT CHANGED
  42. // GET THE STATE
  43. int deboucedInput = bounce.read();
  44. // IF THE CHANGED VALUE IS LOW
  45. if ( deboucedInput == LOW ) {
  46. ledState = !ledState; // SET ledState TO THE OPPOSITE OF ledState
  47. digitalWrite(LED_PIN,ledState); // WRITE THE NEW ledState
  48. }
  49. }
  50. }