kle4ka

P2_ON_OFF_RELAY_WEB

Dec 4th, 2020
844
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. #include <WiFi.h>
  3.  
  4. const char* wifi_name = "Ilievi"; // Your Wifi network name here
  5. const char* wifi_pass = "Anton123";    // Your Wifi network password here
  6. WiFiServer server(80);    // Server will be at port 80
  7.  
  8. int relay_pin = 26;
  9.  
  10. void setup()
  11. {
  12.   Serial.begin (57600);
  13.   pinMode (relay_pin, OUTPUT);
  14.  
  15.   Serial.print ("Connecting to ");
  16.   Serial.print (wifi_name);
  17.   WiFi.begin (wifi_name, wifi_pass);     // Connecting to the wifi network
  18.  
  19.   while (WiFi.status() != WL_CONNECTED) // Waiting for the response of wifi network
  20.   {
  21.     delay (500);
  22.     Serial.print (".");
  23.   }
  24.   Serial.println("");
  25.   Serial.println("Connection Successful");
  26.   Serial.print("IP address: ");
  27.   Serial.println(WiFi.localIP());           // Getting the IP address
  28.   Serial.println("Type the above IP address into browser search bar");
  29.   server.begin();                           // Starting the server
  30. }
  31.  
  32. void loop()
  33. {
  34.   WiFiClient client = server.available();     //Checking if any client request is available or not
  35.   if (client)
  36.   {
  37.     boolean currentLineIsBlank = true;
  38.     String buffer = "";
  39.     while (client.connected())
  40.     {
  41.       if (client.available())                    // if there is some client data available
  42.       {
  43.         char c = client.read();
  44.         buffer += c;                            // read a byte
  45.         if (c == '\n' && currentLineIsBlank)    // check for newline character,
  46.         {
  47.           client.println("HTTP/1.1 200 OK");
  48.           client.println("Content-Type: text/html");
  49.           client.println();
  50.           client.print("<HTML><title>ESP32</title>");
  51.           client.print("<body><h1>ESP32 Standalone Relay Control </h1>");
  52.           client.print("<p>Relay Control</p>");
  53.           client.print("<a href=\"/?relayon\"\"><button>ON</button></a>");
  54.           client.print("<a href=\"/?relayoff\"\"><button>OFF</button></a>");
  55.           client.print("</body></HTML>");
  56.           break;        // break out of the while loop:
  57.         }
  58.         if (c == '\n') {
  59.           currentLineIsBlank = true;
  60.           buffer = "";
  61.         }
  62.         else if (c == '\r') {
  63.           if (buffer.indexOf("GET /?relayon") >= 0)
  64.             digitalWrite(relay_pin, LOW);
  65.           if (buffer.indexOf("GET /?relayoff") >= 0)
  66.             digitalWrite(relay_pin, HIGH);
  67.         }
  68.         else {
  69.           currentLineIsBlank = false;
  70.         }
  71.       }
  72.     }
  73.     client.stop();
  74.   }
  75. }
RAW Paste Data