Repository files navigation

MultiButton

A compact and flexible multi-button state machine library for embedded systems.

中文文档 (Chinese)

Features

  • 7 event types: press down, press up, single click, double click, long press start, long press hold, repeat press
  • Hardware debounce: built-in digital filter eliminates contact bounce
  • State machine driven: reliable state transitions with clear logic
  • Unlimited buttons: linked-list architecture supports any number of button instances
  • Callback & polling: flexible event handling via callbacks or polling button_get_event()
  • Memory efficient: compact bitfield struct (~30 bytes per button)
  • Configurable: adjustable timing thresholds and debounce depth
  • Thread-safe option: optional RTOS lock hooks with zero overhead on bare-metal

Quick Start

#include"multi_button.h"staticButtonbtn1;
// 1. Implement GPIO read functionuint8_tread_button_gpio(uint8_tbutton_id)
{
returnHAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
}
// 2. Define event callback (receives user_data)voidon_single_click(Button*btn, void*user_data)
{
// handle single click
}
// 3. Initialize and startvoidsetup(void)
{
button_init(&btn1, read_button_gpio, 0, 1); // active lowbutton_attach(&btn1, BTN_SINGLE_CLICK, on_single_click, NULL);
button_start(&btn1);
}
// 4. Call from 5ms timer interruptvoidtimer_5ms_isr(void)
{
button_ticks();
}

Event Types

EventDescription
BTN_PRESS_DOWNButton pressed down
BTN_PRESS_UPButton released
BTN_PRESS_REPEATRepeated press detected
BTN_SINGLE_CLICKSingle click completed (after timeout)
BTN_DOUBLE_CLICKDouble click completed (after timeout)
BTN_LONG_PRESS_STARTLong press threshold reached (fires once)
BTN_LONG_PRESS_HOLDLong press continuing (fires every tick while held)

State Machine

 +-- long hold --> [LONG_HOLD]
| |
[IDLE] -- press --> [PRESS] release
^ | |
| release |
| v |
| [RELEASE] <---------------------+
| | ^
| timeout| | quick press
| | |
+-------------+ [REPEAT] -- held too long --> [PRESS]

State Transitions Detail

  • IDLE -> PRESS: Button level matches active level after debounce. Fires BTN_PRESS_DOWN.
  • PRESS -> RELEASE: Button released before long press threshold. Fires BTN_PRESS_UP.
  • PRESS -> LONG_HOLD: Button held past LONG_TICKS. Fires BTN_LONG_PRESS_START.
  • RELEASE -> IDLE (timeout): No re-press within SHORT_TICKS. Fires BTN_SINGLE_CLICK or BTN_DOUBLE_CLICK based on repeat count.
  • RELEASE -> REPEAT: Button pressed again within timeout. Fires BTN_PRESS_DOWN + BTN_PRESS_REPEAT.
  • REPEAT -> RELEASE: Quick release. Continues waiting for more presses.
  • REPEAT -> PRESS: Held too long in repeat state. Resets for a new press cycle.
  • LONG_HOLD -> IDLE: Released from long press. Fires BTN_PRESS_UP.
  • LONG_HOLD (holding): Fires BTN_LONG_PRESS_HOLD every tick (see note below).

API Reference

Core Functions

voidbutton_init(Button*handle, uint8_t(*pin_level)(uint8_t),
uint8_tactive_level, uint8_tbutton_id);
voidbutton_attach(Button*handle, ButtonEventevent, BtnCallbackcb, void*user_data);
voidbutton_detach(Button*handle, ButtonEventevent);
intbutton_start(Button*handle); // returns 0=ok, -1=duplicate, -2=invalidvoidbutton_stop(Button*handle);
voidbutton_ticks(void); // call every 5ms from timer

Utility Functions

ButtonEventbutton_get_event(Button*handle); // current event (polling mode)uint8_tbutton_get_repeat_count(Button*handle); // repeat press countintbutton_is_pressed(Button*handle); // 1=pressed, 0=released, -1=errorvoidbutton_reset(Button*handle); // reset to idle state

User Data (Context Pointer)

Every callback receives a void* user_data pointer, set via button_attach():

typedefstruct {
intled_pin;
intbeep_count;
} ButtonContext;
ButtonContextctx= { .led_pin=13, .beep_count=0 };
voidon_click(Button*btn, void*user_data)
{
ButtonContext*ctx= (ButtonContext*)user_data;
toggle_led(ctx->led_pin);
ctx->beep_count++;
}
button_attach(&btn1, BTN_SINGLE_CLICK, on_click, &ctx);

All callbacks for the same button share the same user_data (it is stored per-button, not per-event).

Configuration

Edit the defines in multi_button.h:

#defineTICKS_INTERVAL 5 // timer tick interval (ms)
#defineDEBOUNCE_TICKS 3 // debounce filter depth (max 7)
#defineSHORT_TICKS (300 / TICKS_INTERVAL) // short press threshold
#defineLONG_TICKS (1000 / TICKS_INTERVAL) // long press threshold
#definePRESS_REPEAT_MAX_NUM 15 // max repeat counter

Thread Safety (RTOS)

For RTOS environments, define lock macros before including the header:

#defineMULTIBUTTON_THREAD_SAFE#defineMULTIBUTTON_LOCK() osMutexAcquire(btn_mutex, osWaitForever)
#defineMULTIBUTTON_UNLOCK() osMutexRelease(btn_mutex)
#include"multi_button.h"

On bare-metal (default), the lock macros compile to nothing with zero overhead.

Callbacks are executed outside the lock, so button_stop()/button_start() can be safely called from within callbacks without deadlock risk. A regular (non-recursive) mutex is sufficient.

Implementing Triple Click (N-Click)

The library natively supports single click and double click events. For triple click or higher N-click, use the BTN_PRESS_REPEAT event combined with button_get_repeat_count():

voidon_repeat_done(Button*btn, void*user_data)
{
// This fires when repeat press is detected// Check repeat count after timeout for final count
}
voidon_click_resolve(Button*btn, void*user_data)
{
uint8_tcount=button_get_repeat_count(btn);
if (count==3) {
// Triple click!
}
}
// Register for single click (fires after timeout with final repeat count)button_attach(&btn, BTN_SINGLE_CLICK, on_click_resolve, NULL);
// Or check repeat count in any callbackbutton_attach(&btn, BTN_PRESS_REPEAT, on_repeat_done, NULL);

Note: BTN_SINGLE_CLICK fires when repeat==1 and BTN_DOUBLE_CLICK fires when repeat==2 after the short-press timeout. For repeat>=3, only BTN_PRESS_REPEAT fires during the press sequence. You can read button_get_repeat_count() from any callback to detect N-click patterns.

Important Notes

BTN_LONG_PRESS_HOLD fires every tick

BTN_LONG_PRESS_HOLD fires on every tick (default 5ms = 200Hz) while the button is held after the long press threshold. If your callback does expensive work, add your own throttling:

voidon_long_hold(Button*btn, void*user_data)
{
staticuint16_tthrottle=0;
if (++throttle<20) return; // fire every 100ms insteadthrottle=0;
// ... do work ...
}

Callback execution context

If button_ticks() is called from a timer interrupt (ISR), all callbacks execute in ISR context. Keep callbacks short and avoid blocking operations. For complex handling, set a flag in the callback and process it in the main loop.

If button_ticks() is called from a main loop or RTOS task, callbacks run in that context with no ISR restrictions.

Building

# Make
make all # library + examples
make test# run unit tests
make library # static library only# CMake
cmake -B build -DMULTIBUTTON_BUILD_TESTS=ON -DMULTIBUTTON_BUILD_EXAMPLES=ON
cmake --build build
cd build && ctest

Examples

  • examples/basic_example.c - Single/double click, long press, repeat detection
  • examples/advanced_example.c - Multi-button management, dynamic callback attach/detach
  • examples/poll_example.c - Polling mode without callbacks

FAQ

Q: How do I detect triple click? A: Register a BTN_PRESS_REPEAT callback and check button_get_repeat_count() for the desired count. See the "Implementing Triple Click" section above.

Q: Is it safe to call button_stop() from inside a callback? A: Yes. The library caches the next-pointer before invoking callbacks, so removing a button during iteration is safe.

Q: What happens if the ticks counter overflows during a very long press? A: The ticks counter saturates at UINT16_MAX (65535) instead of wrapping around. At 5ms intervals, this covers ~327 seconds of continuous holding.

Q: Can I use this library in a multi-threaded RTOS? A: Yes. Define MULTIBUTTON_THREAD_SAFE and provide MULTIBUTTON_LOCK()/MULTIBUTTON_UNLOCK() macros. A regular (non-recursive) mutex is sufficient since callbacks execute outside the lock.

Compatibility

  • C99 standard
  • Works on STM32, Arduino, ESP32, and other MCU platforms
  • Supports bare-metal and RTOS environments
  • Minimal memory footprint for resource-constrained systems

License

MIT License - see LICENSE for details.

About

