#include "DHTesp.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h> // Library for I2C LCD
// Pin definitions
const int DHT_PIN = 15;
const int SDA_PIN = 18;
const int SCL_PIN = 5;
// DHT sensor object
DHTesp dhtSensor;
// LCD object
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set I2C address for a 16x2 LCD
// Shared variables
float temperature = 0.0;
float humidity = 0.0;
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
Wire.begin(SDA_PIN, SCL_PIN);
lcd.init();
lcd.backlight();
// Create tasks
xTaskCreatePinnedToCore(
TaskDHT, // Function to implement the task
"TaskDHT", // Name of the task
1024, // Stack size in words
NULL, // Task input parameter
1, // Priority of the task
NULL, // Task handle
0); // Core where the task should run
xTaskCreatePinnedToCore(
TaskLCD,
"TaskLCD",
2048,
NULL,
1,
NULL,
0);
}
void loop() {
// No code in the loop as we are using FreeRTOS tasks
}
// Task to read temperature and humidity
void TaskDHT(void *pvParameters) {
for(;;) {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
temperature = data.temperature;
humidity = data.humidity;
vTaskDelay(2000); // Wait for a new reading from the sensor (DHT22 has ~0.5Hz sample rate)
}
}
// Task to display temperature and humidity on LCD
void TaskLCD(void *pvParameters) {
for(;;) {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Temp: " + String(temperature, 1) + " C");
lcd.setCursor(0,1);
lcd.print("Hum : " + String(humidity, 1) + " %");
vTaskDelay(2000);
}
}