{"id":13490430,"url":"https://github.com/LennartHennigs/Button2","last_synced_at":"2025-03-28T06:31:17.337Z","repository":{"id":26504278,"uuid":"109268441","full_name":"LennartHennigs/Button2","owner":"LennartHennigs","description":"Arduino/ESP button library that provides callback functions to track single, double, triple and long clicks. It also takes care of debouncing.","archived":false,"fork":false,"pushed_at":"2025-01-26T20:41:05.000Z","size":156,"stargazers_count":514,"open_issues_count":8,"forks_count":82,"subscribers_count":12,"default_branch":"master","last_synced_at":"2025-03-25T02:36:42.899Z","etag":null,"topics":["arduino","arduino-library","button","c-plus-plus","embedded","esp32","esp8266","hardware","mbed","touch"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/LennartHennigs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"ko_fi":"lennart0815"}},"created_at":"2017-11-02T13:28:37.000Z","updated_at":"2025-03-21T14:10:58.000Z","dependencies_parsed_at":"2024-01-02T17:25:22.362Z","dependency_job_id":"55b0217e-9810-49f8-bb2c-23c4c8dc28ea","html_url":"https://github.com/LennartHennigs/Button2","commit_stats":null,"previous_names":[],"tags_count":32,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LennartHennigs%2FButton2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LennartHennigs%2FButton2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LennartHennigs%2FButton2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LennartHennigs%2FButton2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/LennartHennigs","download_url":"https://codeload.github.com/LennartHennigs/Button2/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245984431,"owners_count":20704791,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arduino","arduino-library","button","c-plus-plus","embedded","esp32","esp8266","hardware","mbed","touch"],"created_at":"2024-07-31T19:00:46.570Z","updated_at":"2025-03-28T06:31:17.329Z","avatar_url":"https://github.com/LennartHennigs.png","language":"C++","funding_links":["https://ko-fi.com/lennart0815"],"categories":["C++"],"sub_categories":[],"readme":"# Button2\n\nArduino/ESP library to simplify working with buttons.\n\n- Author: Lennart Hennigs (\u003chttps://www.lennarthennigs.de\u003e)\n- Copyright (C) 2017-2025 Lennart Hennigs.\n- Released under the MIT license.\n\n## Description\n\nThis library allows you to use callback functions to track single, double, triple and long clicks. Alternatively, it provides function to use in your main `loop()`.\nThe library also takes care of debouncing. Using this lib will reduce and simplify your source code significantly.\n\nIt has been tested with Arduino, ESP8266 and ESP32 devices.\n\nTo see the latest changes to the library please take a look at the [Changelog](https://github.com/LennartHennigs/Button2/blob/master/CHANGELOG.md).\n\nIf you find this library helpful please consider giving it a ⭐️ at [GitHub](https://github.com/LennartHennigs/Button2) and/or [buy me a ☕️](https://ko-fi.com/lennart0815).\n\nThank you!\n\n## How To Use\n\nThis library allows you to define a button and uses callback functions to detect different types of button interactions.\nIf you don't want to use callback there are also functions available for using it in your code's main `loop()`.\n\n### Definition\n\n- Include the library on top\n\n```c++\n #include \"Button2.h\"\n```\n\n- Define the button either using the `constructor` or the `begin()` function.\n\n```c++\n  void begin(byte attachTo, byte buttonMode = INPUT_PULLUP, boolean activeLow  = true);\n```\n\n### Button Types\n\n- You can use the class for \"real\" buttons (*pullup*, *pulldown*, and *active low*).\n- Per default the button pins are defined as `INPUT_PULLUP`. You can override this upon creation.\n\n```c++\n   #include \"Button2.h\"\n   #define BUTTON_PIN D3\n\n   Button2 button;\n\n   void setup() {\n     button.begin(BUTTON_PIN);\n  }\n```\n\n- You can also the library with other types of buttons, e.g. capacitive touch or ones handled via I2C. See the section on defining custom handlers below.\n\n### Callback Handler\n\n- Instead of frequently checking the button state in your main `loop()` this class allows you to assign callback functions.\n- You can define callback functions to track various types of clicks:\n  - `setTapHandler()` will be be called when any click occurs. This is the most basic handler. It ignores all timings built-in the library for double or triple click detection.\n  - `setClickHandler()` will be triggered after a single click occurred.\n  - `setChangedHandler()`, `setPressedHandler()` and `setReleasedHandler()` allow to detect basic interactions.\n  - `setLongClickDetectedHandler()` will be triggered as soon as the long click timeout has passed.\n  - `setLongClickHandler()` will be triggered after the button has released.\n  - `setDoubleClickHandler()` and `setTripleClickHandler()` detect complex interactions.\n\n- **Note:** You will experience a short delay with `setClickHandler()` and `setLongClickHandler()` as need to check whether a long or multi-click is in progress. For immediate feedback use `setTapHandler()`or `setLongClickDetectedHandler()`\n\n- You can assign callback functions for single or for multiple buttons.\n- You can track individual or multiple events with a single handler.\n- Please take a look at the included examples (see below) to get an overview over the different callback handlers and their usage.\n- All callback functions need a `Button2` reference parameter. There the reference to the triggered button is stored. This can used to call status functions, e.g. `wasPressedFor()`.\n\n### Longpress Handling\n\n- There are two possible callback functions: `setLongClickDetectedHandler()` and `setLongClickHandler()`.\n- `setLongClickDetectedHandler()` will be called as soon as the defined timeout has passed.\n- `setLongClickHandler()` will only be called after the button has been released.\n- `setLongClickDetectedRetriggerable(bool retriggerable)` allows you to define whether want to get multiple notifications for a **single** long click depending on the timeout.\n- `getLongClickCount()` gets you the number of long clicks – this is useful when `retriggerable` is set.\n\n### The Loop\n\n- For the class to work, you need to call the button's `loop()` member function in your sketch's `loop()` function.\n\n```c++\n   #include \"Button2.h\"\n   #define BUTTON_PIN D3\n\n   Button2 button;\n\n   void handleTap(Button2\u0026 b) {\n    // check for really long clicks\n    if (b.wasPressedFor() \u003e 1000) {\n    // do something\n    }\n   }\n\n   void setup() {\n     button.begin(BUTTON_PIN);\n     button.setTapHandler(handleTap);\n  }\n\n  void loop() {\n     button.loop();\n  }\n```\n\n- As the `loop()`function needs to be called continuously, `delay()` and other blocking functions will interfere with the detection of clicks. Consider cleaning up your loop or call the `loop()` function via an interrupt.\n- Please see the *examples* below for more details.\n\n### Using an timer interrupt instead\n\n- Alternatively, you can call the button's `loop()` function via a timer interrupt.\n- I haven't tried this extensively, USE THIS AT YOUR OWN RISK!\n- You need make sure that the interval is quick enough that it can detect your timeouts (see below).\n- There is an example for the ESP32 [ESP32TimerInterrupt.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/ESP32TimerInterrupt/ESP32TimerInterrupt.ino) that I tested.\n\n### Timeouts\n\n- The default timeouts for events are (in ms):\n\n```c++\n  #define BTN_DEBOUNCE_MS 50\n  #define BTN_LONGCLICK_MS 200\n  #define BTN_DOUBLECLICK_MS 300\n```\n\n- You can define your own timeouts by using these setter functions:\n  - `void setDebounceTime(unsigned int ms)`\n  - `void setLongClickTime(unsigned int ms)`\n  - `void setDoubleClickTime(unsigned int ms)`\n- There are also getter functions available, if needed.\n  \n### Using Button2 in the main `loop()`\n\n- Even though I suggest to use handlers for tracking events, you can also use Button2 to check button's state in the main loop\n- `bool wasPressed()` allows you to check whether the button was pressed\n- `clickType read(bool keepState = false)` gives you the type of click that took place\n- `clickType wait(bool keepState = false)` combines `read()` and `wasPressed()` and halts execution until a button click was detected. Thus, it is blocking code.\n- The `clickType` is an enum defined as...\n\n```c++\n    enum clickType {\n      single_click, \n      double_click, \n      triple_click, \n      long_click,\n      empty\n    };\n```\n\n- There are also dedicated waits (`waitForClick()`, `waitForDouble()`, `waitForTriple()` and `waitForLong()`) to detect a specific type\n- The `read()` and the *wait* functions will reset the state of `wasPressed()` unless specified otherwise (via a `bool` parameter)\n- `resetPressedState()` allows you to clear value returned by `wasPressed()` – it is similar to passing `keepState = false` for `read()` or `wait()`.\n- Check out the [ButtonLoop.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/ButtonLoop/ButtonLoop.ino) example to see it in action\n\n### Status Functions\n\n- There are several status functions available to check the status of a button:\n\n``` c++\nunsigned int wasPressedFor() const;\nbyte getNumberOfClicks() const;\nbyte getType() const;\nboolean isPressed() const;\nboolean isPressedRaw() const;\nbool wasPressed() const;\n```\n\n### IDs for Button Instances\n\n- Each button instance gets a unique (auto incremented) ID upon creation.\n- You can get a buttons' ID via `getID()`.\n- Alternatively, you can use `setID(int newID)` to set a new one. But then you need to make sure that they are unique.\n\n### Creating A Custom Button State Handler\n\n- Out of the box *Button2* supports regular hardware buttons.\n- If you want to add other button types you need to define your own function that tracks the state of the button.\n- Use `setButtonStateFunction()` to assign it to your *Button2* instance\n- Make the button pin 'VIRTUAL', i.e. by calling  `button.begin(VIRTUAL_PIN);`\n- And don't forget to initialize the button as this cannot be handled by *Button2*\n- See [ESP32CapacitiveTouch.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/ESP32CapacitiveTouch/ESP32CapacitiveTouch.ino), [M5StackCore2CustomHandler.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/M5StackCore2CustomHandler/M5StackCore2CustomHandler.ino), and [CustomButtonStateHandler.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/CustomButtonStateHandler/CustomButtonStateHandler.ino) as examples.\n\n## Examples\n\n- [SingleButtonSimple.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/SingleButtonSimple/SingleButtonSimple.ino) – the most basic example, shows how to assign event handlers\n- [LongpressHandler.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/LongpressHandler/LongpressHandler.ino) – shows how determine the time of a button press\n- [SingleButton.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/SingleButton/SingleButton.ino) – shows the different event handlers\n- [MultipleButtons.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/MultipleButtons/MultipleButtons.ino) – how to use two buttons\n- [MultiHandler.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/MultiHandler/MultiHandler.ino) – how to use a single handler for multiple events\n- [MultiHandlerTwoButtons.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/MultiHandlerTwoButtons/MultiHandlerTwoButtons.ino) – a single handler for multiple buttons\n- [TrackDualButtonClick.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/TrackDualButtonClick/TrackDualButtonClick.ino) – how to detect when two buttons are clicked at the same time\n- [CustomButtonStateHandler.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/CustomButtonStateHandler/CustomButtonStateHandler.ino) - how to assign your own button handler\n- [ESP32CapacitiveTouch.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/ESP32CapacitiveTouch/ESP32CapacitiveTouch.ino) – how to access the ESP32s capacitive touch handlers\n- [M5StackCore2CustomHandler.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/M5StackCore2CustomHandler/M5StackCore2CustomHandler.ino) - example for the M5Stack Core2 touch buttons\n- [ESP32TimerInterrupt.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/ESP32TimerInterrupt/ESP32TimerInterrupt.ino) - how to use a timer interrupt with the library.\n- [ButtonLoop.ino](https://github.com/LennartHennigs/Button2/blob/master/examples/ButtonLoop/ButtonLoop.ino) – how to use the button class in the main loop (I recommend using handlers, but well...)\n\n## Class Definition\n\nThe button class offers a few additional functions, please take a look at the *Class Definition* below.\n\nSee below the constructors and member functions the library provides:\n\n```c++\nButton2();\nButton2(byte attachTo, byte buttonMode = INPUT_PULLUP, boolean activeLow = true);\n\nvoid begin(byte attachTo, byte buttonMode = INPUT_PULLUP, boolean activeLow  = true);\n\nvoid setDebounceTime(unsigned int ms);\nvoid setLongClickTime(unsigned int ms);\nvoid setDoubleClickTime(unsigned int ms);\n\nunsigned int getDebounceTime();\nunsigned int getLongClickTime();\nunsigned int getDoubleClickTime();\nbyte getPin();\n\nvoid reset();\n\nvoid setButtonStateFunction(StateCallbackFunction f);\n\nvoid setChangedHandler(CallbackFunction f);\nvoid setPressedHandler(CallbackFunction f);\nvoid setReleasedHandler(CallbackFunction f);\n\nvoid setTapHandler(CallbackFunction f);\nvoid setClickHandler(CallbackFunction f);\nvoid setDoubleClickHandler(CallbackFunction f);\nvoid setTripleClickHandler(CallbackFunction f);\n\nvoid setLongClickHandler(CallbackFunction f);\nvoid setLongClickDetectedHandler(CallbackFunction f);\nvoid setLongClickDetectedRetriggerable(bool retriggerable);\nvoid byte getLongClickCount() const;\n\nunsigned int wasPressedFor() const;\nvoid resetPressedState();\nbyte resetClickCount();\n\nboolean isPressed() const;\nboolean isPressedRaw() const;\n\nbool wasPressed() const;\nclickType read(bool keepState = false);\nclickType wait(bool keepState = false);\nvoid waitForClick(bool keepState = false);\nvoid waitForDouble(bool keepState = false);\nvoid waitForTriple(bool keepState = false);\nvoid waitForLong(bool keepState = false);\n\nbyte getNumberOfClicks() const;\nbyte getType() const;\nString clickToString(clickType type) const;\n\nint getID() const;\nvoid setID(int newID);\n\nbool operator == (Button2 \u0026rhs);\n\nvoid loop();\n```\n\n## Installation\n\nOpen the Arduino IDE choose \"Sketch \u003e Include Library\" and search for \"Button2\".\nOr download the ZIP archive (\u003chttps://github.com/lennarthennigs/Button2/zipball/master\u003e), and choose \"Sketch \u003e Include Library \u003e Add .ZIP Library...\" and select the downloaded file.\n\n## License\n\nMIT License\n\nCopyright (c) 2017-2025 Lennart Hennigs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FLennartHennigs%2FButton2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FLennartHennigs%2FButton2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FLennartHennigs%2FButton2/lists"}