Guest User

Untitled

a guest
Oct 31st, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 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/gpio/0 will set the GPIO2 low,
  5. * http://server_ip/gpio/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 = "your-ssid";
  13. const char* password = "your-password";
  14.  
  15. // Create an instance of the server
  16. // specify the port to listen on as an argument
  17. WiFiServer server(80);
  18.  
  19. void setup() {
  20. Serial.begin(115200);
  21. delay(10);
  22.  
  23. // prepare GPIO2
  24. pinMode(2, OUTPUT);
  25. digitalWrite(2, 0);
  26.  
  27. // Connect to WiFi network
  28. Serial.println();
  29. Serial.println();
  30. Serial.print("Connecting to ");
  31. Serial.println(ssid);
  32.  
  33. WiFi.begin(ssid, password);
  34.  
  35. while (WiFi.status() != WL_CONNECTED) {
  36. delay(500);
  37. Serial.print(".");
  38. }
  39. Serial.println("");
  40. Serial.println("WiFi connected");
  41.  
  42. // Start the server
  43. server.begin();
  44. Serial.println("Server started");
  45.  
  46. // Print the IP address
  47. Serial.println(WiFi.localIP());
  48. }
  49.  
  50. void loop() {
  51. // Check if a client has connected
  52. WiFiClient client = server.available();
  53. if (!client) {
  54. return;
  55. }
  56.  
  57. // Wait until the client sends some data
  58. Serial.println("new client");
  59. while(!client.available()){
  60. delay(1);
  61. }
  62.  
  63. // Read the first line of the request
  64. String req = client.readStringUntil('\r');
  65. Serial.println(req);
  66. client.flush();
  67.  
  68. // Match the request
  69. int val;
  70. if (req.indexOf("/gpio/0") != -1)
  71. val = 0;
  72. else if (req.indexOf("/gpio/1") != -1)
  73. val = 1;
  74. else {
  75. Serial.println("invalid request");
  76. client.stop();
  77. return;
  78. }
  79.  
  80. // Set GPIO2 according to the request
  81. digitalWrite(2, val);
  82.  
  83. client.flush();
  84.  
  85. // Prepare the response
  86. String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
  87. s += (val)?"high":"low";
  88. s += "</html>\n";
  89.  
  90. // Send the response to the client
  91. client.print(s);
  92. delay(1);
  93. Serial.println("Client disonnected");
  94.  
  95. // The client will actually be disconnected
  96. // when the function returns and 'client' object is detroyed
  97. }
Add Comment
Please, Sign In to add comment