Button driver for embedded system

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

MultiButton

A compact and flexible multi-button state machine library for embedded systems.

中文文档 (Chinese)

Features

  • 7 event types: press down, press up, single click, double click, long press start, long press hold, repeat press
  • Hardware debounce: built-in digital filter eliminates contact bounce
  • State machine driven: reliable state transitions with clear logic
  • Unlimited buttons: linked-list architecture supports any number of button instances
  • Callback & polling: flexible event handling via callbacks or polling button_get_event()
  • Memory efficient: compact bitfield struct (~30 bytes per button)
  • Configurable: adjustable timing thresholds and debounce depth
  • Thread-safe option: optional RTOS lock hooks with zero overhead on bare-metal

Quick Start

#include"multi_button.h"staticButtonbtn1;
// 1. Implement GPIO read functionuint8_tread_button_gpio(uint8_tbutton_id)
{
returnHAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
}
// 2. Define event callback (receives user_data)voidon_single_click(Button*btn, void*user_data)
{
// handle single click
}
// 3. Initialize and startvoidsetup(void)
{
button_init(&btn1, read_button_gpio, 0, 1); // active lowbutton_attach(&btn1, BTN_SINGLE_CLICK, on_single_click, NULL);
button_start(&btn1);
}
// 4. Call from 5ms timer interruptvoidtimer_5ms_isr(void)
{
button_ticks();
}

Event Types

EventDescription
BTN_PRESS_DOWNButton pressed down
BTN_PRESS_UPButton released
BTN_PRESS_REPEATRepeated press detected
BTN_SINGLE_CLICKSingle click completed (after timeout)
BTN_DOUBLE_CLICKDouble click completed (after timeout)
BTN_LONG_PRESS_STARTLong press threshold reached (fires once)
BTN_LONG_PRESS_HOLDLong press continuing (fires every tick while held)

State Machine

 +-- long hold --> [LONG_HOLD]
| |
[IDLE] -- press --> [PRESS] release
^ | |
| release |
| v |
| [RELEASE] <---------------------+
| | ^
| timeout| | quick press
| | |
+-------------+ [REPEAT] -- held too long --> [PRESS]

State Transitions Detail

  • IDLE -> PRESS: Button level matches active level after debounce. Fires BTN_PRESS_DOWN.
  • PRESS -> RELEASE: Button released before long press threshold. Fires BTN_PRESS_UP.
  • PRESS -> LONG_HOLD: Button held past LONG_TICKS. Fires BTN_LONG_PRESS_START.
  • RELEASE -> IDLE (timeout): No re-press within SHORT_TICKS. Fires BTN_SINGLE_CLICK or BTN_DOUBLE_CLICK based on repeat count.
  • RELEASE -> REPEAT: Button pressed again within timeout. Fires BTN_PRESS_DOWN + BTN_PRESS_REPEAT.
  • REPEAT -> RELEASE: Quick release. Continues waiting for more presses.
  • REPEAT -> PRESS: Held too long in repeat state. Resets for a new press cycle.
  • LONG_HOLD -> IDLE: Released from long press. Fires BTN_PRESS_UP.
  • LONG_HOLD (holding): Fires BTN_LONG_PRESS_HOLD every tick (see note below).

API Reference

Core Functions

voidbutton_init(Button*handle, uint8_t(*pin_level)(uint8_t),
uint8_tactive_level, uint8_tbutton_id);
voidbutton_attach(Button*handle, ButtonEventevent, BtnCallbackcb, void*user_data);
voidbutton_detach(Button*handle, ButtonEventevent);
intbutton_start(Button*handle); // returns 0=ok, -1=duplicate, -2=invalidvoidbutton_stop(Button*handle);
voidbutton_ticks(void); // call every 5ms from timer

Utility Functions

ButtonEventbutton_get_event(Button*handle); // current event (polling mode)uint8_tbutton_get_repeat_count(Button*handle); // repeat press countintbutton_is_pressed(Button*handle); // 1=pressed, 0=released, -1=errorvoidbutton_reset(Button*handle); // reset to idle state

User Data (Context Pointer)

Every callback receives a void* user_data pointer, set via button_attach():

typedefstruct {
intled_pin;
intbeep_count;
} ButtonContext;
ButtonContextctx= { .led_pin=13, .beep_count=0 };
voidon_click(Button*btn, void*user_data)
{
ButtonContext*ctx= (ButtonContext*)user_data;
toggle_led(ctx->led_pin);
ctx->beep_count++;
}
button_attach(&btn1, BTN_SINGLE_CLICK, on_click, &ctx);

All callbacks for the same button share the same user_data (it is stored per-button, not per-event).

Configuration

Edit the defines in multi_button.h:

#defineTICKS_INTERVAL 5 // timer tick interval (ms)
#defineDEBOUNCE_TICKS 3 // debounce filter depth (max 7)
#defineSHORT_TICKS (300 / TICKS_INTERVAL) // short press threshold
#defineLONG_TICKS (1000 / TICKS_INTERVAL) // long press threshold
#definePRESS_REPEAT_MAX_NUM 15 // max repeat counter

Thread Safety (RTOS)

For RTOS environments, define lock macros before including the header:

#defineMULTIBUTTON_THREAD_SAFE#defineMULTIBUTTON_LOCK() osMutexAcquire(btn_mutex, osWaitForever)
#defineMULTIBUTTON_UNLOCK() osMutexRelease(btn_mutex)
#include"multi_button.h"

On bare-metal (default), the lock macros compile to nothing with zero overhead.

Callbacks are executed outside the lock, so button_stop()/button_start() can be safely called from within callbacks without deadlock risk. A regular (non-recursive) mutex is sufficient.

Implementing Triple Click (N-Click)

The library natively supports single click and double click events. For triple click or higher N-click, use the BTN_PRESS_REPEAT event combined with button_get_repeat_count():

voidon_repeat_done(Button*btn, void*user_data)
{
// This fires when repeat press is detected// Check repeat count after timeout for final count
}
voidon_click_resolve(Button*btn, void*user_data)
{
uint8_tcount=button_get_repeat_count(btn);
if (count==3) {
// Triple click!
}
}
// Register for single click (fires after timeout with final repeat count)button_attach(&btn, BTN_SINGLE_CLICK, on_click_resolve, NULL);
// Or check repeat count in any callbackbutton_attach(&btn, BTN_PRESS_REPEAT, on_repeat_done, NULL);

Note: BTN_SINGLE_CLICK fires when repeat==1 and BTN_DOUBLE_CLICK fires when repeat==2 after the short-press timeout. For repeat>=3, only BTN_PRESS_REPEAT fires during the press sequence. You can read button_get_repeat_count() from any callback to detect N-click patterns.

Important Notes

BTN_LONG_PRESS_HOLD fires every tick

BTN_LONG_PRESS_HOLD fires on every tick (default 5ms = 200Hz) while the button is held after the long press threshold. If your callback does expensive work, add your own throttling:

voidon_long_hold(Button*btn, void*user_data)
{
staticuint16_tthrottle=0;
if (++throttle<20) return; // fire every 100ms insteadthrottle=0;
// ... do work ...
}

Callback execution context

If button_ticks() is called from a timer interrupt (ISR), all callbacks execute in ISR context. Keep callbacks short and avoid blocking operations. For complex handling, set a flag in the callback and process it in the main loop.

If button_ticks() is called from a main loop or RTOS task, callbacks run in that context with no ISR restrictions.

Building

# Make
make all # library + examples
make test# run unit tests
make library # static library only# CMake
cmake -B build -DMULTIBUTTON_BUILD_TESTS=ON -DMULTIBUTTON_BUILD_EXAMPLES=ON
cmake --build build
cd build && ctest

Examples

  • examples/basic_example.c - Single/double click, long press, repeat detection
  • examples/advanced_example.c - Multi-button management, dynamic callback attach/detach
  • examples/poll_example.c - Polling mode without callbacks

FAQ

Q: How do I detect triple click? A: Register a BTN_PRESS_REPEAT callback and check button_get_repeat_count() for the desired count. See the "Implementing Triple Click" section above.

Q: Is it safe to call button_stop() from inside a callback? A: Yes. The library caches the next-pointer before invoking callbacks, so removing a button during iteration is safe.

Q: What happens if the ticks counter overflows during a very long press? A: The ticks counter saturates at UINT16_MAX (65535) instead of wrapping around. At 5ms intervals, this covers ~327 seconds of continuous holding.

Q: Can I use this library in a multi-threaded RTOS? A: Yes. Define MULTIBUTTON_THREAD_SAFE and provide MULTIBUTTON_LOCK()/MULTIBUTTON_UNLOCK() macros. A regular (non-recursive) mutex is sufficient since callbacks execute outside the lock.

Compatibility

  • C99 standard
  • Works on STM32, Arduino, ESP32, and other MCU platforms
  • Supports bare-metal and RTOS environments
  • Minimal memory footprint for resource-constrained systems

License

MIT License - see LICENSE for details.

About

Button driver for embedded system

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

