iot_onoff.ino 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Simple HTTP get webclient test
  3. */
  4. #include <ESP8266WiFi.h>
  5. const char* ssid = "hazard18";
  6. const char* password = "pu1f0xylu1";
  7. const char* host = "192.168.1.97";
  8. void setup() {
  9. pinMode(0, OUTPUT);
  10. pinMode(4, INPUT);
  11. pinMode(A0, INPUT);
  12. Serial.begin(115200);
  13. delay(100);
  14. // We start by connecting to a WiFi network
  15. Serial.println();
  16. Serial.println();
  17. Serial.print("Connecting to ");
  18. Serial.println(ssid);
  19. WiFi.begin(ssid, password);
  20. while (WiFi.status() != WL_CONNECTED) {
  21. delay(500);
  22. Serial.print(".");
  23. }
  24. Serial.println("");
  25. Serial.println("WiFi connected");
  26. Serial.println("IP address: ");
  27. Serial.println(WiFi.localIP());
  28. }
  29. int value = 0;
  30. void loop() {
  31. delay(500);
  32. ++value;
  33. Serial.print("connecting to ");
  34. Serial.println(host);
  35. // Use WiFiClient class to create TCP connections
  36. WiFiClient client;
  37. const int httpPort = 8084;
  38. if (!client.connect(host, httpPort)) {
  39. Serial.println("connection failed");
  40. return;
  41. }
  42. // We now create a URI for the request
  43. int gpio4 = digitalRead(4);
  44. int gpioA0 = analogRead(A0);
  45. String url = "/gpio?status=" + String(gpio4) + "&a0=" + String(gpioA0);
  46. Serial.print("Requesting URL (" + String(value) + ")" + " : ");
  47. Serial.println(url);
  48. // This will send the request to the server
  49. client.print(String("GET ") + url + " HTTP/1.1\r\n" +
  50. "Host: " + host + "\r\n" +
  51. "Connection: close\r\n\r\n");
  52. delay(500);
  53. // Read all the lines of the reply from server and print them to Serial
  54. while(client.available()){
  55. String line = client.readStringUntil('\r');
  56. Serial.print(line);
  57. if (line.toInt() == 0){
  58. Serial.print("at 0");
  59. digitalWrite(0, LOW);
  60. }else{
  61. Serial.print("at 1");
  62. digitalWrite(0, HIGH);
  63. }
  64. }
  65. Serial.println();
  66. Serial.println("closing connection");
  67. }