#define timeSeconds 10
// Set GPIOs for LED and PIR Motion Sensor
const int LED = 4;
const int motionSensor = 2;
// Timer: Auxiliary Variables
unsigned long now = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;
boolean motion = false;
// Checks if motion was detected, sets LED on HIGH, and starts a timer
void IRAM_ATTR detectsMovement(){
digitalWrite(LED, HIGH);
startTimer = true;
lastTrigger = millis();
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(motionSensor, INPUT_PULLUP);
// Set motionSensor pin as interrupt, assign interrupt function, and set RISING mode
attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);
// Set LED to LOW
pinMode(LED, OUTPUT);
pinMode(LED, LOW);
}
void loop() {
// Current time
now = millis();
if((digitalRead(LED)==HIGH) && (motion==false)){
Serial.println("MOTION DETECTED");
motion=true;
}
// Turn off LED after the number of seconds defined in timeSeconds
if(startTimer && ((now-lastTrigger)>(timeSeconds*1000))){
Serial.println("MOTION STOPPED");
digitalWrite(LED, LOW);
startTimer=false;
motion=false;
}
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}
Loading
esp32-devkit-v1
esp32-devkit-v1