#include <Arduino.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
// Define pin constants
#define DHTPIN 4 // Pin cho DHT11
#define LDR_PIN A0 // Pin cho cảm biến ánh sáng
#define LIGHT_THRESHOLD 1000 // Ngưỡng ánh sáng
#define Led_PIN 16
// Initialize DHT11
DHT dht(DHTPIN, DHT11);
// Initialize LCD I2C
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Queue để lưu dữ liệu nhiệt độ
QueueHandle_t tempQueue;
// Task Handle
TaskHandle_t Task1Handle;
TaskHandle_t Task2Handle;
TaskHandle_t Task3Handle;
void setup() {
Serial.begin(9600);
dht.begin();
lcd.begin();
lcd.backlight(); // Bật đèn nền LCD
pinMode(Led_PIN, OUTPUT);
// Tạo Queue với kích thước tối đa là 5
tempQueue = xQueueCreate(5, sizeof(float));
if (tempQueue == NULL) {
Serial.println("Failed to create queue.");
while (1); // Loop indefinitely if queue creation fails
}
// Tạo các task
xTaskCreate(Task1, "Read Temp", 1000, NULL, 1, &Task1Handle);
xTaskCreate(Task2, "Display Temp", 1000, NULL, 1, &Task2Handle);
xTaskCreate(Task3, "Check Light", 1000, NULL, 1, &Task3Handle);
}
void loop() {
}
void Task1(void *pvParameters) {
while (1) {
// Đọc nhiệt độ từ cảm biến DHT11
float temperature = dht.readTemperature();
if (!isnan(temperature)) {
// Gửi dữ liệu vào Queue
xQueueSend(tempQueue, &temperature, portMAX_DELAY);
} else {
Serial.println("Failed to read temperature.");
}
vTaskDelay(2000 / portTICK_PERIOD_MS); // Đọc mỗi 2 giây
}
}
void Task2(void *pvParameters) {
float receivedTemp;
while (1) {
// Nhận dữ liệu từ Queue
if (xQueueReceive(tempQueue, &receivedTemp, portMAX_DELAY)) {
// Hiển thị lên LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(receivedTemp);
lcd.print(" C");
}
vTaskDelay(1000 / portTICK_PERIOD_MS); // Cập nhật mỗi giây
}
}