Advertisement
Guest User

ESP 8266 / DHT22 simple webserver

a guest
Dec 16th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include "DHT.h"
  2. #include <ESP8266WiFi.h>
  3. #include <ESP8266WebServer.h>
  4.  
  5. #define DHTPIN 5
  6. #define DHTTYPE DHT22
  7. #define RATE 115200
  8. #define DEBUG true
  9.  
  10. #define SSID "szvsyGm6E74c6HnevvfBHuuY6NG3otjOyxBpEyb9"
  11. #define PASS "szvsyGm6E74c6HnevvfBHuuY6NG3otjOyxBpEyb9"
  12.  
  13. DHT myDht(DHTPIN, DHTTYPE);
  14. ESP8266WebServer server(80);
  15.  
  16. void setup() {
  17.   myDht.begin();
  18.   if (DEBUG == true) {
  19.     Serial.begin(RATE);
  20.     Serial.println("");
  21.     Serial.println("Connecting to WiFI");
  22.   }
  23.  
  24.   WiFi.begin(SSID, PASS);
  25.  
  26.   while (WiFi.status() != WL_CONNECTED) {
  27.     delay(10);
  28.     if (DEBUG == true) {
  29.       Serial.print(".");
  30.     }
  31.   }
  32.   if (DEBUG == true) {
  33.     Serial.println("");
  34.     Serial.println("Connected");
  35.     Serial.println(WiFi.localIP());
  36.   }
  37.  
  38.   server.on("/measurement", HTTP_GET, returnMeasurement);    
  39.   server.begin();
  40.   if (DEBUG == true) {
  41.     Serial.println("HTTP server started");
  42.   }
  43. }
  44.  
  45. void returnMeasurement() {
  46.   if (DEBUG == true) {
  47.     Serial.println("GET on /measurement");
  48.   }
  49.   float temperature = myDht.readTemperature();
  50.   float humidity    = myDht.readHumidity();
  51.   float heatIndex   = myDht.computeHeatIndex(temperature, humidity, false);
  52.   String json       = "{\"temperature\":" + String(temperature) + ",\"humidity\":" + String(humidity) + ",\"heatIndex\":" + String(heatIndex) + "}";
  53.   server.send(200, "application/json", json);
  54. }
  55.  
  56. void loop() {
  57.   server.handleClient();
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement