Button2: Simplifying Button Control on Arduino & ESP Boards
What is the Button2 Library?
Key Features of Button2 Library
-
Support Multiple Button Events: Detects single clicks, double clicks, triple clicks, long presses, and more.
-
Event-Driven Actions: Handle button events with callbacks, improving code readability and efficiency.
-
Debounce Mechanism: Built-in debounce handling ensures reliable input detection, preventing false triggers.
-
Multi-Button Support: Manage multiple buttons without complex coding, ideal for multi-functional interfaces.
-
ESP32 and Arduino Compatibility: Works seamlessly with Arduino IDE, supporting both ESP8266 and ESP32 boards.
Why Use Button2 for Your Project?
User Guide
1. Import the Library
// Initialize M5StickC Plus2 #include "Button2.h"
Button2
class to create a button object and pass the button pin as an argument:// Initialize M5StickC Plus2 #define BUTTON_PIN D3 Button2 button; void setup() { button.begin(BUTTON_PIN); }
3. Set Callback Functions
setXXXHandler()
methods to assign callback functions for different button actions:-
setTapHandler()
: Triggers for any button tap; serves as the basic callback function. -
setClickHandler()
: Triggers on a single click. -
setChangedHandler()
,setPressedHandler()
,setReleasedHandler()
: Detects changes in button state. -
setLongClickDetectedHandler()
: Triggers when the button is held for a specified duration. -
setLongClickHandler()
: Triggers after the button is released following a long press. -
setDoubleClickHandler()
,setTripleClickHandler()
: Detects double and triple clicks.// Initialize M5StickC Plus2 void handleTap(Button2& b) { // Handle Button Click Events } void setup() { // ... button.setTapHandler(handleTap); }
✔ Copied!
4. Call the loop()
Function
loop()
function, call the loop()
function of the button object:// Initialize M5StickC Plus2 void loop() { button.loop(); }
5. Extended Features
-
Customizable parameters like long press duration and double-click timing.
-
Using a timer interrupts calling the
loop()
function, preventing the blocking of the main loop. -
Custom button state detection functions that support various types of buttons, such as capacitive touch buttons and I2C-based buttons.
Example Code
// Initialize M5StickC Plus2 #include Button2 button(2); // Create a button object on GPIO pin 2 void setup() { Serial.begin(9600); // Initialize serial communication // Handle single click button.setClickHandler([](Button2 &btn) { Serial.println("Single click detected!"); }); // Handle long press after release button.setLongClickHandler([](Button2 &btn) { Serial.println("Long press completed!"); }); } void loop() { button.loop(); // Continuously check for button events }
Conclusion: Simplify Button Management with Button2