Guest User

Untitled

a guest
Feb 2nd, 2022
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
  9.  INSTRUCTIONS
  10.  ====================
  11.  Set BUTTON_PIN to the pin attached to the button.
  12.  Set LED_PIN to the pin attached to a LED.
  13.  
  14.  */
  15.  
  16. // Include the Bounce2 library found here :
  17. // https://github.com/thomasfredericks/Bounce2
  18. #include <Bounce2.h>
  19.  
  20. // INSTANTIATE A Button OBJECT
  21. Bounce2::Button button = Bounce2::Button();
  22.  
  23. // WE WILL attach() THE BUTTON TO THE FOLLOWING PIN IN setup()
  24. int BUTTON_PIN = 2;
  25.  
  26. // DEFINE THE PIN FOR THE LED :
  27. // 1) SOME BOARDS HAVE A DEFAULT LED (LED_BUILTIN)
  28. int LED_PIN = LED_BUILTIN;
  29. // 2) OTHERWISE SET YOUR OWN PIN
  30. //#define LED_PIN 13
  31.  
  32. // SET A VARIABLE TO STORE THE LED STATE
  33. bool ledState = LOW;
  34.  
  35. void setup() {
  36.  
  37.   // BUTTON SETUP
  38.  
  39.   // SELECT ONE OF THE FOLLOWING :
  40.   // 1) IF YOUR BUTTON HAS AN INTERNAL PULL-UP
  41.   //button.attach( BUTTON_PIN ,  INPUT_PULLUP ); // USE INTERNAL PULL-UP
  42.   // 2) IF YOUR BUTTON USES AN EXTERNAL PULL-UP
  43.   button.attach( BUTTON_PIN, INPUT ); // USE EXTERNAL PULL-UP
  44.  
  45.   // DEBOUNCE INTERVAL IN MILLISECONDS
  46.   button.interval(100);
  47.  
  48.   // INDICATE THAT THE LOW STATE CORRESPONDS TO PHYSICALLY PRESSING THE BUTTON
  49.   button.setPressedState(LOW);
  50.  
  51.   // LED SETUP
  52.   pinMode(LED_PIN,OUTPUT);
  53.   digitalWrite(LED_PIN,ledState);
  54.  
  55.   Serial.begin(9600);
  56.  
  57. }
  58.  
  59. void loop() {
  60.   // UPDATE THE BUTTON
  61.   // YOU MUST CALL THIS EVERY LOOP
  62.   button.update();
  63.  
  64.   if ( button.pressed() ) {
  65.  
  66.     Serial.print("Pressed");
  67.     // TOGGLE THE LED STATE :
  68.     ledState = !ledState; // SET ledState TO THE OPPOSITE OF ledState
  69.     digitalWrite(LED_PIN,ledState);
  70.  
  71.   }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment