#include <DHT.h>
const int Trig = 17;
const int Echo = 16;
const int DHTPin = 13;
const int Buzz = 19;
#define DHTTYPE DHT22
DHT dht(DHTPin, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("Ultrasonic and DHT22 Sensor\nNikash M.S. \n22DX21");
pinMode(33, OUTPUT);
pinMode(25, OUTPUT);
pinMode(26, OUTPUT);
pinMode(Trig, OUTPUT);
pinMode(Echo, INPUT);
pinMode(Buzz, OUTPUT);
dht.begin();
}
void loop() {
digitalWrite(Trig, LOW);
delayMicroseconds(2);
digitalWrite(Trig, HIGH);
delayMicroseconds(10);
digitalWrite(Trig, LOW);
long duration = pulseIn(Echo, HIGH);
int distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
delay(2000);
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C ");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
if (temperature < 30 && humidity > 70 && distance > 300) {
digitalWrite(33, HIGH);
digitalWrite(25, LOW);
digitalWrite(26, LOW);
noTone(Buzz);
Serial.println("Safe: Distance > 300 cm, Temp < 30 °C, Humidity > 70%");
delay(2000);
}
else if (temperature >= 30 && temperature <= 70 && humidity >= 30 && humidity <= 70 && distance >= 200 && distance <= 300) {
digitalWrite(33, LOW);
digitalWrite(25, HIGH);
digitalWrite(26, LOW);
noTone(Buzz);
Serial.println("Unsafe: Distance 200-300 cm, Temp 30-70 °C, Humidity 30-70%");
delay(2000);
}
else if (temperature >= 70 && humidity <= 30 && distance >= 200) {
digitalWrite(33, LOW);
digitalWrite(25, LOW);
digitalWrite(26, HIGH);
tone(Buzz, 50);
Serial.println("Danger: Distance >= 200 cm, Temp >= 70 °C, Humidity <= 30%");
delay(2000);
} else {
digitalWrite(33, LOW);
digitalWrite(25, LOW);
digitalWrite(26, LOW);
noTone(Buzz);
}
delay(2000);
}