#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
#include <DHT.h>
#define TFT_CS 5
#define TFT_RST 16
#define TFT_DC 17
#define DHT_PIN 12 // Pin connected to DHT22 sensor
#define RELAY_PIN 14 // Pin connected to relay
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHT_PIN, DHTTYPE);
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
// Initialize TFT display
tft.begin();
tft.setRotation(4); // Rotate screen 90 degrees
// Set background color
tft.fillScreen(ILI9341_BLACK); // Set background color to white
// Set text size
tft.setTextSize(2);
// Draw title
tft.setTextColor(ILI9341_WHITE);
tft.setCursor(10, 10);
tft.println("Temperature Control");
// Draw top border
tft.drawRect(0, 0, tft.width(), 20, ILI9341_WHITE);
// Initialize DHT sensor
dht.begin();
}
void loop() {
// Read temperature from DHT sensor
float temperature = dht.readTemperature();
// Check if temperature is valid
if (!isnan(temperature)) {
// Print temperature to serial monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
// Turn on relay if temperature is lower than 20°C
if (temperature < 20) {
digitalWrite(RELAY_PIN, HIGH);
Serial.println("Relay: ON");
drawRelayStatus(true); // Draw relay status on TFT display (ON)
} else {
digitalWrite(RELAY_PIN, LOW);
Serial.println("Relay: OFF");
drawRelayStatus(false); // Draw relay status on TFT display (OFF)
}
// Draw temperature on TFT display
drawTemperature(temperature);
} else {
Serial.println("Failed to read temperature from DHT sensor");
}
delay(2000); // Wait 2 seconds before next reading
}
void drawTemperature(float temp) {
// Clear previous temperature
tft.fillRect(0, 30, 240, 30, ILI9341_BLACK); // Clear temperature area
// Draw current temperature
tft.setTextColor(ILI9341_WHITE);
tft.setCursor(10, 40);
tft.setTextSize(2);
tft.print("Temp: ");
tft.print(temp);
tft.println("C");
}
void drawRelayStatus(bool isOn) {
// Clear previous relay status
tft.fillRect(0, 80, 240, 30, ILI9341_BLACK); // Clear relay status area
// Set text color
tft.setTextColor(isOn ? ILI9341_GREEN : ILI9341_RED); // Green if ON, red if OFF
// Draw current relay status
tft.setCursor(30, 90);
tft.setTextSize(3);
tft.print("Relay: ");
tft.println(isOn ? "ON" : "OFF");
}
Loading
ili9341-cap-touch
ili9341-cap-touch