Facebook
From Idiotic Owl, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 970
  1. #include <ESP8266WiFi.h>
  2.  
  3. const char* ssid = "internet";//type your ssid
  4. const char* password = "123456789";//type your password
  5.  
  6. int ledPin = 2; // GPIO2 of ESP8266
  7. WiFiServer server(80);//Service Port
  8.  
  9. void setup() {
  10. Serial.begin();
  11. delay(10);
  12.  
  13. pinMode(ledPin, OUTPUT);
  14. digitalWrite(ledPin, LOW);
  15.  
  16. // Connect to WiFi network
  17. Serial.println();
  18. Serial.println();
  19. Serial.print("Connecting to ");
  20. Serial.println(ssid);
  21.  
  22. WiFi.begin(ssid, password);
  23.  
  24. while (WiFi.status() != WL_CONNECTED) {
  25. delay(500);
  26. Serial.print(".");
  27. }
  28. Serial.println("");
  29. Serial.println("WiFi connected");
  30.  
  31. // Start the server
  32. server.begin();
  33. Serial.println("Server started");
  34.  
  35. // Print the IP address
  36. Serial.print("Use this URL to connect: ");
  37. Serial.print("http://");
  38. Serial.print(WiFi.localIP());
  39. Serial.println("/");
  40. }
  41.  
  42. void loop() {
  43. // Check if a client has connected
  44. WiFiClient client = server.available();
  45. if (!client) {
  46. return;
  47. }
  48.  
  49. // Wait until the client sends some data
  50. Serial.println("new client");
  51. while(!client.available()){
  52. delay(1);
  53. }
  54.  
  55. // Read the first line of the request
  56. String request = client.readStringUntil('\r');
  57. Serial.println(request);
  58. client.flush();
  59.  
  60. // Match the request
  61.  
  62. int value = LOW;
  63. if (request.indexOf("/LED=ON") != -1) {
  64. digitalWrite(ledPin, HIGH);
  65. value = HIGH;
  66. }
  67. if (request.indexOf("/LED=OFF") != -1){
  68. digitalWrite(ledPin, LOW);
  69. value = LOW;
  70. }
  71.  
  72. //Set ledPin according to the request
  73. //digitalWrite(ledPin, value);
  74.  
  75. // Return the response
  76. client.println("HTTP/1.1 200 OK");
  77. client.println("Content-Type: text/html");
  78. client.println(""); //  do not forget this one
  79. client.println("<!DOCTYPE HTML>");
  80. client.println("<html>");
  81.  
  82. client.print("Led pin is now: ");
  83.  
  84. if(value == HIGH) {
  85. client.print("On");  
  86. } else {
  87. client.print("Off");
  88. }
  89. client.println("<br><br>");
  90. client.println("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 2 ON<br>");
  91. client.println("Click <a href=\"/LED=OFF\">here turn the LED on pin 2 OFF<br>");
  92. client.println("</html>");
  93.  
  94. delay(1);
  95. Serial.println("Client disconnected");
  96. Serial.println("");
  97. }