#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#define BTN_RED GPIO_NUM_13
#define RED_LED_GPIO GPIO_NUM_4
#define GREEN_LED_GPIO GPIO_NUM_2
#define BLUE_LED_GPIO GPIO_NUM_15
#define DELAY_TIME 200
volatile bool button_pressed = false;
volatile char cnt = 0;
TickType_t button_down_time = 0;
TickType_t button_up_time = 0;
TickType_t press_duration = 0;
uint64_t up_time = 0;
uint64_t down_time = 0;
uint64_t duration = 0;
static void gpio_isr_handler(void* arg)
{
if (gpio_get_level(BTN_RED) == 0){
gpio_set_level(BLUE_LED_GPIO, 1);
cnt = 1;
button_down_time = xTaskGetTickCount();
down_time = esp_timer_get_time();
}
if (gpio_get_level(BTN_RED) == 1){
gpio_set_level(BLUE_LED_GPIO, 0);
cnt = 2;
button_up_time = xTaskGetTickCount();
up_time = esp_timer_get_time();
duration = (up_time - down_time) / 1000; // Convert to milliseconds
press_duration = button_up_time - button_down_time;
button_pressed = true;
}
}
void button_config()
{
gpio_install_isr_service(0);
printf("configuring button\n");
gpio_reset_pin(BTN_RED);
gpio_set_direction(BTN_RED, GPIO_MODE_INPUT);
gpio_pullup_en(BTN_RED);
gpio_set_intr_type(BTN_RED, GPIO_INTR_ANYEDGE);
gpio_isr_handler_add(BTN_RED, gpio_isr_handler, NULL);
printf("config complete\n");
}
extern "C" void app_main()
{
button_config();
gpio_set_direction(RED_LED_GPIO, GPIO_MODE_OUTPUT);
gpio_set_direction(BLUE_LED_GPIO, GPIO_MODE_OUTPUT);
gpio_set_direction(GREEN_LED_GPIO, GPIO_MODE_OUTPUT);
static int prevTick;
static bool BlinkControl = false;
int curTick;
while (1) {
// printf("Cnt: %d\n",cnt);
curTick = xTaskGetTickCount();
if((curTick - prevTick)>500){
printf("BlinkControl Before: %d\n", BlinkControl);
BlinkControl = (BlinkControl>0)?0:1;
printf("BlinkControl After: %d\n", BlinkControl);
gpio_set_level(RED_LED_GPIO, BlinkControl);
gpio_set_level(GREEN_LED_GPIO, BlinkControl);
gpio_set_level(BLUE_LED_GPIO, !BlinkControl);
BlinkControl = !BlinkControl;
prevTick = curTick;
}
if (button_pressed) {
// printf("Button press detected!\n");
if (press_duration < pdMS_TO_TICKS(500)) printf("Short press detected: %d (%lld)\n", press_duration, duration);
else printf("Long press detected: %d (%lld)\n", press_duration, duration);
button_pressed = false;
button_down_time = 0;
button_up_time = 0;
}
// vTaskDelay(DELAY_TIME / portTICK_PERIOD_MS);
}
}