#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
void IRAM_ATTR button_isr_handler(void* arg);
#define SENSOR_PIN 4 // Button connected to GPIO4
#define LED_PIN 2
bool sensor_called = false; // Global flag for ISR
bool Body_detected = false;
void app_main() {
// Configuring GPIO as input
gpio_set_direction(SENSOR_PIN, GPIO_MODE_INPUT);
gpio_set_level(LED_PIN, GPIO_MODE_OUTPUT);
// Setting interrupt on FALLING edge (button press)
gpio_set_intr_type(SENSOR_PIN, GPIO_INTR_ANYEDGE);
// Install ISR service (interrupt handling)
gpio_install_isr_service(0);
// Attaching ISR handler to SENSOR_PIN
gpio_isr_handler_add(SENSOR_PIN, button_isr_handler, NULL);
while (1) {
if (sensor_called) { // Check flag in main loop
sensor_called = false; // Reset flag
if (Body_detected) {
printf("body detected\n");
gpio_set_level(LED_PIN, 1);
}
else {
printf("no body detected\n");
gpio_set_level(LED_PIN, 0);
}
}
printf("Main loop running...\n");
vTaskDelay(pdMS_TO_TICKS(100)); // loop continues running
}
}
// Interrupt Service Routine (ISR)
void IRAM_ATTR button_isr_handler(void* arg) {
int body = gpio_get_level(SENSOR_PIN);
Body_detected = (body == 1);
sensor_called = true;
}