Optional ESP32 Implementation (PIR)
Optional ESP32 Implementation (PIR)
animation
sensors
NoteOptional ESP32 Implementation
This example reads the sensor and reports its output. Use it after checking the wiring, then compare the reported values with the physical test described above.
#define PIR_PIN 13 // GPIO13 for PIR sensor
bool motionDetected = false;
unsigned long lastMotionTime = 0;
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
Serial.println("PIR Motion Sensor Test");
Serial.println("Warming up sensor (30-60 seconds)...");
delay(60000); // PIR needs 30-60s warm-up time
Serial.println("Ready!");
}
void loop() {
int pirState = digitalRead(PIR_PIN);
if (pirState == HIGH) {
if (!motionDetected) {
motionDetected = true;
lastMotionTime = millis();
Serial.println("MOTION DETECTED!");
Serial.print("Time: ");
Serial.println(millis() / 1000);
// Trigger action (turn on light, send alert, etc.)
digitalWrite(LED_BUILTIN, HIGH);
}
} else {
if (motionDetected) {
unsigned long motionDuration = (millis() - lastMotionTime) / 1000;
Serial.print("Motion ended. Duration: ");
Serial.print(motionDuration);
Serial.println(" seconds");
motionDetected = false;
digitalWrite(LED_BUILTIN, LOW);
}
}
delay(100);
}