#include <Arduino.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/queue.h>
#include <DHTesp.h>
#include <LiquidCrystal_I2C.h>
#define DHT_PIN 23 // Pin của cảm biến DHT22
#define LDR_PIN 34 // Pin của cảm biến LDR
#define LED_PIN 18 // Pin của LED
// Queue để truyền dữ liệu nhiệt độ và độ ẩm
QueueHandle_t sensorQueue;
// Task 1: Đọc dữ liệu từ cảm biến DHT22
void task1(void *parameter) {
DHTesp dht;
dht.setup(DHT_PIN, DHTesp::DHT22);
while (true) {
TempAndHumidity data = dht.getTempAndHumidity();
Serial.print("Temp: ");
Serial.print(data.temperature);
Serial.print(" °C, Humidity: ");
Serial.print(data.humidity);
Serial.println(" %");
// Gửi dữ liệu vào Queue
if (xQueueSend(sensorQueue, &data, portMAX_DELAY) != pdTRUE) {
Serial.println("Failed to send data to queue");
}
vTaskDelay(2000 / portTICK_PERIOD_MS); // Đợi 2 giây trước khi đọc lại
}
}
// Task 2: Hiển thị dữ liệu lên LCD
void task2(void *parameter) {
LiquidCrystal_I2C lcd(0x27, 16, 2);
lcd.init();
lcd.backlight();
TempAndHumidity data;
while (true) {
// Nhận dữ liệu từ Queue
if (xQueueReceive(sensorQueue, &data, portMAX_DELAY) == pdTRUE) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(data.temperature);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Hum: ");
lcd.print(data.humidity);
lcd.print(" %");
}
}
}
// Task 3: Đọc dữ liệu từ cảm biến ánh sáng và điều khiển LED
void task3(void *parameter) {
while (true) {
int ldrValue = analogRead(LDR_PIN);
Serial.print("LDR Value: ");
Serial.println(ldrValue);
// Kiểm tra giá trị ánh sáng và bật/tắt LED
if (ldrValue < 1000) { // Mức ánh sáng thấp hơn 1000 Lux
digitalWrite(LED_PIN, HIGH); // Bật LED
Serial.println("LED ON");
} else {
digitalWrite(LED_PIN, LOW); // Tắt LED
Serial.println("LED OFF");
}
vTaskDelay(1000 / portTICK_PERIOD_MS); // Đợi 1 giây trước khi kiểm tra lại
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
// Tạo Queue
sensorQueue = xQueueCreate(5, sizeof(TempAndHumidity));
// Tạo Tasks
xTaskCreate(task1, "Task 1", 2048, NULL, 1, NULL);
xTaskCreate(task2, "Task 2", 2048, NULL, 1, NULL);
xTaskCreate(task3, "Task 3", 2048, NULL, 1, NULL);
}
void loop() {
// Loop trống vì FreeRTOS đã quản lý tasks
}