Course Content
IoT Engineering Course using ESP32 with 12 Real-World Projects

📘 Home Security Code 


🎯 Objective of This Lesson

Students will learn:

  • How to read digital input from PIR

  • How to detect motion

  • How to print status on Serial Monitor

  • How basic intrusion detection logic works


🔌 Hardware Reminder

PIR Pin ESP32 Pin
VCC 5V
GND GND
OUT GPIO 27

🧾 Complete ESP32 Code (Copy–Paste Ready)

#define PIR_PIN 27 // PIR OUT connected to GPIO 27

int motionState = 0;
int lastState = 0;

void setup() {

Serial.begin(115200);
pinMode(PIR_PIN, INPUT);

Serial.println("Home Security System Started...");
Serial.println("Warming up PIR Sensor...");
delay(30000); // 30 seconds warm-up
Serial.println("System Ready!");
}

void loop() {

motionState = digitalRead(PIR_PIN);

if (motionState == HIGH && lastState == LOW) {
Serial.println("⚠ MOTION DETECTED! Intruder Alert!");
lastState = HIGH;
}

else if (motionState == LOW && lastState == HIGH) {
Serial.println("Area Clear - No Motion");
lastState = LOW;
}

delay(200);
}

🧠 Code Explanation (Step-by-Step)


1️⃣ Define PIR Pin

 
#define PIR_PIN 27
 

This tells ESP32 that PIR OUT is connected to GPIO 27.


2️⃣ Motion Variables

 
int motionState = 0;
int lastState = 0;
 
  • motionState → Current PIR reading

  • lastState → Previous PIR reading

Why we use this?

To avoid repeated printing of same message.


3️⃣ Serial Communication

 
Serial.begin(115200);
 

Used to display output in Serial Monitor.


4️⃣ Warm-Up Time

 
delay(30000);
 

PIR needs 30 seconds to stabilize.

Without this:

  • False triggers may occur.


5️⃣ Reading PIR Output

 
motionState = digitalRead(PIR_PIN);
 

Returns:

HIGH → Motion detected
LOW → No motion


6️⃣ Motion Detection Logic

 
if (motionState == HIGH && lastState == LOW)
 

This means:

Motion just started.

Print:

⚠ MOTION DETECTED! Intruder Alert!

Then update lastState.


7️⃣ Motion End Detection

 
else if (motionState == LOW && lastState == HIGH)
 

This means:

Motion stopped.

Print:

Area Clear – No Motion


8️⃣ Why Use lastState?

Without it:

Serial Monitor would continuously print:

MOTION DETECTED
MOTION DETECTED
MOTION DETECTED

Using state comparison makes system professional.


📊 Example Serial Monitor Output

System start:

Home Security System Started
Warming up PIR Sensor…
System Ready!

When someone walks:

⚠ MOTION DETECTED! Intruder Alert!

When movement stops:

Area Clear – No Motion


🎓 Learning Outcomes

After this lesson, students understand:

  • Digital sensor reading

  • HIGH vs LOW logic

  • State change detection

  • Intrusion detection programming

  • Basic security system design



Scroll to Top