MultiButton

A compact and flexible multi-button state machine library for embedded systems.

中文文档 (Chinese)

Features

  • 7 event types: press down, press up, single click, double click, long press start, long press hold, repeat press
  • Hardware debounce: built-in digital filter eliminates contact bounce
  • State machine driven: reliable state transitions with clear logic
  • Unlimited buttons: linked-list architecture supports any number of button instances
  • Callback & polling: flexible event handling via callbacks or polling button_get_event()
  • Memory efficient: compact bitfield struct (~30 bytes per button)
  • Configurable: adjustable timing thresholds and debounce depth
  • Thread-safe option: optional RTOS lock hooks with zero overhead on bare-metal

Quick Start

#include"multi_button.h"staticButtonbtn1;
// 1. Implement GPIO read functionuint8_tread_button_gpio(uint8_tbutton_id)
{
returnHAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
}
// 2. Define event callback (receives user_data)voidon_single_click(Button*btn, void*user_data)
{
// handle single click
}
// 3. Initialize and startvoidsetup(void)
{
button_init(&btn1, read_button_gpio, 0, 1); // active lowbutton_attach(&btn1, BTN_SINGLE_CLICK, on_single_click, NULL);
button_start(&btn1);
}
// 4. Call from 5ms timer interruptvoidtimer_5ms_isr(void)
{
button_ticks();
}

Event Types

EventDescription
BTN_PRESS_DOWNButton pressed down
BTN_PRESS_UPButton released
BTN_PRESS_REPEATRepeated press detected
BTN_SINGLE_CLICKSingle click completed (after timeout)
BTN_DOUBLE_CLICKDouble click completed (after timeout)
BTN_LONG_PRESS_STARTLong press threshold reached (fires once)
BTN_LONG_PRESS_HOLDLong press continuing (fires every tick while held)

State Machine

 +-- long hold --> [LONG_HOLD]
| |
[IDLE] -- press --> [PRESS] release
^ | |
| release |
| v |
| [RELEASE] <---------------------+
| | ^
| timeout| | quick press
| | |
+-------------+ [REPEAT] -- held too long --> [PRESS]

State Transitions Detail

  • IDLE -> PRESS: Button level matches active level after debounce. Fires BTN_PRESS_DOWN.
  • PRESS -> RELEASE: Button released before long press threshold. Fires BTN_PRESS_UP.
  • PRESS -> LONG_HOLD: Button held past LONG_TICKS. Fires BTN_LONG_PRESS_START.
  • RELEASE -> IDLE (timeout): No re-press within SHORT_TICKS. Fires BTN_SINGLE_CLICK or BTN_DOUBLE_CLICK based on repeat count.
  • RELEASE -> REPEAT: Button pressed again within timeout. Fires BTN_PRESS_DOWN + BTN_PRESS_REPEAT.
  • REPEAT -> RELEASE: Quick release. Continues waiting for more presses.
  • REPEAT -> PRESS: Held too long in repeat state. Resets for a new press cycle.
  • LONG_HOLD -> IDLE: Released from long press. Fires BTN_PRESS_UP.
  • LONG_HOLD (holding): Fires BTN_LONG_PRESS_HOLD every tick (see note below).

API Reference

Core Functions

voidbutton_init(Button*handle, uint8_t(*pin_level)(uint8_t),
uint8_tactive_level, uint8_tbutton_id);
voidbutton_attach(Button*handle, ButtonEventevent, BtnCallbackcb, void*user_data);
voidbutton_detach(Button*handle, ButtonEventevent);
intbutton_start(Button*handle); // returns 0=ok, -1=duplicate, -2=invalidvoidbutton_stop(Button*handle);
voidbutton_ticks(void); // call every 5ms from timer

Utility Functions

ButtonEventbutton_get_event(Button*handle); // current event (polling mode)uint8_tbutton_get_repeat_count(Button*handle); // repeat press countintbutton_is_pressed(Button*handle); // 1=pressed, 0=released, -1=errorvoidbutton_reset(Button*handle); // reset to idle state

User Data (Context Pointer)

Every callback receives a void* user_data pointer, set via button_attach():

typedefstruct {
intled_pin;
intbeep_count;
} ButtonContext;
ButtonContextctx= { .led_pin=13, .beep_count=0 };
voidon_click(Button*btn, void*user_data)
{
ButtonContext*ctx= (ButtonContext*)user_data;
toggle_led(ctx->led_pin);
ctx->beep_count++;
}
button_attach(&btn1, BTN_SINGLE_CLICK, on_click, &ctx);

All callbacks for the same button share the same user_data (it is stored per-button, not per-event).

Configuration

Edit the defines in multi_button.h:

#defineTICKS_INTERVAL 5 // timer tick interval (ms)
#defineDEBOUNCE_TICKS 3 // debounce filter depth (max 7)
#defineSHORT_TICKS (300 / TICKS_INTERVAL) // short press threshold
#defineLONG_TICKS (1000 / TICKS_INTERVAL) // long press threshold
#definePRESS_REPEAT_MAX_NUM 15 // max repeat counter

Thread Safety (RTOS)

For RTOS environments, define lock macros before including the header:

#defineMULTIBUTTON_THREAD_SAFE#defineMULTIBUTTON_LOCK() osMutexAcquire(btn_mutex, osWaitForever)
#defineMULTIBUTTON_UNLOCK() osMutexRelease(btn_mutex)
#include"multi_button.h"

On bare-metal (default), the lock macros compile to nothing with zero overhead.

Callbacks are executed outside the lock, so button_stop()/button_start() can be safely called from within callbacks without deadlock risk. A regular (non-recursive) mutex is sufficient.

Implementing Triple Click (N-Click)

The library natively supports single click and double click events. For triple click or higher N-click, use the BTN_PRESS_REPEAT event combined with button_get_repeat_count():

voidon_repeat_done(Button*btn, void*user_data)
{
// This fires when repeat press is detected// Check repeat count after timeout for final count
}
voidon_click_resolve(Button*btn, void*user_data)
{
uint8_tcount=button_get_repeat_count(btn);
if (count==3) {
// Triple click!
}
}
// Register for single click (fires after timeout with final repeat count)button_attach(&btn, BTN_SINGLE_CLICK, on_click_resolve, NULL);
// Or check repeat count in any callbackbutton_attach(&btn, BTN_PRESS_REPEAT, on_repeat_done, NULL);

Note: BTN_SINGLE_CLICK fires when repeat==1 and BTN_DOUBLE_CLICK fires when repeat==2 after the short-press timeout. For repeat>=3, only BTN_PRESS_REPEAT fires during the press sequence. You can read button_get_repeat_count() from any callback to detect N-click patterns.

Important Notes

BTN_LONG_PRESS_HOLD fires every tick

BTN_LONG_PRESS_HOLD fires on every tick (default 5ms = 200Hz) while the button is held after the long press threshold. If your callback does expensive work, add your own throttling:

voidon_long_hold(Button*btn, void*user_data)
{
staticuint16_tthrottle=0;
if (++throttle<20) return; // fire every 100ms insteadthrottle=0;
// ... do work ...
}

Callback execution context

If button_ticks() is called from a timer interrupt (ISR), all callbacks execute in ISR context. Keep callbacks short and avoid blocking operations. For complex handling, set a flag in the callback and process it in the main loop.

If button_ticks() is called from a main loop or RTOS task, callbacks run in that context with no ISR restrictions.

Building

# Make
make all # library + examples
make test# run unit tests
make library # static library only# CMake
cmake -B build -DMULTIBUTTON_BUILD_TESTS=ON -DMULTIBUTTON_BUILD_EXAMPLES=ON
cmake --build build
cd build && ctest

Examples

  • examples/basic_example.c - Single/double click, long press, repeat detection
  • examples/advanced_example.c - Multi-button management, dynamic callback attach/detach
  • examples/poll_example.c - Polling mode without callbacks

FAQ

Q: How do I detect triple click? A: Register a BTN_PRESS_REPEAT callback and check button_get_repeat_count() for the desired count. See the "Implementing Triple Click" section above.

Q: Is it safe to call button_stop() from inside a callback? A: Yes. The library caches the next-pointer before invoking callbacks, so removing a button during iteration is safe.

Q: What happens if the ticks counter overflows during a very long press? A: The ticks counter saturates at UINT16_MAX (65535) instead of wrapping around. At 5ms intervals, this covers ~327 seconds of continuous holding.

Q: Can I use this library in a multi-threaded RTOS? A: Yes. Define MULTIBUTTON_THREAD_SAFE and provide MULTIBUTTON_LOCK()/MULTIBUTTON_UNLOCK() macros. A regular (non-recursive) mutex is sufficient since callbacks execute outside the lock.

Compatibility

  • C99 standard
  • Works on STM32, Arduino, ESP32, and other MCU platforms
  • Supports bare-metal and RTOS environments
  • Minimal memory footprint for resource-constrained systems

License

MIT License - see LICENSE for details.

About

Button driver for embedded system

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

