Advertisement
vitareinforce

ISP8266

Jun 5th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. /*
  2. * This sketch demonstrates how to set up a simple HTTP-like server.
  3. * The server will set a GPIO pin depending on the request
  4. * http://server_ip/led/0 will set the GPIO2 low,
  5. * http://server_ip/led/1 will set the GPIO2 high
  6. * server_ip is the IP address of the ESP8266 module, will be
  7. * printed to Serial when the module is connected.
  8. */
  9.  
  10. #include <ESP8266WiFi.h>
  11.  
  12. const char* ssid = "LSKK_AP_Meeting";
  13. const char* password = "lskkpelajarpejuang";
  14.  
  15. // Create an instance of the server
  16. // specify the port to listen on as an argument
  17. WiFiServer server(80);
  18. int ledPin = 13;
  19.  
  20. void setup() {
  21. Serial.begin(115200);
  22. delay(10);
  23.  
  24. // prepare GPIO2
  25. pinMode(ledPin, OUTPUT);
  26. digitalWrite(ledPin, 0);
  27.  
  28. // Connect to WiFi network
  29. Serial.println();
  30. Serial.println();
  31. Serial.print("Connecting to ");
  32. Serial.println(ssid);
  33.  
  34. WiFi.begin(ssid, password);
  35.  
  36. while (WiFi.status() != WL_CONNECTED) {
  37. delay(500);
  38. Serial.print(".");
  39. }
  40. Serial.println("");
  41. Serial.println("WiFi connected");
  42.  
  43. // Start the server
  44. server.begin();
  45. Serial.println("Server started");
  46.  
  47. // Print the IP address
  48. Serial.println(WiFi.localIP());
  49. }
  50.  
  51. void loop() {
  52. // Check if a client has connected
  53. WiFiClient client = server.available();
  54. if (!client) {
  55. return;
  56. }
  57.  
  58. // Wait until the client sends some data
  59. Serial.println("new client");
  60. while(!client.available()){
  61. delay(1);
  62. }
  63.  
  64. // Read the first line of the request
  65. String req = client.readStringUntil('\r');
  66. Serial.println(req);
  67. client.flush();
  68.  
  69. // Match the request
  70. int val;
  71. if (req.indexOf("/led/0") != -1) // led=on
  72. val = 0;
  73. else if (req.indexOf("/led/1") != -1)
  74. val = 1;
  75. else {
  76. Serial.println("invalid request");
  77. client.stop();
  78. return;
  79. }
  80.  
  81. // Set GPIO2 according to the request
  82. digitalWrite(ledPin, val);
  83.  
  84. client.flush();
  85.  
  86. // Return the response
  87. client.println("HTTP/1.1 200 OK");
  88. client.println("Content-Type: text/html");
  89. client.println(""); // do not forget this one
  90. client.print("Led pin is now: ");
  91.  
  92. if(val == 1) {
  93. client.print("On");
  94. } else {
  95. client.print("Off");
  96. }
  97. Serial.println("Client disonnected");
  98.  
  99. // The client will actually be disconnected
  100. // when the function returns and 'client' object is detroyed
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement