#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#define DHT_PIN 15 // ESP32 pin GPIO1 connected to DHT22 sensor's data pin
#define TRIG_PIN 19 // ESP32 pin GPIO19 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 18 // ESP32 pin GPIO18 connected to Ultrasonic Sensor's ECHO pin
#define LED_PIN 12 // ESP32 pin GPIO12 connected to LED's anode
#define BUZZER_PIN 14 // ESP32 pin GPIO14 connected to buzzer's positive pin
#define LCD_ADDRESS 0x27 // I2C address of the LCD display
#define LCD_COLUMNS 16 // Number of columns in your LCD
#define LCD_ROWS 2 // Number of rows in your LCD
LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLUMNS, LCD_ROWS); // Initialize the LCD object
DHT dht(DHT_PIN, DHT22); // Initialize DHT sensor object
void setup() {
Wire.begin();
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
// Initialize the LCD
lcd.begin(LCD_COLUMNS, LCD_ROWS);
lcd.backlight(); // Turn on the backlight (if available)
lcd.clear(); // Clear the LCD screen
lcd.setCursor(0, 0);
lcd.print("Distance:");
// Initialize DHT sensor
dht.begin();
}
void loop() {
// Ultrasonic sensor measurements
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long duration = pulseIn(ECHO_PIN, HIGH);
// Speed of sound is 343m/s or 0.0343cm/us
float distance_cm = duration * 0.0343 / 2;
// DHT sensor measurements
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Print the distance on LCD
lcd.setCursor(0, 0);
lcd.print(" "); // Clear the line
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance_cm);
lcd.print(" cm");
// Print DHT data on LCD
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temperature);
// Print the distance and DHT data on serial monitor
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.print(" cm, ");
Serial.print("Temperature: ");
Serial.print(temperature);
// Turn on LED if distance is less than 100cm
if (distance_cm < 100) {
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH); // Turn on the buzzer
} else {
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW); // Turn off the buzzer
}
// Display fire alert if temperature exceeds 45°C
if (temperature >= 30.0) {
lcd.setCursor(0, 1);
lcd.print("Fire Alert!");
delay(2000); // Delay for 2 seconds to display the fire alert message
}
delay(1000); // Delay for 1 second before next measurement
}