PowerTimer-Firmware/src/buttons.c

65 lines
1.3 KiB
C

#include <string.h>
#include "hardware/gpio.h"
#include "pinout.h"
#include "buttons.h"
static const uint8_t m_pins[NUM_BUTTONS] = {
BTN_ON_PIN,
BTN_OFF_PIN
};
static uint8_t m_events[NUM_BUTTONS];
static uint32_t m_last_change_time[NUM_BUTTONS];
static uint32_t m_states;
void buttons_init(void)
{
for(int i = 0; i < NUM_BUTTONS; i++) {
gpio_init(m_pins[i]);
gpio_set_dir(m_pins[i], false); // true = output
gpio_set_pulls(m_pins[i], true, false); // enable pullup
}
memset(m_events, 0, sizeof(m_events));
memset(m_last_change_time, 0, sizeof(m_last_change_time));
m_states = 0;
}
void buttons_update_state(uint32_t time_ms)
{
for(int i = 0; i < NUM_BUTTONS; i++) {
bool is_pressed = gpio_get(m_pins[i]);
bool was_pressed = (m_states >> i) != 0;
m_events[i] = 0;
if(is_pressed && !was_pressed) {
m_events[i] |= BTN_EVENT_PRESSED;
m_states |= (1 << i);
m_last_change_time[i] = time_ms;
} else if(!is_pressed && was_pressed) {
m_events[i] |= BTN_EVENT_RELEASED;
m_states &= ~(1 << i);
m_last_change_time[i] = time_ms;
}
}
}
uint8_t buttons_get_events(button_id_t button)
{
return m_events[button];
}
bool buttons_is_pressed(button_id_t button)
{
return (m_states & (1 << button)) != 0;
}
uint32_t buttons_get_last_change_time(button_id_t button)
{
return m_last_change_time[button];
}