MultiButton

A compact and flexible multi-button state machine library for embedded systems.

中文文档 (Chinese)

Features

  • 7 event types: press down, press up, single click, double click, long press start, long press hold, repeat press
  • Hardware debounce: built-in digital filter eliminates contact bounce
  • State machine driven: reliable state transitions with clear logic
  • Unlimited buttons: linked-list architecture supports any number of button instances
  • Callback & polling: flexible event handling via callbacks or polling button_get_event()
  • Memory efficient: compact bitfield struct (~30 bytes per button)
  • Configurable: adjustable timing thresholds and debounce depth
  • Thread-safe option: optional RTOS lock hooks with zero overhead on bare-metal

Quick Start

#include"multi_button.h"staticButtonbtn1;
// 1. Implement GPIO read functionuint8_tread_button_gpio(uint8_tbutton_id)
{
returnHAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
}
// 2. Define event callback (receives user_data)voidon_single_click(Button*btn, void*user_data)
{
// handle single click
}
// 3. Initialize and startvoidsetup(void)
{
button_init(&btn1, read_button_gpio, 0, 1); // active lowbutton_attach(&btn1, BTN_SINGLE_CLICK, on_single_click, NULL);
button_start(&btn1);
}
// 4. Call from 5ms timer interruptvoidtimer_5ms_isr(void)
{
button_ticks();
}

Event Types

EventDescription
BTN_PRESS_DOWNButton pressed down
BTN_PRESS_UPButton released
BTN_PRESS_REPEATRepeated press detected
BTN_SINGLE_CLICKSingle click completed (after timeout)
BTN_DOUBLE_CLICKDouble click completed (after timeout)
BTN_LONG_PRESS_STARTLong press threshold reached (fires once)
BTN_LONG_PRESS_HOLDLong press continuing (fires every tick while held)

State Machine

 +-- long hold --> [LONG_HOLD]
| |
[IDLE] -- press --> [PRESS] release
^ | |
| release |
| v |
| [RELEASE] <---------------------+
| | ^
| timeout| | quick press
| | |
+-------------+ [REPEAT] -- held too long --> [PRESS]

State Transitions Detail

  • IDLE -> PRESS: Button level matches active level after debounce. Fires BTN_PRESS_DOWN.
  • PRESS -> RELEASE: Button released before long press threshold. Fires BTN_PRESS_UP.
  • PRESS -> LONG_HOLD: Button held past LONG_TICKS. Fires BTN_LONG_PRESS_START.
  • RELEASE -> IDLE (timeout): No re-press within SHORT_TICKS. Fires BTN_SINGLE_CLICK or BTN_DOUBLE_CLICK based on repeat count.
  • RELEASE -> REPEAT: Button pressed again within timeout. Fires BTN_PRESS_DOWN + BTN_PRESS_REPEAT.
  • REPEAT -> RELEASE: Quick release. Continues waiting for more presses.
  • REPEAT -> PRESS: Held too long in repeat state. Resets for a new press cycle.
  • LONG_HOLD -> IDLE: Released from long press. Fires BTN_PRESS_UP.
  • LONG_HOLD (holding): Fires BTN_LONG_PRESS_HOLD every tick (see note below).

API Reference

Core Functions

voidbutton_init(Button*handle, uint8_t(*pin_level)(uint8_t),
uint8_tactive_level, uint8_tbutton_id);
voidbutton_attach(Button*handle, ButtonEventevent, BtnCallbackcb, void*user_data);
voidbutton_detach(Button*handle, ButtonEventevent);
intbutton_start(Button*handle); // returns 0=ok, -1=duplicate, -2=invalidvoidbutton_stop(Button*handle);
voidbutton_ticks(void); // call every 5ms from timer

Utility Functions

ButtonEventbutton_get_event(Button*handle); // current event (polling mode)uint8_tbutton_get_repeat_count(Button*handle); // repeat press countintbutton_is_pressed(Button*handle); // 1=pressed, 0=released, -1=errorvoidbutton_reset(Button*handle); // reset to idle state

User Data (Context Pointer)

Every callback receives a void* user_data pointer, set via button_attach():

typedefstruct {
intled_pin;
intbeep_count;
} ButtonContext;
ButtonContextctx= { .led_pin=13, .beep_count=0 };
voidon_click(Button*btn, void*user_data)
{
ButtonContext*ctx= (ButtonContext*)user_data;
toggle_led(ctx->led_pin);
ctx->beep_count++;
}
button_attach(&btn1, BTN_SINGLE_CLICK, on_click, &ctx);

All callbacks for the same button share the same user_data (it is stored per-button, not per-event).

Configuration

Edit the defines in multi_button.h:

#defineTICKS_INTERVAL 5 // timer tick interval (ms)
#defineDEBOUNCE_TICKS 3 // debounce filter depth (max 7)
#defineSHORT_TICKS (300 / TICKS_INTERVAL) // short press threshold
#defineLONG_TICKS (1000 / TICKS_INTERVAL) // long press threshold
#definePRESS_REPEAT_MAX_NUM 15 // max repeat counter

Thread Safety (RTOS)

For RTOS environments, define lock macros before including the header:

#defineMULTIBUTTON_THREAD_SAFE#defineMULTIBUTTON_LOCK() osMutexAcquire(btn_mutex, osWaitForever)
#defineMULTIBUTTON_UNLOCK() osMutexRelease(btn_mutex)
#include"multi_button.h"

On bare-metal (default), the lock macros compile to nothing with zero overhead.

Callbacks are executed outside the lock, so button_stop()/button_start() can be safely called from within callbacks without deadlock risk. A regular (non-recursive) mutex is sufficient.

Implementing Triple Click (N-Click)

The library natively supports single click and double click events. For triple click or higher N-click, use the BTN_PRESS_REPEAT event combined with button_get_repeat_count():

voidon_repeat_done(Button*btn, void*user_data)
{
// This fires when repeat press is detected// Check repeat count after timeout for final count
}
voidon_click_resolve(Button*btn, void*user_data)
{
uint8_tcount=button_get_repeat_count(btn);
if (count==3) {
// Triple click!
}
}
// Register for single click (fires after timeout with final repeat count)button_attach(&btn, BTN_SINGLE_CLICK, on_click_resolve, NULL);
// Or check repeat count in any callbackbutton_attach(&btn, BTN_PRESS_REPEAT, on_repeat_done, NULL);

Note: BTN_SINGLE_CLICK fires when repeat==1 and BTN_DOUBLE_CLICK fires when repeat==2 after the short-press timeout. For repeat>=3, only BTN_PRESS_REPEAT fires during the press sequence. You can read button_get_repeat_count() from any callback to detect N-click patterns.

Important Notes

BTN_LONG_PRESS_HOLD fires every tick

BTN_LONG_PRESS_HOLD fires on every tick (default 5ms = 200Hz) while the button is held after the long press threshold. If your callback does expensive work, add your own throttling:

voidon_long_hold(Button*btn, void*user_data)
{
staticuint16_tthrottle=0;
if (++throttle<20) return; // fire every 100ms insteadthrottle=0;
// ... do work ...
}

Callback execution context

If button_ticks() is called from a timer interrupt (ISR), all callbacks execute in ISR context. Keep callbacks short and avoid blocking operations. For complex handling, set a flag in the callback and process it in the main loop.

If button_ticks() is called from a main loop or RTOS task, callbacks run in that context with no ISR restrictions.

Building

# Make
make all # library + examples
make test# run unit tests
make library # static library only# CMake
cmake -B build -DMULTIBUTTON_BUILD_TESTS=ON -DMULTIBUTTON_BUILD_EXAMPLES=ON
cmake --build build
cd build && ctest

Examples

  • examples/basic_example.c - Single/double click, long press, repeat detection
  • examples/advanced_example.c - Multi-button management, dynamic callback attach/detach
  • examples/poll_example.c - Polling mode without callbacks

FAQ

Q: How do I detect triple click? A: Register a BTN_PRESS_REPEAT callback and check button_get_repeat_count() for the desired count. See the "Implementing Triple Click" section above.

Q: Is it safe to call button_stop() from inside a callback? A: Yes. The library caches the next-pointer before invoking callbacks, so removing a button during iteration is safe.

Q: What happens if the ticks counter overflows during a very long press? A: The ticks counter saturates at UINT16_MAX (65535) instead of wrapping around. At 5ms intervals, this covers ~327 seconds of continuous holding.

Q: Can I use this library in a multi-threaded RTOS? A: Yes. Define MULTIBUTTON_THREAD_SAFE and provide MULTIBUTTON_LOCK()/MULTIBUTTON_UNLOCK() macros. A regular (non-recursive) mutex is sufficient since callbacks execute outside the lock.

Compatibility

  • C99 standard
  • Works on STM32, Arduino, ESP32, and other MCU platforms
  • Supports bare-metal and RTOS environments
  • Minimal memory footprint for resource-constrained systems

License

MIT License - see LICENSE for details.

About

Button driver for embedded system

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

