add input_handler module

This commit is contained in:
2025-05-29 18:53:28 +02:00
parent 62fabba1fa
commit f9cd3be74e
2 changed files with 120 additions and 0 deletions

74
src/input_handler.c Normal file
View File

@@ -0,0 +1,74 @@
#include <avr/io.h>
#include "input_handler.h"
#include "timer_counter.h"
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,
};