Button.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #pragma once
  2. #include <Arduino.h>
  3. #include <functional>
  4. // Button timing configuration
  5. #define BUTTON_DEBOUNCE_TIME_MS 50 // Debounce time in ms
  6. #define BUTTON_CLICK_TIMEOUT_MS 500 // Max time between clicks for multi-click
  7. #define BUTTON_LONG_PRESS_TIME_MS 3000 // Time to trigger long press (3 seconds)
  8. #define BUTTON_READ_INTERVAL_MS 10 // How often to read the button
  9. class Button {
  10. public:
  11. enum EventType {
  12. NONE,
  13. SHORT_PRESS,
  14. DOUBLE_PRESS,
  15. TRIPLE_PRESS,
  16. QUADRUPLE_PRESS,
  17. LONG_PRESS,
  18. ANY_PRESS
  19. };
  20. using EventCallback = std::function<void()>;
  21. Button(uint8_t pin, bool activeState = LOW);
  22. Button(uint8_t pin, bool activeState, bool isAnalog, uint16_t analogThreshold = 20);
  23. void begin();
  24. void update();
  25. // Set callbacks for different events
  26. void onShortPress(EventCallback callback) { _onShortPress = callback; }
  27. void onDoublePress(EventCallback callback) { _onDoublePress = callback; }
  28. void onTriplePress(EventCallback callback) { _onTriplePress = callback; }
  29. void onQuadruplePress(EventCallback callback) { _onQuadruplePress = callback; }
  30. void onLongPress(EventCallback callback) { _onLongPress = callback; }
  31. void onAnyPress(EventCallback callback) { _onAnyPress = callback; }
  32. // State getters
  33. bool isPressed() const { return _currentState; }
  34. EventType getLastEvent() const { return _lastEvent; }
  35. private:
  36. enum State {
  37. IDLE,
  38. PRESSED,
  39. RELEASED,
  40. WAITING_FOR_MULTI_CLICK
  41. };
  42. uint8_t _pin;
  43. bool _activeState;
  44. bool _isAnalog;
  45. uint16_t _analogThreshold;
  46. State _state = IDLE;
  47. bool _currentState;
  48. bool _lastState;
  49. uint32_t _stateChangeTime = 0;
  50. uint32_t _pressTime = 0;
  51. uint32_t _releaseTime = 0;
  52. uint32_t _lastReadTime = 0;
  53. uint8_t _clickCount = 0;
  54. EventType _lastEvent = NONE;
  55. // Callbacks
  56. EventCallback _onShortPress = nullptr;
  57. EventCallback _onDoublePress = nullptr;
  58. EventCallback _onTriplePress = nullptr;
  59. EventCallback _onQuadruplePress = nullptr;
  60. EventCallback _onLongPress = nullptr;
  61. EventCallback _onAnyPress = nullptr;
  62. bool readButton();
  63. void handleStateChange();
  64. void triggerEvent(EventType event);
  65. };