#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include "UI.h"
#include <Arduino_FreeRTOS.h>
#include <DHT.h>
#define SWITCH_BUTTON 3
#define HEATER_POT_PIN A6
#define TEMP_POT_PIN A7
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
int heaterPotVal = 0, lastHeaterPotVal = -1;
int tempPotVal = 0, lastTempPotVal = -1;
int switchState = 0, lastSwitchState = -1;
int isAutomatic = 1;
float temperature = 0.0;
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
// Task handles
TaskHandle_t uiUpdateTaskHandle;
TaskHandle_t tempReadTaskHandle;
// Function to initialize display
void setupDisplay() {
tft.begin();
drawButtons();
pinMode(SWITCH_BUTTON, INPUT);
}
// FreeRTOS task to handle input and update the UI
void uiUpdateTask(void *pvParameters) {
Serial.println("UI Task Running");
while (true) {
// Read inputs
heaterPotVal = analogRead(HEATER_POT_PIN);
tempPotVal = analogRead(TEMP_POT_PIN);
switchState = digitalRead(SWITCH_BUTTON);
// Update ModeText if switch state changes
if (switchState != lastSwitchState) {
lastSwitchState = switchState;
if (switchState == 1) {
if (ModeText.text == "Mode: Automatic") {
ModeText.changeText("Mode: Manual");
isAutomatic = 0;
} else {
ModeText.changeText("Mode: Automatic");
isAutomatic = 1;
}
}
}
// Update HeaterText if the heater pot value changes significantly
if (abs(heaterPotVal - lastHeaterPotVal) > 5 && isAutomatic == 0) {
lastHeaterPotVal = heaterPotVal;
HeaterText.changeText("Heater Power: " + String(heaterPotVal / 100));
}
// Update TempText if the temp pot value changes significantly
if (abs(tempPotVal - lastTempPotVal) > 5 && isAutomatic == 1) {
lastTempPotVal = tempPotVal;
TempText.changeText("Temperature: " + String(tempPotVal / 30));
}
// Add a short delay to avoid excessive CPU usage
vTaskDelay(pdMS_TO_TICKS(200));
}
}
// FreeRTOS task to read temperature and humidity from the DHT sensor
void tempReadTask(void *pvParameters) {
while (true) {
temperature = dht.readTemperature();
// Check if reading is valid
if (isnan(temperature) ) {
Serial.println("Failed to read from DHT sensor!");
} else {
// Update UI elements if required
Serial.print("Temperature: ");
Serial.print(temperature);
RoomTempText.changeText("Room Temperature: " + String(temperature) + "°C");
}
// Wait 2 seconds between readings
vTaskDelay(pdMS_TO_TICKS(200));
}
}
void setup() {
Serial.begin(115200);
// Initialize DHT sensor
dht.begin();
// Initialize display and create UI
setupDisplay();
// Create tasks
// xTaskCreate(uiUpdateTask, "UI Update", 100, NULL, 1, &uiUpdateTaskHandle);
xTaskCreate(tempReadTask, "Temp Read", 500, NULL, 1, &tempReadTaskHandle);
// Start the FreeRTOS scheduler
vTaskStartScheduler();
}
void loop() {
// Let FreeRTOS handle the scheduling. Leave this empty.
}
Loading
ili9341-cap-touch
ili9341-cap-touch