SimpleBasicButton.ino 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * BasicButton example. This shows a very basic example of how to register events with a button.
  3. *
  4. * I don't recommend anybody actually use the BasicButton class as it doesn't provide any debouncing facilities or the
  5. * ability to enable internal pullups. It is just to give a very simple demonstration with no additional dependencies.
  6. * For a better option use the PushButton library from the Libraries menu
  7. */
  8. #include <Button.h>
  9. #include <ButtonEventCallback.h>
  10. #include <BasicButton.h>
  11. // Create an instance of BasicButton reading digital pin 5
  12. BasicButton button = BasicButton(5);
  13. void setup(){
  14. // Open up the serial port so that we can write to it
  15. Serial.begin(9600);
  16. // When the button is first pressed, call the function onButtonPressed (further down the page)
  17. button.onPress(onButtonPressed);
  18. // Once the button has been held for 1 second (1000ms) call onButtonHeld. Call it again every 0.5s (500ms) until it is let go
  19. button.onHoldRepeat(1000, 500, onButtonHeld);
  20. // When the button is released, call onButtonReleased
  21. button.onRelease(onButtonReleased);
  22. }
  23. void loop(){
  24. // Check the state of the button
  25. button.update();
  26. }
  27. // btn is a reference to the button that fired the event. That means you can use the same event handler for many buttons
  28. void onButtonPressed(Button& btn){
  29. Serial.println("button pressed");
  30. }
  31. // duration reports back how long it has been since the button was originally pressed.
  32. // repeatCount tells us how many times this function has been called by this button.
  33. void onButtonHeld(Button& btn, uint16_t duration, uint16_t repeatCount){
  34. Serial.print("button has been held for ");
  35. Serial.print(duration);
  36. Serial.print(" ms; this event has been fired ");
  37. Serial.print(repeatCount);
  38. Serial.println(" times");
  39. }
  40. // duration reports back the total time that the button was held down
  41. void onButtonReleased(Button& btn, uint16_t duration){
  42. Serial.print("button released after ");
  43. Serial.print(duration);
  44. Serial.println(" ms");
  45. }