//when motoin is detected light will be on in a room or else the light will be off.
#include <WiFi.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const int relayPin = 4; // Pin connected to the relay module
const int motionSensorPin = 2; // Pin connected to the motion sensor
WiFiServer server(80);
void setup() {
Serial.begin(115200);
pinMode(relayPin, OUTPUT);
pinMode(motionSensorPin, INPUT);
// Connect to Wi-Fi
Serial.println();
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available(); // Check if a client has connected
if (client) { // If a client has connected
Serial.println("New client connected");
String currentLine = ""; // Make a String to hold incoming data
while (client.connected()) { // Loop while the client is connected
if (client.available()) { // If data is available to read
char c = client.read(); // Read a character
Serial.write(c); // Print it out to the serial monitor
if (c == '\n') { // If the character is a newline character
// If the current line is blank, you got two newline characters in a row
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// Display the HTML web page
client.println("<html><head><title>Home Automation</title></head><body>");
client.println("<h1>Home Automation</h1>");
client.println("<h2>Motion Detection</h2>");
client.println("<p>Click the button to simulate motion detection:</p>");
client.println("<form action=\"/motion\" method=\"get\"><button type=\"submit\">Trigger Motion</button></form>");
client.println("</body></html>");
// The HTTP response ends with another blank line:
client.println();
// Break out of the while loop
break;
} else { // If you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // If you got anything else but a carriage return character
currentLine += c; // Add it to the end of the currentLine
}
}
}
// Clear the header variable
currentLine = "";
// Close the connection
client.stop();
Serial.println("Client disconnected");
}
// Check for motion
bool motionDetected = digitalRead(motionSensorPin);
if (motionDetected) {
// Turn on the relay to activate home automation
digitalWrite(relayPin, HIGH);
Serial.println("Motion detected! Turning on lights.");
delay(5000); // Simulate lights being on for 5 seconds
digitalWrite(relayPin, LOW);
Serial.println("Lights turned off.");
}
delay(1000); // Check for motion every second
}