#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <DHT.h>
// DHT sensor settings
#define DHTPIN 12 // let's move to GPIO12 to avoid conflicts
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// TFT display settings
#define TFT_CS 15
#define TFT_DC 2
#define TFT_RST 4
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
// Graph settings
#define GRAPH_WIDTH 250
#define GRAPH_HEIGHT 150
#define GRAPH_X 20
#define GRAPH_Y 50
#define MAX_POINTS 100
float temperatureData[MAX_POINTS];
float humidityData[MAX_POINTS];
int dataIndex = 0;
void setup() {
Serial.begin(115200);
// Important: Initialize SPI manually
SPI.begin(18, 19, 23, 15);
tft.begin();
tft.setRotation(1); // Landscape
tft.fillScreen(ILI9341_BLACK);
dht.begin();
// Labels
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.setCursor(10, 10);
tft.print("Temp. & Humidity");
// Draw graph box
tft.drawRect(GRAPH_X - 1, GRAPH_Y - 1, GRAPH_WIDTH + 2, GRAPH_HEIGHT + 2, ILI9341_WHITE);
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temp: ");
Serial.print(t);
Serial.print(" C, Humidity: ");
Serial.println(h);
if (dataIndex >= MAX_POINTS) {
shiftData();
dataIndex = MAX_POINTS - 1;
}
temperatureData[dataIndex] = t;
humidityData[dataIndex] = h;
dataIndex++;
drawGraph();
delay(1000); // Update every second
}
void shiftData() {
for (int i = 1; i < MAX_POINTS; i++) {
temperatureData[i - 1] = temperatureData[i];
humidityData[i - 1] = humidityData[i];
}
}
void drawGraph() {
tft.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT, ILI9341_BLACK);
for (int i = 1; i < dataIndex; i++) {
int x0 = GRAPH_X + (i - 1) * (GRAPH_WIDTH / MAX_POINTS);
int y0_t = GRAPH_Y + GRAPH_HEIGHT - map(temperatureData[i - 1], 0, 50, 0, GRAPH_HEIGHT);
int y0_h = GRAPH_Y + GRAPH_HEIGHT - map(humidityData[i - 1], 0, 100, 0, GRAPH_HEIGHT);
int x1 = GRAPH_X + i * (GRAPH_WIDTH / MAX_POINTS);
int y1_t = GRAPH_Y + GRAPH_HEIGHT - map(temperatureData[i], 0, 50, 0, GRAPH_HEIGHT);
int y1_h = GRAPH_Y + GRAPH_HEIGHT - map(humidityData[i], 0, 100, 0, GRAPH_HEIGHT);
tft.drawLine(x0, y0_t, x1, y1_t, ILI9341_RED);
tft.drawLine(x0, y0_h, x1, y1_h, ILI9341_CYAN);
}
}