#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>

// TFT LCD Pins
#define TFT_CS     53
#define TFT_RST    9
#define TFT_DC     10

// NTC Thermistor
#define NTC_PIN A0  

// TFT Display
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);

// Graph Settings
#define GRAPH_X_START 10
#define GRAPH_Y_START 200
#define GRAPH_WIDTH 300
#define GRAPH_HEIGHT 100
#define TEMP_MIN 20  // Min expected temperature
#define TEMP_MAX 40  // Max expected temperature

int graphX = GRAPH_X_START;  // Initial X position of the graph

void setup() {
  Serial.begin(9600);
  tft.begin();
  tft.setRotation(3);
  tft.fillScreen(ILI9341_BLACK);
  
  // Draw Graph Axes
  tft.drawRect(GRAPH_X_START, GRAPH_Y_START - GRAPH_HEIGHT, GRAPH_WIDTH, GRAPH_HEIGHT, ILI9341_WHITE);
  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(1);
  tft.setCursor(5, GRAPH_Y_START - GRAPH_HEIGHT - 15);
  tft.print("Temperature Graph (C)");
}

void loop() {
  int analogValue = analogRead(NTC_PIN);
  float voltage = analogValue * (5.0 / 1023.0);
  
  // Convert to temperature (simplified)
  float temperature = map(analogValue, 400, 800, TEMP_MIN, TEMP_MAX);
  
  // Display Temperature
  tft.fillRect(20, 30, 200, 30, ILI9341_BLACK); // Clear previous text
  tft.setCursor(20, 30);
  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(2);
  tft.print("Temp: ");
  tft.print(temperature);
  tft.println(" C");

  // Map temperature to graph height
  int graphY = map(temperature, TEMP_MIN, TEMP_MAX, GRAPH_Y_START, GRAPH_Y_START - GRAPH_HEIGHT);
  
  // Draw new point on graph
  tft.fillCircle(graphX, graphY, 2, ILI9341_GREEN);

  // Move graph X forward
  graphX++;
  if (graphX > GRAPH_X_START + GRAPH_WIDTH) {
    graphX = GRAPH_X_START;  
    tft.fillRect(GRAPH_X_START + 1, GRAPH_Y_START - GRAPH_HEIGHT + 1, GRAPH_WIDTH - 2, GRAPH_HEIGHT - 2, ILI9341_BLACK);
  }

  Serial.println(temperature);  // For debugging
  delay(500);
}