#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 20, 4);
const float BETA = 3950;
int ledPin = 2; //LED
int motionIn = 12; //pir motion
int analogIn = 35; //NTC temperature sensor
int pirState = LOW; //pir state
int val = 0;
float sum = 0; //calculate total temperature
int count = 0; //record the number of temperature have been detected
int delayCount = 0; //record if the motion goes low for over 9 seconds
int ifStart = 0; //record if current state goes from high to low
void LCD_print(float celsius, int flag){
LCD.setCursor(1, 0); //print current temperature
LCD.print("current: ");
LCD.println(celsius);
LCD.setCursor(1, 1);
if(celsius < 10){
digitalWrite(ledPin, HIGH); //tem < 10, light the LED
LCD.println("LED On");
}
else{
digitalWrite(ledPin, LOW);
LCD.println(" ");
}
if(flag == 1){
LCD.setCursor(1, 2); //print average temperature
LCD.print("average: ");
LCD.println(sum / count);
}
else{
LCD.setCursor(1, 2); //cover average temperature
LCD.println(" ");
}
}
void setup() {
pinMode(motionIn, INPUT); //set motion input
pinMode(analogIn, INPUT); //set analog input
pinMode(ledPin, OUTPUT); //set LED output
analogReadResolution(10);
LCD.init();
Serial.begin(9600);
}
void loop() {
int analogValue = analogRead(analogIn); //read temperature
float celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
val = digitalRead(motionIn); //detect motion
if(val == HIGH){
if(pirState == LOW){
Serial.println("Motion detected!");
pirState = HIGH;
}
ifStart = 1;
sum += celsius; //calculate the sum of current temperature
count++; //record the number of temperature
LCD_print(celsius, 1);
}
else{
if(pirState == HIGH){
Serial.println("Motion ended!");
pirState = LOW;
}
if(ifStart == 1) LCD_print(celsius, 0);
if(delayCount == 3){
digitalWrite(ledPin, LOW);
LCD.clear();
}
}
if(val == HIGH){
delay(500); //high: delay 0.5 seconds
delayCount = 0;
}
else{
delay(3000); //low: delay 3 seconds
delayCount++;
}
}