#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "soc/gpio_periph.h"
#include "freertos/timers.h"
#include "esp_log.h"

#define HIGH 1
#define LOW 0

static const char *TAG = "GPIO_INPUT";

volatile bool button_state = false;
volatile int count = 0;


void debounce_timer_callback(TimerHandle_t xTimer) {
    bool current_state = !gpio_get_level(GPIO_NUM_9);

    if (current_state != button_state) {
      button_state = current_state;
      if(button_state) count++;
    }
}

void app_main(void)
{
  gpio_set_direction(GPIO_NUM_1, GPIO_MODE_OUTPUT);
  gpio_set_direction(GPIO_NUM_9, GPIO_MODE_INPUT);

  TimerHandle_t timer = xTimerCreate("Meu temporizador", pdMS_TO_TICKS(50), pdTRUE, 0, debounce_timer_callback);

  /* Verificar se o temporizador foi criado com sucesso */
  if (timer == NULL) {
      printf("Erro ao criar temporizador!\n");
      return;
  }
  
  /* Iniciar o temporizador */
  if (xTimerStart(timer, 0) != pdPASS) {
      printf("Erro ao iniciar temporizador!\n");
      return;
  }

  while(1) {
    bool stored_state = button_state;

    if (stored_state)
    {
      gpio_set_level(GPIO_NUM_1, HIGH);       
    }
    else
    {  
      gpio_set_level(GPIO_NUM_1, LOW);        
    } 

    ESP_LOGE(TAG, "Counter = %d", count);
  }
}