Skip to content

Instantly share code, notes, and snippets.

@santolucito
Created March 22, 2021 14:00
Show Gist options
  • Save santolucito/9190ebd85c56f16d47ef32f72e5510cd to your computer and use it in GitHub Desktop.
Save santolucito/9190ebd85c56f16d47ef32f72e5510cd to your computer and use it in GitHub Desktop.
DHT-11 w/ ESP32
// DHT Temperature & Humidity Sensor
// Unified Sensor Library Example
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Ticker.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#define DHTPIN 14
#define DHTTYPE DHT11 // DHT 11
DHT_Unified dht(DHTPIN, DHTTYPE);
/** Task handle for the light value read task */
TaskHandle_t tempTaskHandle = NULL;
/** Ticker for temperature reading */
Ticker tempTicker;
/** Flag if task should run */
bool tasksEnabled = false;
uint32_t delayMS;
String tempVal = "";
String humidVal = "";
// network to connect to
const char* ssid = "Milstein505";
const char* password = "6=458M5n";
WebServer server(8877);
void setup() {
Serial.begin(9600);
// Initialize device.
dht.begin();
sensor_t sensor;
dht.temperature().getSensor(&sensor);
// Set delay between sensor readings based on sensor details.
delayMS = sensor.min_delay / 1000;
xTaskCreatePinnedToCore(
tempTask, /* Function to implement the task */
"tempTask ", /* Name of the task */
4000, /* Stack size in words */
NULL, /* Task input parameter */
5, /* Priority of the task */
&tempTaskHandle, /* Task handle. */
1); /* Core where the task should run */
Serial.println("created task");
if (tempTaskHandle == NULL) {
Serial.println("Failed to start task for temperature update");
} else {
// Start update of environment data every 4 seconds
tempTicker.attach(4, triggerGetTemp);
}
//setup wifi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
//go to this IP from another computer on the same network to see website
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp32")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/inline", []() {
server.send(200, "text/plain", "this works as well");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void handleRoot() {
String jsonVal = "{temp: " + tempVal + ", humidity: " + humidVal + "}";
server.send(200, "text/json", jsonVal);
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
/**
* triggerGetTemp
* Sets flag dhtUpdated to true for handling in loop()
* called by Ticker getTempTimer
*/
void triggerGetTemp() {
if (tempTaskHandle != NULL) {
xTaskResumeFromISR(tempTaskHandle);
}
}
/**
* Task to reads temperature from DHT11 sensor
* @param pvParameters
* pointer to task parameters
*/
void tempTask(void *pvParameters) {
Serial.println("tempTask loop started");
while (1) // tempTask loop
{
if (tasksEnabled) {
// Get temperature values
getTemperature();
}
// Got sleep again
vTaskSuspend(NULL);
}
}
/**
* getTemperature
* Reads temperature from DHT11 sensor
* @return bool
* true if temperature could be aquired
* false if aquisition failed
*/
bool getTemperature() {
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println(F("Error reading temperature!"));
return false;
}
else {
Serial.print(F("Temperature: "));
Serial.print(event.temperature);
Serial.println(F("°C"));
tempVal = String(event.temperature) + " °C";
}
// Get humidity event and print its value.
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println(F("Error reading humidity!"));
return false;
}
else {
Serial.print(F("Humidity: "));
Serial.print(event.relative_humidity);
Serial.println(F("%"));
humidVal = String(event.relative_humidity) + "%";
}
return true;
}
void loop() {
// Delay between measurements.
if (!tasksEnabled) {
// Enable task that will read values from the DHT sensor
tasksEnabled = true;
if (tempTaskHandle != NULL) {
vTaskResume(tempTaskHandle);
}
}
server.handleClient();
yield();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment