#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// 定义引脚
const int pirPin = 13;      // PIR运动传感器
const int tempPin = 12;     // NTC温度传感器
const int ledPin = 2;       // LED

// 初始化LCD
LiquidCrystal_I2C lcd(0x27, 20, 4); // 根据实际I2C地址调整

// 变量
float totalTemp = 0;
int tempReadCount = 0;
bool pirState = LOW;
unsigned long lastReadTime = 0;
unsigned long lastLowTime = 0;

void setup() {
    Serial.begin(115200);
    pinMode(pirPin, INPUT);
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, LOW); // 初始LED关闭

    Wire.begin();
    lcd.begin(0x27, 20, 4);
    lcd.backlight();
}

void loop() {
    pirState = digitalRead(pirPin);
    unsigned long currentTime = millis();

    if (pirState == HIGH) {
        // 运动传感器被触发
        if (currentTime - lastReadTime >= 500) { // 每0.5秒读取一次温度
            float temperature = readTemperature();  
            totalTemp += temperature;
            tempReadCount++;
            Serial.print("Temperature: ");
            Serial.println(temperature);

            lcd.clear(); // 清空LCD显示
            lcd.setCursor(0, 1); // 设置光标位置
            lcd.print("Temperature: ");
            lcd.print(temperature);


            if (temperature < 10.0) {
              digitalWrite(ledPin, HIGH); // 打开LED
              Serial.print("LED on       ");// Print "LED on" on LCD
            } else {
              digitalWrite(ledPin, LOW); // 关闭LED
              Serial.print("LED off       ");
            }
            
            lastReadTime = currentTime;
            lastLowTime = currentTime; // 记录高电平时间
        }
    } else {
        // 运动传感器未被触发
        if (currentTime - lastReadTime >= 3000) { // 每3秒读取一次温度
            float temperature = readTemperature();             
            Serial.print("Temperature: ");
            Serial.println(temperature);

            if (temperature < 10.0) {
              digitalWrite(ledPin, HIGH); // 打开LED
              Serial.print("LED on       ");// Print "LED on" on LCD
            } else {
              digitalWrite(ledPin, LOW); // 关闭LED
              Serial.print("LED off       ");
            }
  
            // 计算平均温度并在LCD上显示
            if (tempReadCount > 0) {
                float averageTemp = totalTemp / tempReadCount;
                lcd.setCursor(0, 1);
                lcd.print("Avg Temp: ");
                lcd.print(averageTemp);
                lcd.print(" C       ");
            }
            
            lastReadTime = currentTime;
            }
        
      
        // 检查低电平持续时间
        if (currentTime - lastLowTime >= 9000) {
            digitalWrite(ledPin, LOW); // 关闭LED
            lcd.clear(); // 清空LCD显示
        } 
        
    }

}

float readTemperature() {
  const float BETA = 3950; // should match the Beta Coefficient of the thermistor
  int analogValue = analogRead(tempPin);
  float temperature = 1 / (log(1 / (4095. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;  
  return temperature;
}