#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define therm A2
#define lightSensor A3
const int pirPin = 2;
const float BETA = 3950;
unsigned long previousMillis = 0;
int seconds = 0;
int minutes = 0;
int hours = 0;
float readings[10];
int readIndex = 0;
float total = 0;
float averageTemp = 0;
String lightStatus = "";
void setup() {
lcd.begin(16, 2);
lcd.backlight();
lcd.clear();
pinMode(pirPin, INPUT);
pinMode(therm, INPUT);
pinMode(lightSensor, INPUT);
for (int i = 0; i < 10; i++) {
int analogValue = analogRead(therm);
float voltage = analogValue * (5.0 / 1023.0);
float Rt = 10000 * voltage / (5.0 - voltage);
float T = 1.0 / (1.0 / 298.15 + (1.0 / BETA) * log(Rt / 10000));
float celsius = T - 273.15;
readings[i] = celsius;
total += celsius;
}
delay(1000);
}
void loop() {
bool motionDetected = digitalRead(pirPin);
if (motionDetected) {
lcd.backlight();
updateDisplay();
} else {
lcd.noBacklight();
lcd.clear();
}
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= 1000) {
previousMillis = currentMillis;
updateTime();
updateTemperature();
}
updateLightLevel();
}
void updateTime() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
if (hours >= 24) {
hours = 0;
}
}
}
}
void updateTemperature() {
int analogValue = analogRead(therm);
float voltage = analogValue * (5.0 / 1023.0);
float Rt = 10000 * voltage / (5.0 - voltage);
float T = 1.0 / (1.0 / 298.15 + (1.0 / BETA) * log(Rt / 10000));
float celsius = T - 273.15;
total = total - readings[readIndex];
readings[readIndex] = celsius;
total = total + readings[readIndex];
readIndex = (readIndex + 1) % 10;
averageTemp = total / 10;
}
void updateLightLevel() {
int analogValue = analogRead(A3);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(50 * 1e3 * pow(10, 0.7) / resistance, (1 / 0.7));
if (lux <= 150) {
lightStatus = "Dark";
} else {
lightStatus = "Light";
}
}
void updateDisplay() {
lcd.setCursor(0, 0);
lcd.print(formatTime(hours, minutes, seconds));
lcd.setCursor(0, 1);
lcd.print(averageTemp, 1);
lcd.print("C");
lcd.setCursor(10, 1);
lcd.print(lightStatus);
}
String formatTime(int hours, int minutes, int seconds) {
char buffer[9];
sprintf(buffer, "%02d:%02d:%02d", hours, minutes, seconds);
return String(buffer);
}