#include "DHTesp.h" // Click here to get the library: http://librarymanager/All#DHTesp #include #ifndef ESP32 #pragma message(THIS EXAMPLE IS FOR ESP32 ONLY!) #error Select ESP32 board. #endif DHTesp dht; void tempTask(void *pvParameters); bool getTemperature(); void triggerGetTemp(); TaskHandle_t tempTaskHandle = NULL; Ticker tempTicker; ComfortState cf; bool tasksEnabled = false; int dhtPin = 22; bool initTemp() { byte resultValue = 0; // Initialize temperature sensor dht.setup(dhtPin, DHTesp::DHT11); Serial.println("DHT initiated"); // Start task to get temperature 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 */ if (tempTaskHandle == NULL) { Serial.println("Failed to start task for temperature update"); return false; } else { // Start update of environment data every 20 seconds tempTicker.attach(1, triggerGetTemp); } return true; } void triggerGetTemp() { if (tempTaskHandle != NULL) { xTaskResumeFromISR(tempTaskHandle); } } void tempTask(void *pvParameters) { Serial.println("tempTask loop started"); while (1) // tempTask loop { if (tasksEnabled) { // Get temperature values getTemperature(); } // Got sleep again vTaskSuspend(NULL); } } bool getTemperature() { // Reading temperature for humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor) TempAndHumidity newValues = dht.getTempAndHumidity(); // Check if any reads failed and exit early (to try again). if (dht.getStatus() != 0) { Serial.println("DHT11 error status: " + String(dht.getStatusString())); return false; } float heatIndex = dht.computeHeatIndex(newValues.temperature, newValues.humidity); float dewPoint = dht.computeDewPoint(newValues.temperature, newValues.humidity); float cr = dht.getComfortRatio(cf, newValues.temperature, newValues.humidity); Serial.println(" อุณหภูมิ : " + String(newValues.temperature) + " °C " + " ความชื้น : " + String(newValues.humidity) + " %"); return true; } void setup() { Serial.begin(115200); Serial.println(); Serial.println("DHT ESP32 example with tasks"); initTemp(); // Signal end of setup() to tasks tasksEnabled = true; } void loop() { if (!tasksEnabled) { // Wait 2 seconds to let system settle down delay(2000); // Enable task that will read values from the DHT sensor tasksEnabled = true; if (tempTaskHandle != NULL) { vTaskResume(tempTaskHandle); } } yield(); }