Login
1 branch 0 tags
Ben (Desktop/Arch) Smoother UI bb6b2c1 1 month ago 72 Commits
moon / esp32 / main / buttons.c
/**
 * @file buttons.c
 * ESP32 GPIO button driver
 * Buttons are wired active-low (press connects to GND)
 */

#include "buttons.h"
#include "../../src/moon.h"
#include "driver/gpio.h"
#include "pinout.h"
#include "utils.h"

uint32_t buttons_duration_released = 0;

void buttons_init(void) {
	gpio_config_t io_conf = {
	    .pin_bit_mask = (1ULL << PIN_UP) | (1ULL << PIN_DOWN) |
	                    (1ULL << PIN_OK) | (1ULL << PIN_BACK),
	    .mode = GPIO_MODE_INPUT,
	    .pull_up_en = GPIO_PULLUP_ENABLE,
	    .pull_down_en = GPIO_PULLDOWN_DISABLE,
	    .intr_type = GPIO_INTR_DISABLE,
	};
	gpio_config(&io_conf);
}

void buttons_update(void) {
	static uint32_t last_update = 0;
	button_state = 0;

	// Active-low: pressed when GPIO reads 0
	if (gpio_get_level(PIN_UP) == 0) {
		button_state |= BUTTON_STATE_UP;
	}
	if (gpio_get_level(PIN_DOWN) == 0) {
		button_state |= BUTTON_STATE_DOWN;
	}
	if (gpio_get_level(PIN_OK) == 0) {
		button_state |= BUTTON_STATE_OK;
	}
	if (gpio_get_level(PIN_BACK) == 0) {
		button_state |= BUTTON_STATE_BACK;
	}

	const uint32_t now = get_millis();
	if (button_state == 0) {
		buttons_duration_released += now - last_update;
	} else {
		buttons_duration_released = 0;
		set_display_brightness(255);
	}
	last_update = now;
}