#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <Servo.h>
// Define pin connections
#define DHTPIN 2 // Pin connected to the DHT22
#define FLAME_SENSOR_PIN A3 // Analog pin connected to the flame sensor
#define MQ2_PIN A0 // Analog pin connected to MQ-2 gas sensor
#define SERVO_PIN 9 // Pin connected to servo motor
// Initialize the LCD and DHT22 sensor
LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address might vary, adjust if necessary
DHT dht(DHTPIN, DHT22);
Servo servo;
// Define thresholds
float tempThreshold = 35.0; // Temperature threshold in Celsius for both temp and gas check
float tempOnlyThreshold = 33.0; // Temperature threshold for temperature-only check
int gasThreshold = 750; // Gas threshold level (adjust as needed)
// Timing variables
unsigned long previousMillis = 0;
const long interval = 1000; // Interval for updating the display (1000 ms = 1 second)
void setup() {
// Start LCD, servo, and sensors
lcd.begin(20, 4); // Specify 20 columns and 4 rows
lcd.backlight();
dht.begin();
servo.attach(SERVO_PIN);
servo.write(0); // Set servo to initial position
// Display initial messages
lcd.setCursor(0, 0);
lcd.print("System Initializing");
delay(2000);
lcd.clear();
}
void loop() {
// Read data from sensors
float temp = dht.readTemperature();
float humidity = dht.readHumidity();
int flameDetected = analogRead(FLAME_SENSOR_PIN) < 500; // Adjust threshold for flame detection
int gasLevel = analogRead(MQ2_PIN);
// Servo control based on temperature, gas, and flame thresholds
if (temp > tempThreshold && gasLevel > gasThreshold && flameDetected) {
servo.write(65); // Move servo to 65 degrees if all three conditions are met
lcd.setCursor(11, 3);
lcd.print("ALERT");
}
else if (temp > tempOnlyThreshold) {
servo.write(45); // Move servo to 45 degrees if only the temperature exceeds 33°C
}
else {
servo.write(0);
lcd.setCursor(11, 3);
lcd.print(" "); // Clear alert message
}
// Check if 1 second has passed to update the display
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis; // Save the last time the display was updated
// Update display every second
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temp);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Hum: ");
lcd.print(humidity);
lcd.print(" %");
lcd.setCursor(0, 2);
lcd.print("Gas Level: ");
lcd.print(gasLevel);
lcd.setCursor(0, 3);
lcd.print("Flame: ");
lcd.print(flameDetected ? "Yes" : "No ");
}
}