MultiButton

A compact and flexible multi-button state machine library for embedded systems.

中文文档 (Chinese)

Features

  • 7 event types: press down, press up, single click, double click, long press start, long press hold, repeat press
  • Hardware debounce: built-in digital filter eliminates contact bounce
  • State machine driven: reliable state transitions with clear logic
  • Unlimited buttons: linked-list architecture supports any number of button instances
  • Callback & polling: flexible event handling via callbacks or polling button_get_event()
  • Memory efficient: compact bitfield struct (~30 bytes per button)
  • Configurable: adjustable timing thresholds and debounce depth
  • Thread-safe option: optional RTOS lock hooks with zero overhead on bare-metal

Quick Start

#include"multi_button.h"staticButtonbtn1;
// 1. Implement GPIO read functionuint8_tread_button_gpio(uint8_tbutton_id)
{
returnHAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
}
// 2. Define event callback (receives user_data)voidon_single_click(Button*btn, void*user_data)
{
// handle single click
}
// 3. Initialize and startvoidsetup(void)
{
button_init(&btn1, read_button_gpio, 0, 1); // active lowbutton_attach(&btn1, BTN_SINGLE_CLICK, on_single_click, NULL);
button_start(&btn1);
}
// 4. Call from 5ms timer interruptvoidtimer_5ms_isr(void)
{
button_ticks();
}

Event Types

EventDescription
BTN_PRESS_DOWNButton pressed down
BTN_PRESS_UPButton released
BTN_PRESS_REPEATRepeated press detected
BTN_SINGLE_CLICKSingle click completed (after timeout)
BTN_DOUBLE_CLICKDouble click completed (after timeout)
BTN_LONG_PRESS_STARTLong press threshold reached (fires once)
BTN_LONG_PRESS_HOLDLong press continuing (fires every tick while held)

State Machine

 +-- long hold --> [LONG_HOLD]
| |
[IDLE] -- press --> [PRESS] release
^ | |
| release |
| v |
| [RELEASE] <---------------------+
| | ^
| timeout| | quick press
| | |
+-------------+ [REPEAT] -- held too long --> [PRESS]

State Transitions Detail

  • IDLE -> PRESS: Button level matches active level after debounce. Fires BTN_PRESS_DOWN.
  • PRESS -> RELEASE: Button released before long press threshold. Fires BTN_PRESS_UP.
  • PRESS -> LONG_HOLD: Button held past LONG_TICKS. Fires BTN_LONG_PRESS_START.
  • RELEASE -> IDLE (timeout): No re-press within SHORT_TICKS. Fires BTN_SINGLE_CLICK or BTN_DOUBLE_CLICK based on repeat count.
  • RELEASE -> REPEAT: Button pressed again within timeout. Fires BTN_PRESS_DOWN + BTN_PRESS_REPEAT.
  • REPEAT -> RELEASE: Quick release. Continues waiting for more presses.
  • REPEAT -> PRESS: Held too long in repeat state. Resets for a new press cycle.
  • LONG_HOLD -> IDLE: Released from long press. Fires BTN_PRESS_UP.
  • LONG_HOLD (holding): Fires BTN_LONG_PRESS_HOLD every tick (see note below).

API Reference

Core Functions

voidbutton_init(Button*handle, uint8_t(*pin_level)(uint8_t),
uint8_tactive_level, uint8_tbutton_id);
voidbutton_attach(Button*handle, ButtonEventevent, BtnCallbackcb, void*user_data);
voidbutton_detach(Button*handle, ButtonEventevent);
intbutton_start(Button*handle); // returns 0=ok, -1=duplicate, -2=invalidvoidbutton_stop(Button*handle);
voidbutton_ticks(void); // call every 5ms from timer

Utility Functions

ButtonEventbutton_get_event(Button*handle); // current event (polling mode)uint8_tbutton_get_repeat_count(Button*handle); // repeat press countintbutton_is_pressed(Button*handle); // 1=pressed, 0=released, -1=errorvoidbutton_reset(Button*handle); // reset to idle state

User Data (Context Pointer)

Every callback receives a void* user_data pointer, set via button_attach():

typedefstruct {
intled_pin;
intbeep_count;
} ButtonContext;
ButtonContextctx= { .led_pin=13, .beep_count=0 };
voidon_click(Button*btn, void*user_data)
{
ButtonContext*ctx= (ButtonContext*)user_data;
toggle_led(ctx->led_pin);
ctx->beep_count++;
}
button_attach(&btn1, BTN_SINGLE_CLICK, on_click, &ctx);

All callbacks for the same button share the same user_data (it is stored per-button, not per-event).

Configuration

Edit the defines in multi_button.h:

#defineTICKS_INTERVAL 5 // timer tick interval (ms)
#defineDEBOUNCE_TICKS 3 // debounce filter depth (max 7)
#defineSHORT_TICKS (300 / TICKS_INTERVAL) // short press threshold
#defineLONG_TICKS (1000 / TICKS_INTERVAL) // long press threshold
#definePRESS_REPEAT_MAX_NUM 15 // max repeat counter

Thread Safety (RTOS)

For RTOS environments, define lock macros before including the header:

#defineMULTIBUTTON_THREAD_SAFE#defineMULTIBUTTON_LOCK() osMutexAcquire(btn_mutex, osWaitForever)
#defineMULTIBUTTON_UNLOCK() osMutexRelease(btn_mutex)
#include"multi_button.h"

On bare-metal (default), the lock macros compile to nothing with zero overhead.

Callbacks are executed outside the lock, so button_stop()/button_start() can be safely called from within callbacks without deadlock risk. A regular (non-recursive) mutex is sufficient.

Implementing Triple Click (N-Click)

The library natively supports single click and double click events. For triple click or higher N-click, use the BTN_PRESS_REPEAT event combined with button_get_repeat_count():

voidon_repeat_done(Button*btn, void*user_data)
{
// This fires when repeat press is detected// Check repeat count after timeout for final count
}
voidon_click_resolve(Button*btn, void*user_data)
{
uint8_tcount=button_get_repeat_count(btn);
if (count==3) {
// Triple click!
}
}
// Register for single click (fires after timeout with final repeat count)button_attach(&btn, BTN_SINGLE_CLICK, on_click_resolve, NULL);
// Or check repeat count in any callbackbutton_attach(&btn, BTN_PRESS_REPEAT, on_repeat_done, NULL);

Note: BTN_SINGLE_CLICK fires when repeat==1 and BTN_DOUBLE_CLICK fires when repeat==2 after the short-press timeout. For repeat>=3, only BTN_PRESS_REPEAT fires during the press sequence. You can read button_get_repeat_count() from any callback to detect N-click patterns.

Important Notes

BTN_LONG_PRESS_HOLD fires every tick

BTN_LONG_PRESS_HOLD fires on every tick (default 5ms = 200Hz) while the button is held after the long press threshold. If your callback does expensive work, add your own throttling:

voidon_long_hold(Button*btn, void*user_data)
{
staticuint16_tthrottle=0;
if (++throttle<20) return; // fire every 100ms insteadthrottle=0;
// ... do work ...
}

Callback execution context

If button_ticks() is called from a timer interrupt (ISR), all callbacks execute in ISR context. Keep callbacks short and avoid blocking operations. For complex handling, set a flag in the callback and process it in the main loop.

If button_ticks() is called from a main loop or RTOS task, callbacks run in that context with no ISR restrictions.

Building

# Make
make all # library + examples
make test# run unit tests
make library # static library only# CMake
cmake -B build -DMULTIBUTTON_BUILD_TESTS=ON -DMULTIBUTTON_BUILD_EXAMPLES=ON
cmake --build build
cd build && ctest

Examples

  • examples/basic_example.c - Single/double click, long press, repeat detection
  • examples/advanced_example.c - Multi-button management, dynamic callback attach/detach
  • examples/poll_example.c - Polling mode without callbacks

FAQ

Q: How do I detect triple click? A: Register a BTN_PRESS_REPEAT callback and check button_get_repeat_count() for the desired count. See the "Implementing Triple Click" section above.

Q: Is it safe to call button_stop() from inside a callback? A: Yes. The library caches the next-pointer before invoking callbacks, so removing a button during iteration is safe.

Q: What happens if the ticks counter overflows during a very long press? A: The ticks counter saturates at UINT16_MAX (65535) instead of wrapping around. At 5ms intervals, this covers ~327 seconds of continuous holding.

Q: Can I use this library in a multi-threaded RTOS? A: Yes. Define MULTIBUTTON_THREAD_SAFE and provide MULTIBUTTON_LOCK()/MULTIBUTTON_UNLOCK() macros. A regular (non-recursive) mutex is sufficient since callbacks execute outside the lock.

Compatibility

  • C99 standard
  • Works on STM32, Arduino, ESP32, and other MCU platforms
  • Supports bare-metal and RTOS environments
  • Minimal memory footprint for resource-constrained systems

License

MIT License - see LICENSE for details.

About

Button driver for embedded system

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

