Skip to content

Instantly share code, notes, and snippets.

@lefuturiste
Created January 31, 2019 15:39
Show Gist options
  • Save lefuturiste/967cef44ae6935bd7429cc0e5a3b8fad to your computer and use it in GitHub Desktop.
Save lefuturiste/967cef44ae6935bd7429cc0e5a3b8fad to your computer and use it in GitHub Desktop.
A simple http server to get temperature and humidity with DHT-11 sensor and esp8266
#include <ESP8266WiFi.h>
#include "DHT.h"
#define DHTTYPE DHT11
const char* ssid = "xxx";
const char* password = "xxx";
WiFiServer server(80);
const int DHTPin = D8;
static char celsiusTemp[7];
static char humidityTemp[7];
DHT dht(DHTPin, DHTTYPE);
bool started = false;
void setup()
{
Serial.begin(9600);
delay(10);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
delay(500);
server.begin();
delay(500);
Serial.println(WiFi.localIP());
}
void loop()
{
if (started == false) {
delay(500);
dht.begin();
delay(500);
started = true;
}
WiFiClient client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
// we can't read the values for some reason
strcpy(celsiusTemp,"false");
strcpy(humidityTemp, "false");
} else {
float hic = dht.computeHeatIndex(t, h, false);
dtostrf(hic, 6, 2, celsiusTemp);
dtostrf(h, 6, 2, humidityTemp);
}
// Return JSON result to the client
client.print("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"temp\":");
client.print(celsiusTemp);
client.print(", \"humidity\": ");
client.print(humidityTemp);
client.println("}");
client.flush();
delay(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment