Difficulty Level: Intermediate
This tutorial guides you through building a simple home security system using NodeMCU. The system will include a motion sensor and send notifications via email or a web interface when motion is detected.
Connect the PIR motion sensor to the NodeMCU as follows:
1. Open the Arduino IDE and ensure you have the ESP8266 board definitions installed.
2. Load the following code onto your NodeMCU:
#include#include #include const char* ssid = "YOUR_SSID"; // Replace with your Wi-Fi SSID const char* password = "YOUR_PASSWORD"; // Replace with your Wi-Fi Password const int pirPin = D1; // PIR motion sensor pin const int buzzerPin = D2; // Buzzer pin (optional) ESP8266WebServer server(80); void setup() { Serial.begin(115200); pinMode(pirPin, INPUT); pinMode(buzzerPin, OUTPUT); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); // Setup server routes server.on("/", handleRoot); server.begin(); } void loop() { server.handleClient(); int motionState = digitalRead(pirPin); if (motionState == HIGH) { Serial.println("Motion detected!"); digitalWrite(buzzerPin, HIGH); // Activate buzzer sendNotification(); // Call notification function delay(5000); // Delay to avoid multiple triggers digitalWrite(buzzerPin, LOW); // Deactivate buzzer } } void handleRoot() { String message = " Home Security System
"; message += "Motion Sensor Status: " + String(digitalRead(pirPin)) + "
"; server.send(200, "text/html", message); } void sendNotification() { // Implement your email notification or webhook here Serial.println("Sending notification..."); // Code to send email or notification can be added here }
1. Select the appropriate board and port in the Arduino IDE.
2. Click on the upload button to upload the code to the NodeMCU.
1. Open the Serial Monitor to view the NodeMCU's IP address once it's connected to Wi-Fi.
2. Open a web browser and enter the NodeMCU's IP address.
3. The page should display the current status of the motion sensor.
You have successfully set up a basic home security system using NodeMCU and a PIR motion sensor. You can expand this project by integrating additional sensors or implementing more advanced notification systems.