MultiButton

A compact and flexible multi-button state machine library for embedded systems.

中文文档 (Chinese)

Features

  • 7 event types: press down, press up, single click, double click, long press start, long press hold, repeat press
  • Hardware debounce: built-in digital filter eliminates contact bounce
  • State machine driven: reliable state transitions with clear logic
  • Unlimited buttons: linked-list architecture supports any number of button instances
  • Callback & polling: flexible event handling via callbacks or polling button_get_event()
  • Memory efficient: compact bitfield struct (~30 bytes per button)
  • Configurable: adjustable timing thresholds and debounce depth
  • Thread-safe option: optional RTOS lock hooks with zero overhead on bare-metal

Quick Start

#include"multi_button.h"staticButtonbtn1;
// 1. Implement GPIO read functionuint8_tread_button_gpio(uint8_tbutton_id)
{
returnHAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
}
// 2. Define event callback (receives user_data)voidon_single_click(Button*btn, void*user_data)
{
// handle single click
}
// 3. Initialize and startvoidsetup(void)
{
button_init(&btn1, read_button_gpio, 0, 1); // active lowbutton_attach(&btn1, BTN_SINGLE_CLICK, on_single_click, NULL);
button_start(&btn1);
}
// 4. Call from 5ms timer interruptvoidtimer_5ms_isr(void)
{
button_ticks();
}

Event Types

EventDescription
BTN_PRESS_DOWNButton pressed down
BTN_PRESS_UPButton released
BTN_PRESS_REPEATRepeated press detected
BTN_SINGLE_CLICKSingle click completed (after timeout)
BTN_DOUBLE_CLICKDouble click completed (after timeout)
BTN_LONG_PRESS_STARTLong press threshold reached (fires once)
BTN_LONG_PRESS_HOLDLong press continuing (fires every tick while held)

State Machine

 +-- long hold --> [LONG_HOLD]
| |
[IDLE] -- press --> [PRESS] release
^ | |
| release |
| v |
| [RELEASE] <---------------------+
| | ^
| timeout| | quick press
| | |
+-------------+ [REPEAT] -- held too long --> [PRESS]

State Transitions Detail

  • IDLE -> PRESS: Button level matches active level after debounce. Fires BTN_PRESS_DOWN.
  • PRESS -> RELEASE: Button released before long press threshold. Fires BTN_PRESS_UP.
  • PRESS -> LONG_HOLD: Button held past LONG_TICKS. Fires BTN_LONG_PRESS_START.
  • RELEASE -> IDLE (timeout): No re-press within SHORT_TICKS. Fires BTN_SINGLE_CLICK or BTN_DOUBLE_CLICK based on repeat count.
  • RELEASE -> REPEAT: Button pressed again within timeout. Fires BTN_PRESS_DOWN + BTN_PRESS_REPEAT.
  • REPEAT -> RELEASE: Quick release. Continues waiting for more presses.
  • REPEAT -> PRESS: Held too long in repeat state. Resets for a new press cycle.
  • LONG_HOLD -> IDLE: Released from long press. Fires BTN_PRESS_UP.
  • LONG_HOLD (holding): Fires BTN_LONG_PRESS_HOLD every tick (see note below).

API Reference

Core Functions

voidbutton_init(Button*handle, uint8_t(*pin_level)(uint8_t),
uint8_tactive_level, uint8_tbutton_id);
voidbutton_attach(Button*handle, ButtonEventevent, BtnCallbackcb, void*user_data);
voidbutton_detach(Button*handle, ButtonEventevent);
intbutton_start(Button*handle); // returns 0=ok, -1=duplicate, -2=invalidvoidbutton_stop(Button*handle);
voidbutton_ticks(void); // call every 5ms from timer

Utility Functions

ButtonEventbutton_get_event(Button*handle); // current event (polling mode)uint8_tbutton_get_repeat_count(Button*handle); // repeat press countintbutton_is_pressed(Button*handle); // 1=pressed, 0=released, -1=errorvoidbutton_reset(Button*handle); // reset to idle state

User Data (Context Pointer)

Every callback receives a void* user_data pointer, set via button_attach():

typedefstruct {
intled_pin;
intbeep_count;
} ButtonContext;
ButtonContextctx= { .led_pin=13, .beep_count=0 };
voidon_click(Button*btn, void*user_data)
{
ButtonContext*ctx= (ButtonContext*)user_data;
toggle_led(ctx->led_pin);
ctx->beep_count++;
}
button_attach(&btn1, BTN_SINGLE_CLICK, on_click, &ctx);

All callbacks for the same button share the same user_data (it is stored per-button, not per-event).

Configuration

Edit the defines in multi_button.h:

#defineTICKS_INTERVAL 5 // timer tick interval (ms)
#defineDEBOUNCE_TICKS 3 // debounce filter depth (max 7)
#defineSHORT_TICKS (300 / TICKS_INTERVAL) // short press threshold
#defineLONG_TICKS (1000 / TICKS_INTERVAL) // long press threshold
#definePRESS_REPEAT_MAX_NUM 15 // max repeat counter

Thread Safety (RTOS)

For RTOS environments, define lock macros before including the header:

#defineMULTIBUTTON_THREAD_SAFE#defineMULTIBUTTON_LOCK() osMutexAcquire(btn_mutex, osWaitForever)
#defineMULTIBUTTON_UNLOCK() osMutexRelease(btn_mutex)
#include"multi_button.h"

On bare-metal (default), the lock macros compile to nothing with zero overhead.

Callbacks are executed outside the lock, so button_stop()/button_start() can be safely called from within callbacks without deadlock risk. A regular (non-recursive) mutex is sufficient.

Implementing Triple Click (N-Click)

The library natively supports single click and double click events. For triple click or higher N-click, use the BTN_PRESS_REPEAT event combined with button_get_repeat_count():

voidon_repeat_done(Button*btn, void*user_data)
{
// This fires when repeat press is detected// Check repeat count after timeout for final count
}
voidon_click_resolve(Button*btn, void*user_data)
{
uint8_tcount=button_get_repeat_count(btn);
if (count==3) {
// Triple click!
}
}
// Register for single click (fires after timeout with final repeat count)button_attach(&btn, BTN_SINGLE_CLICK, on_click_resolve, NULL);
// Or check repeat count in any callbackbutton_attach(&btn, BTN_PRESS_REPEAT, on_repeat_done, NULL);

Note: BTN_SINGLE_CLICK fires when repeat==1 and BTN_DOUBLE_CLICK fires when repeat==2 after the short-press timeout. For repeat>=3, only BTN_PRESS_REPEAT fires during the press sequence. You can read button_get_repeat_count() from any callback to detect N-click patterns.

Important Notes

BTN_LONG_PRESS_HOLD fires every tick

BTN_LONG_PRESS_HOLD fires on every tick (default 5ms = 200Hz) while the button is held after the long press threshold. If your callback does expensive work, add your own throttling:

voidon_long_hold(Button*btn, void*user_data)
{
staticuint16_tthrottle=0;
if (++throttle<20) return; // fire every 100ms insteadthrottle=0;
// ... do work ...
}

Callback execution context

If button_ticks() is called from a timer interrupt (ISR), all callbacks execute in ISR context. Keep callbacks short and avoid blocking operations. For complex handling, set a flag in the callback and process it in the main loop.

If button_ticks() is called from a main loop or RTOS task, callbacks run in that context with no ISR restrictions.

Building

# Make
make all # library + examples
make test# run unit tests
make library # static library only# CMake
cmake -B build -DMULTIBUTTON_BUILD_TESTS=ON -DMULTIBUTTON_BUILD_EXAMPLES=ON
cmake --build build
cd build && ctest

Examples

  • examples/basic_example.c - Single/double click, long press, repeat detection
  • examples/advanced_example.c - Multi-button management, dynamic callback attach/detach
  • examples/poll_example.c - Polling mode without callbacks

FAQ

Q: How do I detect triple click? A: Register a BTN_PRESS_REPEAT callback and check button_get_repeat_count() for the desired count. See the "Implementing Triple Click" section above.

Q: Is it safe to call button_stop() from inside a callback? A: Yes. The library caches the next-pointer before invoking callbacks, so removing a button during iteration is safe.

Q: What happens if the ticks counter overflows during a very long press? A: The ticks counter saturates at UINT16_MAX (65535) instead of wrapping around. At 5ms intervals, this covers ~327 seconds of continuous holding.

Q: Can I use this library in a multi-threaded RTOS? A: Yes. Define MULTIBUTTON_THREAD_SAFE and provide MULTIBUTTON_LOCK()/MULTIBUTTON_UNLOCK() macros. A regular (non-recursive) mutex is sufficient since callbacks execute outside the lock.

Compatibility

  • C99 standard
  • Works on STM32, Arduino, ESP32, and other MCU platforms
  • Supports bare-metal and RTOS environments
  • Minimal memory footprint for resource-constrained systems

License

MIT License - see LICENSE for details.

About

Button driver for embedded system

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

