SerialBasicButton.ino 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <Button.h>
  2. #include <ButtonEventCallback.h>
  3. #include <BasicButton.h>
  4. // Create an instance of BasicButton reading digital pin 5
  5. BasicButton button = BasicButton(5);
  6. void setup(){
  7. // Open up the serial port so that we can write to it
  8. Serial.begin(9600);
  9. // When the button is first pressed, call the function onButtonPressed
  10. button.onPress(onButtonPressed);
  11. // Once the button has been held for 1 second (1000ms) call onButtonHeld. Call it again every 0.5s (500ms) until it is let go
  12. button.onHoldRepeat(1000, 500, onButtonHeld);
  13. // When the button is released, call onButtonReleased
  14. button.onRelease(onButtonReleased);
  15. }
  16. void loop(){
  17. // Check the state of the button
  18. button.update();
  19. }
  20. // btn is a reference to the button that fired the event. That means you can use the same event handler for many buttons
  21. void onButtonPressed(Button& btn){
  22. Serial.println("button pressed");
  23. }
  24. // duration reports back how long it has been since the button was originally pressed.
  25. // repeatCount tells us how many times this function has been called by this button.
  26. void onButtonHeld(Button& btn, uint16_t duration, uint16_t repeatCount){
  27. Serial.print("button has been held for ");
  28. Serial.print(duration);
  29. Serial.print(" ms; this event has been fired ");
  30. Serial.print(repeatCount);
  31. Serial.println(" times");
  32. }
  33. // duration reports back the total time that the button was held down
  34. void onButtonReleased(Button& btn, uint16_t duration){
  35. Serial.print("button released after ");
  36. Serial.print(duration);
  37. Serial.println(" ms");
  38. }