#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Initialize the LCD (address, columns, rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Define sensor pins
const int pirPin = esp4; // GPIO 5
const int irPin = D2; // GPIO 4
const int gasSensorPin = A0;
const int ledPin = D6; // GPIO 12
const int fanPin = D7; // GPIO 13
const int dhtPin = D5; // GPIO 14
// Initialize DHT22 sensor
#define DHTTYPE DHT22
DHT dht(dhtPin, DHTTYPE);
// Variables for sensor readings
int pirState = LOW;
int irState = LOW;
int gasLevel = 0;
float temperature = 0.0;
float humidity = 0.0;
void setup() {
// Initialize LCD
lcd.begin();
lcd.backlight();
// Set sensor pins as input
pinMode(pirPin, INPUT);
pinMode(irPin, INPUT);
pinMode(gasSensorPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(fanPin, OUTPUT);
// Initialize DHT22 sensor
dht.begin();
// Print initial message
lcd.setCursor(0, 0);
lcd.print("Smart Classroom");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
delay(2000);
lcd.clear();
}
void loop() {
// Read PIR sensor
pirState = digitalRead(pirPin);
if (pirState == HIGH) {
lcd.setCursor(0, 0);
lcd.print("Motion Detected ");
digitalWrite(ledPin, HIGH); // Turn on LED when motion is detected
} else {
lcd.setCursor(0, 0);
lcd.print("No Motion ");
digitalWrite(ledPin, LOW); // Turn off LED when no motion
}
// Read IR sensor
irState = digitalRead(irPin);
if (irState == HIGH) {
lcd.setCursor(0, 1);
lcd.print("IR Signal Detected");
} else {
lcd.setCursor(0, 1);
lcd.print("No IR Signal ");
}
// Read Gas sensor
gasLevel = analogRead(gasSensorPin);
if (gasLevel > 300) { // Adjust threshold as needed
lcd.setCursor(0, 1);
lcd.print("Gas Detected! ");
// Additional actions can be added here (e.g., triggering an alarm)
}
// Read DHT22 sensor
temperature = dht.readTemperature();
humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
lcd.setCursor(0, 0);
lcd.print("DHT22 Error ");
} else {
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print("C ");
lcd.setCursor(0, 1);
lcd.print("Hum: ");
lcd.print(humidity);
lcd.print("% ");
}
// Control fan based on temperature
if (temperature > 25.0) { // Adjust threshold as needed
digitalWrite(fanPin, HIGH); // Turn on the fan
} else {
digitalWrite(fanPin, LOW); // Turn off the fan
}
// Small delay for sensor stability
delay(2000); // Increased delay to allow reading to be visible on LCD
}