#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Adafruit_Sensor.h>
#define NTC_PIN 15 // Temperature sensor pin
#define LED_PIN 16 // LED pin
#define MOTION_PIN 13 // Motion sensor pin
LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address may vary, please adjust based on your LCD
unsigned long previousTempReadTime = 0;
unsigned long previousMotionDetectionTime = 0;
float totalTemperature = 0.0;
int temperatureReadingsCount = 0;
bool motionDetected = false;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
pinMode(MOTION_PIN, INPUT);
pinMode(NTC_PIN, INPUT);
lcd.init();
lcd.backlight();
}
void loop() {
unsigned long currentMillis = millis();
// Read temperature sensor data every 0.5 seconds
if (currentMillis - previousTempReadTime >= 500) {
const float BETA = 3950; // Beta value for temperature sensor
int analogValue = analogRead(NTC_PIN);
float celsius = 1 / (log(1 / (4095.0 / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
Serial.print("Temperature: ");
Serial.println(celsius);
// Print out temperature value and LED status
Serial.print("LED Status: ");
Serial.println(digitalRead(LED_PIN) == HIGH ? "On" : "Off");
previousTempReadTime = currentMillis;
// When the OUT pin of the motion sensor is high, record temperature sensor data
if (digitalRead(MOTION_PIN) == HIGH) {
if (!motionDetected) {
motionDetected = true;
totalTemperature = 0.0;
temperatureReadingsCount = 0;
}
digitalWrite(LED_PIN, HIGH);
totalTemperature += celsius;
temperatureReadingsCount++;
} else {
motionDetected = false;
}
}
// When the OUT pin of the motion sensor goes low
if (digitalRead(MOTION_PIN) == LOW) {
if (currentMillis - previousMotionDetectionTime >= 9000) {
// If the OUT pin goes low for more than 9 seconds, turn off the LED and clean the LCD display
digitalWrite(LED_PIN, LOW);
lcd.clear();
totalTemperature = 0.0;
temperatureReadingsCount = 0;
} else if (currentMillis - previousMotionDetectionTime >= 3000) {
// If the OUT pin of the motion sensor goes low, set the time interval for reading data to 3 seconds
digitalWrite(LED_PIN, HIGH);
} else if (currentMillis - previousMotionDetectionTime >= 3000) {
// When the OUT pin of the motion sensor goes low, if the time exceeds 3 seconds, re-record temperature data
totalTemperature = 0.0;
temperatureReadingsCount = 0;
}
}
// Calculate the average temperature when the OUT pin of the motion sensor is high and print on the LCD display
if (motionDetected && temperatureReadingsCount > 0) {
float averageTemperature = totalTemperature / temperatureReadingsCount;
lcd.setCursor(0, 2);
lcd.print("Avg Temp: ");
lcd.print(averageTemperature);
}
}