#include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" #include "esp_log.h" #include "sdkconfig.h" /* Use project configuration menu (idf.py menuconfig) to choose the GPIO to blink, or you can edit the following line and set a number here. */ #define BLINK_GPIO CONFIG_BLINK_GPIO #define PHOTO_SENSOR_PIN GPIO_NUM_18 static void configure_led(void) { ESP_LOGI("LED", "Example configured to blink GPIO LED!"); gpio_reset_pin(BLINK_GPIO); /* Set the GPIO as a push/pull output */ gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT); } // GPIO setup void setup_photo_sensor() { gpio_config_t io_conf = { .intr_type = GPIO_INTR_ANYEDGE, // Trigger on both rising & falling edges .pin_bit_mask = (1ULL << PHOTO_SENSOR_PIN), .mode = GPIO_MODE_INPUT, .pull_up_en = GPIO_PULLUP_DISABLE, .pull_down_en = GPIO_PULLDOWN_DISABLE }; gpio_config(&io_conf); ESP_LOGI("PHOTO", "Photomicrosensor configured on GPIO %d", PHOTO_SENSOR_PIN); } void read_photo_sensor_task(void *pvParameters) { static int prevState = 0; while (1) { int sensorState = gpio_get_level(PHOTO_SENSOR_PIN); if (sensorState != prevState) { prevState = sensorState; ESP_EARLY_LOGI("PHOTO", "Triggered! State: %d", sensorState); if( sensorState == 0 ) { gpio_set_level(BLINK_GPIO, 1); } else { gpio_set_level(BLINK_GPIO, 0); } } vTaskDelay(pdMS_TO_TICKS(50)); // Delay 50ms (20 times per second) } } void app_main(void) { /* Configure the peripheral according to the LED type */ configure_led(); setup_photo_sensor(); xTaskCreate(read_photo_sensor_task, "read_sensor_task", 2048, NULL, 10, NULL); }