MultiButton

A compact and flexible multi-button state machine library for embedded systems.

中文文档 (Chinese)

Features

  • 7 event types: press down, press up, single click, double click, long press start, long press hold, repeat press
  • Hardware debounce: built-in digital filter eliminates contact bounce
  • State machine driven: reliable state transitions with clear logic
  • Unlimited buttons: linked-list architecture supports any number of button instances
  • Callback & polling: flexible event handling via callbacks or polling button_get_event()
  • Memory efficient: compact bitfield struct (~30 bytes per button)
  • Configurable: adjustable timing thresholds and debounce depth
  • Thread-safe option: optional RTOS lock hooks with zero overhead on bare-metal

Quick Start

#include"multi_button.h"staticButtonbtn1;
// 1. Implement GPIO read functionuint8_tread_button_gpio(uint8_tbutton_id)
{
returnHAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
}
// 2. Define event callback (receives user_data)voidon_single_click(Button*btn, void*user_data)
{
// handle single click
}
// 3. Initialize and startvoidsetup(void)
{
button_init(&btn1, read_button_gpio, 0, 1); // active lowbutton_attach(&btn1, BTN_SINGLE_CLICK, on_single_click, NULL);
button_start(&btn1);
}
// 4. Call from 5ms timer interruptvoidtimer_5ms_isr(void)
{
button_ticks();
}

Event Types

EventDescription
BTN_PRESS_DOWNButton pressed down
BTN_PRESS_UPButton released
BTN_PRESS_REPEATRepeated press detected
BTN_SINGLE_CLICKSingle click completed (after timeout)
BTN_DOUBLE_CLICKDouble click completed (after timeout)
BTN_LONG_PRESS_STARTLong press threshold reached (fires once)
BTN_LONG_PRESS_HOLDLong press continuing (fires every tick while held)

State Machine

 +-- long hold --> [LONG_HOLD]
| |
[IDLE] -- press --> [PRESS] release
^ | |
| release |
| v |
| [RELEASE] <---------------------+
| | ^
| timeout| | quick press
| | |
+-------------+ [REPEAT] -- held too long --> [PRESS]

State Transitions Detail

  • IDLE -> PRESS: Button level matches active level after debounce. Fires BTN_PRESS_DOWN.
  • PRESS -> RELEASE: Button released before long press threshold. Fires BTN_PRESS_UP.
  • PRESS -> LONG_HOLD: Button held past LONG_TICKS. Fires BTN_LONG_PRESS_START.
  • RELEASE -> IDLE (timeout): No re-press within SHORT_TICKS. Fires BTN_SINGLE_CLICK or BTN_DOUBLE_CLICK based on repeat count.
  • RELEASE -> REPEAT: Button pressed again within timeout. Fires BTN_PRESS_DOWN + BTN_PRESS_REPEAT.
  • REPEAT -> RELEASE: Quick release. Continues waiting for more presses.
  • REPEAT -> PRESS: Held too long in repeat state. Resets for a new press cycle.
  • LONG_HOLD -> IDLE: Released from long press. Fires BTN_PRESS_UP.
  • LONG_HOLD (holding): Fires BTN_LONG_PRESS_HOLD every tick (see note below).

API Reference

Core Functions

voidbutton_init(Button*handle, uint8_t(*pin_level)(uint8_t),
uint8_tactive_level, uint8_tbutton_id);
voidbutton_attach(Button*handle, ButtonEventevent, BtnCallbackcb, void*user_data);
voidbutton_detach(Button*handle, ButtonEventevent);
intbutton_start(Button*handle); // returns 0=ok, -1=duplicate, -2=invalidvoidbutton_stop(Button*handle);
voidbutton_ticks(void); // call every 5ms from timer

Utility Functions

ButtonEventbutton_get_event(Button*handle); // current event (polling mode)uint8_tbutton_get_repeat_count(Button*handle); // repeat press countintbutton_is_pressed(Button*handle); // 1=pressed, 0=released, -1=errorvoidbutton_reset(Button*handle); // reset to idle state

User Data (Context Pointer)

Every callback receives a void* user_data pointer, set via button_attach():

typedefstruct {
intled_pin;
intbeep_count;
} ButtonContext;
ButtonContextctx= { .led_pin=13, .beep_count=0 };
voidon_click(Button*btn, void*user_data)
{
ButtonContext*ctx= (ButtonContext*)user_data;
toggle_led(ctx->led_pin);
ctx->beep_count++;
}
button_attach(&btn1, BTN_SINGLE_CLICK, on_click, &ctx);

All callbacks for the same button share the same user_data (it is stored per-button, not per-event).

Configuration

Edit the defines in multi_button.h:

#defineTICKS_INTERVAL 5 // timer tick interval (ms)
#defineDEBOUNCE_TICKS 3 // debounce filter depth (max 7)
#defineSHORT_TICKS (300 / TICKS_INTERVAL) // short press threshold
#defineLONG_TICKS (1000 / TICKS_INTERVAL) // long press threshold
#definePRESS_REPEAT_MAX_NUM 15 // max repeat counter

Thread Safety (RTOS)

For RTOS environments, define lock macros before including the header:

#defineMULTIBUTTON_THREAD_SAFE#defineMULTIBUTTON_LOCK() osMutexAcquire(btn_mutex, osWaitForever)
#defineMULTIBUTTON_UNLOCK() osMutexRelease(btn_mutex)
#include"multi_button.h"

On bare-metal (default), the lock macros compile to nothing with zero overhead.

Callbacks are executed outside the lock, so button_stop()/button_start() can be safely called from within callbacks without deadlock risk. A regular (non-recursive) mutex is sufficient.

Implementing Triple Click (N-Click)

The library natively supports single click and double click events. For triple click or higher N-click, use the BTN_PRESS_REPEAT event combined with button_get_repeat_count():

voidon_repeat_done(Button*btn, void*user_data)
{
// This fires when repeat press is detected// Check repeat count after timeout for final count
}
voidon_click_resolve(Button*btn, void*user_data)
{
uint8_tcount=button_get_repeat_count(btn);
if (count==3) {
// Triple click!
}
}
// Register for single click (fires after timeout with final repeat count)button_attach(&btn, BTN_SINGLE_CLICK, on_click_resolve, NULL);
// Or check repeat count in any callbackbutton_attach(&btn, BTN_PRESS_REPEAT, on_repeat_done, NULL);

Note: BTN_SINGLE_CLICK fires when repeat==1 and BTN_DOUBLE_CLICK fires when repeat==2 after the short-press timeout. For repeat>=3, only BTN_PRESS_REPEAT fires during the press sequence. You can read button_get_repeat_count() from any callback to detect N-click patterns.

Important Notes

BTN_LONG_PRESS_HOLD fires every tick

BTN_LONG_PRESS_HOLD fires on every tick (default 5ms = 200Hz) while the button is held after the long press threshold. If your callback does expensive work, add your own throttling:

voidon_long_hold(Button*btn, void*user_data)
{
staticuint16_tthrottle=0;
if (++throttle<20) return; // fire every 100ms insteadthrottle=0;
// ... do work ...
}

Callback execution context

If button_ticks() is called from a timer interrupt (ISR), all callbacks execute in ISR context. Keep callbacks short and avoid blocking operations. For complex handling, set a flag in the callback and process it in the main loop.

If button_ticks() is called from a main loop or RTOS task, callbacks run in that context with no ISR restrictions.

Building

# Make
make all # library + examples
make test# run unit tests
make library # static library only# CMake
cmake -B build -DMULTIBUTTON_BUILD_TESTS=ON -DMULTIBUTTON_BUILD_EXAMPLES=ON
cmake --build build
cd build && ctest

Examples

  • examples/basic_example.c - Single/double click, long press, repeat detection
  • examples/advanced_example.c - Multi-button management, dynamic callback attach/detach
  • examples/poll_example.c - Polling mode without callbacks

FAQ

Q: How do I detect triple click? A: Register a BTN_PRESS_REPEAT callback and check button_get_repeat_count() for the desired count. See the "Implementing Triple Click" section above.

Q: Is it safe to call button_stop() from inside a callback? A: Yes. The library caches the next-pointer before invoking callbacks, so removing a button during iteration is safe.

Q: What happens if the ticks counter overflows during a very long press? A: The ticks counter saturates at UINT16_MAX (65535) instead of wrapping around. At 5ms intervals, this covers ~327 seconds of continuous holding.

Q: Can I use this library in a multi-threaded RTOS? A: Yes. Define MULTIBUTTON_THREAD_SAFE and provide MULTIBUTTON_LOCK()/MULTIBUTTON_UNLOCK() macros. A regular (non-recursive) mutex is sufficient since callbacks execute outside the lock.

Compatibility

  • C99 standard
  • Works on STM32, Arduino, ESP32, and other MCU platforms
  • Supports bare-metal and RTOS environments
  • Minimal memory footprint for resource-constrained systems

License

MIT License - see LICENSE for details.

About

Button driver for embedded system

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

