#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#define LED_PIN 2
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
#define MOTION_PIN 23
#define TEM_PIN 15
#define BETA 3950
//some GPIO pin dont support analog signal!!
//declare LCD device
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
int motion_val;//motion output defualt:0
float tem_val;
int analog_val;
int recordCount = 0;
int temSum = 0 ;
int averTem = 0; //Used to record the set of temperature when motion.
int OffCount = 0; //Calculate the low motion times;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LED_PIN , OUTPUT);
pinMode(MOTION_PIN , INPUT);
pinMode(TEM_PIN , INPUT);
WifiInitial();
lcd.init();
lcd.backlight();
}
void WifiInitial(void){
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
}
void LCD_temperature(int number){
lcd.setCursor(0 , 0);
lcd.print("Temperature:");
lcd.setCursor(8 , 1);
lcd.print(number);
lcd.print(" Celsius");
}
void temAndled(int tem_val){
Serial.print("Temperature: ");
Serial.print(tem_val);
Serial.println("");
if(tem_val <= 10){
Serial.print("LED : ON\n");
}
else Serial.print("LED : OFF\n");
}
void loop() {
// check whether output of motion sensor.
motion_val = digitalRead(MOTION_PIN);
if(motion_val == HIGH){
/*
When a motion is detected, keep reading the temperature
from the temperature sensor and print the temperature on
the LCD display.
*/
OffCount = 0 ; //if motion is high, the count should restart
analog_val = analogRead(TEM_PIN);
tem_val = 1 / (log(1 / (4095. / analog_val - 1)) / BETA + 1.0 / 298.15) - 273.15;
recordCount ++; //Temperature record count.
temSum += tem_val;//Record the temperature.
lcd.setCursor(0,2);
lcd.print("Average: ");
lcd.print(temSum / recordCount);
LCD_temperature(tem_val);
temAndled( tem_val);//Print out the temperature value and LED status through Serial.
if(tem_val <= 10){
/*If the temperature is below 10 ℃ when a motion is detected,
turn on LED and print the “LED On” on the LCD display.*/
digitalWrite(LED_PIN , HIGH);
lcd.setCursor(6 , 3);
lcd.print("LED ON");
}
else{
/*When the OUT pin of the motion sensor goes LOW, turn off LED and
clean the LCD display. */
digitalWrite(LED_PIN , LOW);
lcd.clear();
LCD_temperature(tem_val);
}
delay(500); // Set the interval for reading data from the temperature sensor to 0.5 seconds.
}
else{
/*If the OUT pin of the motion sensor goes low, set the time interval
for reading data from the temperature sensor to 3 seconds.*/
recordCount = 0 ; //Temperature record count.
temSum = 0;//Record the temperature.
delay(3000);
OffCount ++;
}
if(OffCount >= 3)
{
digitalWrite(LED_PIN , LOW);
lcd.clear();
}
}