#include <LiquidCrystal_I2C.h>
#include <math.h>

#define PIR_PIN 17
#define TEMP_PIN 34
#define LED_PIN 2

const float BETA = 3950;
LiquidCrystal_I2C lcd(0x27, 20, 4);

unsigned long previousMillis = 0;
unsigned long lowStartMillis = 0;
const long intervalHigh = 500;  // 0.5 seconds
const long intervalLow = 3000;  // 3 seconds
int motionDetected;
float temperatureSum = 0;
int temperatureCount = 0;

void setup() {
  Serial.begin(9600);
  pinMode(PIR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  lcd.init();
  lcd.clear();
}

void loop() {
  unsigned long currentMillis = millis();
  motionDetected = digitalRead(PIR_PIN);

  // When motion is detected
  if (motionDetected == HIGH) {
    lowStartMillis = 0;  // Reset the low time counter
    if (currentMillis - previousMillis >= intervalHigh) {
      previousMillis = currentMillis;
      int analogValue = analogRead(TEMP_PIN);
      float temperature = 1 / (log(1 / (4095.0 / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
      Serial.print("Temperature: ");
      Serial.print(temperature);
      Serial.print(" C, LED: ");
      Serial.println(temperature < 10 ? "On" : "Off");

      temperatureSum += temperature;
      temperatureCount++;

      lcd.setCursor(0, 0);
      lcd.print("Temp: ");
      lcd.print(temperature);
      lcd.print(" C");
      if (temperature < 10) {
        digitalWrite(LED_PIN, HIGH);
        lcd.setCursor(0, 1);
        lcd.print("LED On!");
      } else {
        digitalWrite(LED_PIN, LOW);
        lcd.setCursor(0, 1);
        lcd.print("LED Off");
      }
    }
  } else {  // When no motion is detected
    if (lowStartMillis == 0) {
      lowStartMillis = currentMillis;  // Start counting low time
    }

    if (currentMillis - lowStartMillis >= 9000) {  // If low for more than 9 seconds
      digitalWrite(LED_PIN, LOW);
      lcd.clear();
      temperatureSum = 0;
      temperatureCount = 0;
    }

    if (currentMillis - previousMillis >= intervalLow) {
      previousMillis = currentMillis;
      int analogValue = analogRead(TEMP_PIN);
      float temperature = 1 / (log(1 / (4095.0 / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
      Serial.print("Temperature: ");
      Serial.print(temperature);
      Serial.println(" C");

      if (temperatureCount > 0) {
        float averageTemperature = temperatureSum / temperatureCount;
        lcd.setCursor(0, 0);
        lcd.print("Avg Temp: ");
        lcd.print(averageTemperature);
        lcd.print(" C");
      }
    }
  }
}
$abcdeabcde151015202530fghijfghij