nht_cntt

ESP8266 send to server

Apr 3rd, 2018
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <ESP8266WiFi.h>
  3. #include <ESP8266HTTPClient.h>
  4.  
  5. const char* ssid = "nhtcntt";
  6. const char* pass = "123456789";
  7. String URL = "http://192.168.123.1:80/update";
  8.  
  9. void SendInfo2Server(float Nhietdo, float DoAm);
  10.  
  11. void setup() {
  12.     Serial.begin(115200);
  13.     Serial.print("Connectting to");
  14.     Serial.println(ssid);
  15.     WiFi.mode(WIFI_STA);
  16.     WiFi.begin(ssid, pass);
  17.     while( WiFi.status() != WL_CONNECTED)
  18.     {
  19.         delay(2000);
  20.         Serial.println("Failed - Try connect");
  21.     }    
  22.     Serial.println("WiFi connected");
  23.     Serial.print("IP address: ");
  24.     Serial.println(WiFi.localIP());
  25.     Serial.print("MAC: ");
  26.     Serial.println(WiFi.macAddress());
  27.  
  28. }
  29.  
  30. void loop()
  31. {
  32.     SendInfo2Server(10.20, 10.10);
  33.  
  34. }
  35.  
  36. /*
  37.  URL: http://IPorName:80/update
  38.  method: POST
  39.  http header:
  40.              User-Agent: MAC Address
  41.              Content-Type: application/json
  42.              Content-Length: length(http body)
  43.              Connection: close
  44.  http body:  
  45.              {
  46.                  "nhietdo" : float,
  47.                  "doam"    : float
  48.              }
  49. */
  50.  
  51. void SendInfo2Server(float Nhietdo, float DoAm)
  52. {
  53.     HTTPClient http;
  54.     http.begin(URL);
  55.     http.addHeader("Content-Type", "application/json");
  56.     http.setUserAgent(WiFi.macAddress());
  57.     int statuscode = http.POST("{\"nhietdo\" : " + String(Nhietdo) + ", \"doam\" : \"" + String(DoAm) + "%\"}");
  58.     if(statuscode > 0)
  59.     {
  60.         String payload = http.getString();
  61.         Serial.print("payload: ");
  62.         Serial.println(payload);
  63.     }
  64.     http.end();
  65.     delay(5000);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment