#include #include "input_handler.h" #include "timer_counter.h" typedef void (*ButtonRoutine_t)(ButtonKey_t *); const ButtonRoutine_t button_routine[MAX_STATE]; void buttonHandler(ButtonKey_t *key) { button_routine[key->state](key); } static inline GPIO_PinState getPinState(ButtonKey_t *key) { // Read the pin state from the register return (*(key->instance.pin_register) & (1 << key->instance.pin_number)) ? GPIO_PIN_SET : GPIO_PIN_RESET; } static void buttonIdleRoutine(ButtonKey_t *key) { if (getPinState(key) == key->active_state) { key->state = DEBOUNCE; key->last_tick = ticks100us(); } } static void buttonActiveRoutine(ButtonKey_t *key) { if (getPinState(key) != key->active_state) { key->state = DEBOUNCE; key->last_tick = ticks100us(); } } static void buttonDebounceRoutine(ButtonKey_t *key) { // Read the current pin state GPIO_PinState pin_now = getPinState(key); ButtonState_t new_state = (pin_now == key->active_state) ? ACTIVE : IDLE; // Check if debounce time has passed uint16_t debounce_time = (new_state == ACTIVE) ? key->timer_debounce_on : key->timer_debounce_off; if ((ticks100us() - key->last_tick) < debounce_time) { return; // Still in debounce period, do nothing } // If the new state is the same as the last state, we return to the previous state if (new_state == key->last_state) { key->state = key->last_state; return; } // Update the last state and current state key->last_state = new_state; key->state = new_state; if (new_state == ACTIVE && key->buttonPressed) { key->buttonPressed(key); } else if (new_state == IDLE && key->buttonReleased) { key->buttonReleased(key); } } const ButtonRoutine_t button_routine[MAX_STATE] = { buttonIdleRoutine, buttonDebounceRoutine, buttonActiveRoutine, };