Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.2 kB
5
Indexable
Never
#include <ESP8266WiFi.h>

WiFiClient client;
WiFiServer server(80);
int relay = 5;
int pir = 14;

#define pir D5

void setup() 
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  WiFi.begin("treako", "wifi9718");
  while(WiFi.status() != WL_CONNECTED)
  {
    delay(200);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("NodeMCU is connected!");
  Serial.println(WiFi.localIP());
  server.begin();
  pinMode(pir, INPUT);   // declare sensor as input
  pinMode(relay, OUTPUT);  // declare LED as output
}

void loop() 
{
  // put your main code here, to run repeatedly:
  client = server.available();  //Gets a client that is connected to the server and has data available for reading.    
  if (client == 1)
  {  
    String request =  client.readStringUntil('\n');
    Serial.println(request);
    request.trim();
    long state = digitalRead(pir);
    if(state == HIGH) {
      digitalWrite (relay, LOW);
      Serial.println("Motion detected!");
      delay(2000);
    }
    if(request == "GET /ledon HTTP/1.1")
    {
      digitalWrite(relay, LOW);
    }
    if(request == "GET /ledoff HTTP/1.1" && state==LOW)
    {
      digitalWrite(relay, HIGH);
    }
    else{
      digitalWrite(relay, HIGH);
    }
  }
}