BasicPushButton.ino 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * PushButton example. This shows a basic example of how to register events with a button.
  3. */
  4. #include <Button.h>
  5. #include <ButtonEventCallback.h>
  6. #include <PushButton.h>
  7. #include <Bounce2.h> // https://github.com/thomasfredericks/Bounce-Arduino-Wiring
  8. // Create an instance of PushButton reading digital pin 5
  9. PushButton button = PushButton(5);
  10. void setup(){
  11. // Open up the serial port so that we can write to it
  12. Serial.begin(9600);
  13. // Configure the button as you'd like - not necessary if you're happy with the defaults
  14. button.configureButton(configurePushButton);
  15. // When the button is first pressed, call the function onButtonPressed (further down the page)
  16. button.onPress(onButtonPressed);
  17. // Once the button has been held for 1 second (1000ms) call onButtonHeld. Call it again every 0.5s (500ms) until it is let go
  18. button.onHoldRepeat(1000, 500, onButtonHeld);
  19. // When the button is released, call onButtonReleased
  20. button.onRelease(onButtonReleased);
  21. }
  22. void loop(){
  23. // Check the state of the button
  24. button.update();
  25. }
  26. // Use this function to configure the internal Bounce object to suit you. See the documentation at: https://github.com/thomasfredericks/Bounce2/wiki
  27. // This function can be left out if the defaults are acceptable - just don't call configureButton
  28. void configurePushButton(Bounce& bouncedButton){
  29. // Set the debounce interval to 15ms - default is 10ms
  30. bouncedButton.interval(15);
  31. }
  32. // btn is a reference to the button that fired the event. That means you can use the same event handler for many buttons
  33. void onButtonPressed(Button& btn){
  34. Serial.println("button pressed");
  35. }
  36. // duration reports back how long it has been since the button was originally pressed.
  37. // repeatCount tells us how many times this function has been called by this button.
  38. void onButtonHeld(Button& btn, uint16_t duration, uint16_t repeatCount){
  39. Serial.print("button has been held for ");
  40. Serial.print(duration);
  41. Serial.print(" ms; this event has been fired ");
  42. Serial.print(repeatCount);
  43. Serial.println(" times");
  44. }
  45. // duration reports back the total time that the button was held down
  46. void onButtonReleased(Button& btn, uint16_t duration){
  47. Serial.print("button released after ");
  48. Serial.print(duration);
  49. Serial.println(" ms");
  50. }