#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
void IRAM_ATTR motion_sensor_isr_handler(void* arg);
#define MOTION_SENSOR_PIN 4 //Motion sensor connected to GPIO4 (JI)
#define LED_PIN 2 //LED connected to GPIO2 (JI)
// Global flags for ISR
bool motionStateChanged = false; //Flag to indicate the sensor state has changed. (JI)
bool isMotionDetected = false; //Flag to track if motion is currently detected. (JI)
void app_main() {
//Configure motion sensor pin as input with pull-up resistor
gpio_set_direction(MOTION_SENSOR_PIN, GPIO_MODE_INPUT);
gpio_set_pull_mode(MOTION_SENSOR_PIN, GPIO_PULLUP_ONLY);
//Set interrupts to trigger on both rising and falling edges. (JI)
gpio_set_intr_type(MOTION_SENSOR_PIN, GPIO_INTR_ANYEDGE);
gpio_set_direction(LED_PIN, GPIO_MODE_OUTPUT); //Configure LED pin as output. (JI)
gpio_set_pull_mode(LED_PIN, GPIO_PULLUP_ONLY); //Configure LED pin as output with pull-up resistor. (JI)
gpio_set_level(LED_PIN, 0); //Initially set the LED value to zero. (JI)
//Install ISR service (interrupt handling)
gpio_install_isr_service(0);
//Attaching ISR handler to MOTION_SENSOR. (JI)
gpio_isr_handler_add(MOTION_SENSOR_PIN, motion_sensor_isr_handler, NULL); //
while (1) {
if (motionStateChanged) { //Checking if the motion state has changed. (JI)
motionStateChanged = false; //Reset flag.
if (isMotionDetected) { //If motion is detected, print a message and turn on the LED. (JI)
printf("Motion Detected!\n");
gpio_set_level(LED_PIN, 1);
} else { //If motion is not detected, print a message and turn off the LED. (JI)
printf("No Motion Detected.\n");
gpio_set_level(LED_PIN, 0);
}
}
printf("Main loop running...\n");
vTaskDelay(pdMS_TO_TICKS(500));
}
}
//Interrupt Service Routine (ISR)
void IRAM_ATTR motion_sensor_isr_handler(void* arg) {
int sensor_state = gpio_get_level(MOTION_SENSOR_PIN); //Read the current state of the motion sensor pin and store the value in sensor_state. (JI)
isMotionDetected = (sensor_state == 1); //If sensor_state is HIGH, motion is detected. (JI)
motionStateChanged = true; //Set flag to TRUE so program can enter the "motionStateChanged" code block in the main program to print a message of motion detected or not. (JI)
}