main.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <stdio.h>
  2. #include "freertos/FreeRTOS.h"
  3. #include "freertos/task.h"
  4. #include "driver/gpio.h"
  5. #include "esp_log.h"
  6. #include "sdkconfig.h"
  7. /* Use project configuration menu (idf.py menuconfig) to choose the GPIO to blink,
  8. or you can edit the following line and set a number here.
  9. */
  10. #define BLINK_GPIO CONFIG_BLINK_GPIO
  11. #define PHOTO_SENSOR_PIN GPIO_NUM_18
  12. static void configure_led(void)
  13. {
  14. ESP_LOGI("LED", "Example configured to blink GPIO LED!");
  15. gpio_reset_pin(BLINK_GPIO);
  16. /* Set the GPIO as a push/pull output */
  17. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  18. }
  19. // GPIO setup
  20. void setup_photo_sensor() {
  21. gpio_config_t io_conf = {
  22. .intr_type = GPIO_INTR_ANYEDGE, // Trigger on both rising & falling edges
  23. .pin_bit_mask = (1ULL << PHOTO_SENSOR_PIN),
  24. .mode = GPIO_MODE_INPUT,
  25. .pull_up_en = GPIO_PULLUP_DISABLE,
  26. .pull_down_en = GPIO_PULLDOWN_DISABLE
  27. };
  28. gpio_config(&io_conf);
  29. ESP_LOGI("PHOTO", "Photomicrosensor configured on GPIO %d", PHOTO_SENSOR_PIN);
  30. }
  31. void read_photo_sensor_task(void *pvParameters) {
  32. static int prevState = 0;
  33. while (1) {
  34. int sensorState = gpio_get_level(PHOTO_SENSOR_PIN);
  35. if (sensorState != prevState) {
  36. prevState = sensorState;
  37. ESP_EARLY_LOGI("PHOTO", "Triggered! State: %d", sensorState);
  38. if( sensorState == 0 ) {
  39. gpio_set_level(BLINK_GPIO, 1);
  40. }
  41. else {
  42. gpio_set_level(BLINK_GPIO, 0);
  43. }
  44. }
  45. vTaskDelay(pdMS_TO_TICKS(50)); // Delay 50ms (20 times per second)
  46. }
  47. }
  48. void app_main(void)
  49. {
  50. /* Configure the peripheral according to the LED type */
  51. configure_led();
  52. setup_photo_sensor();
  53. xTaskCreate(read_photo_sensor_task, "read_sensor_task", 2048, NULL, 10, NULL);
  54. }