MultiButton

A compact and flexible multi-button state machine library for embedded systems.

中文文档 (Chinese)

Features

  • 7 event types: press down, press up, single click, double click, long press start, long press hold, repeat press
  • Hardware debounce: built-in digital filter eliminates contact bounce
  • State machine driven: reliable state transitions with clear logic
  • Unlimited buttons: linked-list architecture supports any number of button instances
  • Callback & polling: flexible event handling via callbacks or polling button_get_event()
  • Memory efficient: compact bitfield struct (~30 bytes per button)
  • Configurable: adjustable timing thresholds and debounce depth
  • Thread-safe option: optional RTOS lock hooks with zero overhead on bare-metal

Quick Start

#include"multi_button.h"staticButtonbtn1;
// 1. Implement GPIO read functionuint8_tread_button_gpio(uint8_tbutton_id)
{
returnHAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
}
// 2. Define event callback (receives user_data)voidon_single_click(Button*btn, void*user_data)
{
// handle single click
}
// 3. Initialize and startvoidsetup(void)
{
button_init(&btn1, read_button_gpio, 0, 1); // active lowbutton_attach(&btn1, BTN_SINGLE_CLICK, on_single_click, NULL);
button_start(&btn1);
}
// 4. Call from 5ms timer interruptvoidtimer_5ms_isr(void)
{
button_ticks();
}

Event Types

EventDescription
BTN_PRESS_DOWNButton pressed down
BTN_PRESS_UPButton released
BTN_PRESS_REPEATRepeated press detected
BTN_SINGLE_CLICKSingle click completed (after timeout)
BTN_DOUBLE_CLICKDouble click completed (after timeout)
BTN_LONG_PRESS_STARTLong press threshold reached (fires once)
BTN_LONG_PRESS_HOLDLong press continuing (fires every tick while held)

State Machine

 +-- long hold --> [LONG_HOLD]
| |
[IDLE] -- press --> [PRESS] release
^ | |
| release |
| v |
| [RELEASE] <---------------------+
| | ^
| timeout| | quick press
| | |
+-------------+ [REPEAT] -- held too long --> [PRESS]

State Transitions Detail

  • IDLE -> PRESS: Button level matches active level after debounce. Fires BTN_PRESS_DOWN.
  • PRESS -> RELEASE: Button released before long press threshold. Fires BTN_PRESS_UP.
  • PRESS -> LONG_HOLD: Button held past LONG_TICKS. Fires BTN_LONG_PRESS_START.
  • RELEASE -> IDLE (timeout): No re-press within SHORT_TICKS. Fires BTN_SINGLE_CLICK or BTN_DOUBLE_CLICK based on repeat count.
  • RELEASE -> REPEAT: Button pressed again within timeout. Fires BTN_PRESS_DOWN + BTN_PRESS_REPEAT.
  • REPEAT -> RELEASE: Quick release. Continues waiting for more presses.
  • REPEAT -> PRESS: Held too long in repeat state. Resets for a new press cycle.
  • LONG_HOLD -> IDLE: Released from long press. Fires BTN_PRESS_UP.
  • LONG_HOLD (holding): Fires BTN_LONG_PRESS_HOLD every tick (see note below).

API Reference

Core Functions

voidbutton_init(Button*handle, uint8_t(*pin_level)(uint8_t),
uint8_tactive_level, uint8_tbutton_id);
voidbutton_attach(Button*handle, ButtonEventevent, BtnCallbackcb, void*user_data);
voidbutton_detach(Button*handle, ButtonEventevent);
intbutton_start(Button*handle); // returns 0=ok, -1=duplicate, -2=invalidvoidbutton_stop(Button*handle);
voidbutton_ticks(void); // call every 5ms from timer

Utility Functions

ButtonEventbutton_get_event(Button*handle); // current event (polling mode)uint8_tbutton_get_repeat_count(Button*handle); // repeat press countintbutton_is_pressed(Button*handle); // 1=pressed, 0=released, -1=errorvoidbutton_reset(Button*handle); // reset to idle state

User Data (Context Pointer)

Every callback receives a void* user_data pointer, set via button_attach():

typedefstruct {
intled_pin;
intbeep_count;
} ButtonContext;
ButtonContextctx= { .led_pin=13, .beep_count=0 };
voidon_click(Button*btn, void*user_data)
{
ButtonContext*ctx= (ButtonContext*)user_data;
toggle_led(ctx->led_pin);
ctx->beep_count++;
}
button_attach(&btn1, BTN_SINGLE_CLICK, on_click, &ctx);

All callbacks for the same button share the same user_data (it is stored per-button, not per-event).

Configuration

Edit the defines in multi_button.h:

#defineTICKS_INTERVAL 5 // timer tick interval (ms)
#defineDEBOUNCE_TICKS 3 // debounce filter depth (max 7)
#defineSHORT_TICKS (300 / TICKS_INTERVAL) // short press threshold
#defineLONG_TICKS (1000 / TICKS_INTERVAL) // long press threshold
#definePRESS_REPEAT_MAX_NUM 15 // max repeat counter

Thread Safety (RTOS)

For RTOS environments, define lock macros before including the header:

#defineMULTIBUTTON_THREAD_SAFE#defineMULTIBUTTON_LOCK() osMutexAcquire(btn_mutex, osWaitForever)
#defineMULTIBUTTON_UNLOCK() osMutexRelease(btn_mutex)
#include"multi_button.h"

On bare-metal (default), the lock macros compile to nothing with zero overhead.

Callbacks are executed outside the lock, so button_stop()/button_start() can be safely called from within callbacks without deadlock risk. A regular (non-recursive) mutex is sufficient.

Implementing Triple Click (N-Click)

The library natively supports single click and double click events. For triple click or higher N-click, use the BTN_PRESS_REPEAT event combined with button_get_repeat_count():

voidon_repeat_done(Button*btn, void*user_data)
{
// This fires when repeat press is detected// Check repeat count after timeout for final count
}
voidon_click_resolve(Button*btn, void*user_data)
{
uint8_tcount=button_get_repeat_count(btn);
if (count==3) {
// Triple click!
}
}
// Register for single click (fires after timeout with final repeat count)button_attach(&btn, BTN_SINGLE_CLICK, on_click_resolve, NULL);
// Or check repeat count in any callbackbutton_attach(&btn, BTN_PRESS_REPEAT, on_repeat_done, NULL);

Note: BTN_SINGLE_CLICK fires when repeat==1 and BTN_DOUBLE_CLICK fires when repeat==2 after the short-press timeout. For repeat>=3, only BTN_PRESS_REPEAT fires during the press sequence. You can read button_get_repeat_count() from any callback to detect N-click patterns.

Important Notes

BTN_LONG_PRESS_HOLD fires every tick

BTN_LONG_PRESS_HOLD fires on every tick (default 5ms = 200Hz) while the button is held after the long press threshold. If your callback does expensive work, add your own throttling:

voidon_long_hold(Button*btn, void*user_data)
{
staticuint16_tthrottle=0;
if (++throttle<20) return; // fire every 100ms insteadthrottle=0;
// ... do work ...
}

Callback execution context

If button_ticks() is called from a timer interrupt (ISR), all callbacks execute in ISR context. Keep callbacks short and avoid blocking operations. For complex handling, set a flag in the callback and process it in the main loop.

If button_ticks() is called from a main loop or RTOS task, callbacks run in that context with no ISR restrictions.

Building

# Make
make all # library + examples
make test# run unit tests
make library # static library only# CMake
cmake -B build -DMULTIBUTTON_BUILD_TESTS=ON -DMULTIBUTTON_BUILD_EXAMPLES=ON
cmake --build build
cd build && ctest

Examples

  • examples/basic_example.c - Single/double click, long press, repeat detection
  • examples/advanced_example.c - Multi-button management, dynamic callback attach/detach
  • examples/poll_example.c - Polling mode without callbacks

FAQ

Q: How do I detect triple click? A: Register a BTN_PRESS_REPEAT callback and check button_get_repeat_count() for the desired count. See the "Implementing Triple Click" section above.

Q: Is it safe to call button_stop() from inside a callback? A: Yes. The library caches the next-pointer before invoking callbacks, so removing a button during iteration is safe.

Q: What happens if the ticks counter overflows during a very long press? A: The ticks counter saturates at UINT16_MAX (65535) instead of wrapping around. At 5ms intervals, this covers ~327 seconds of continuous holding.

Q: Can I use this library in a multi-threaded RTOS? A: Yes. Define MULTIBUTTON_THREAD_SAFE and provide MULTIBUTTON_LOCK()/MULTIBUTTON_UNLOCK() macros. A regular (non-recursive) mutex is sufficient since callbacks execute outside the lock.

Compatibility

  • C99 standard
  • Works on STM32, Arduino, ESP32, and other MCU platforms
  • Supports bare-metal and RTOS environments
  • Minimal memory footprint for resource-constrained systems

License

MIT License - see LICENSE for details.

About

Button driver for embedded system

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages