#include <DHT.h>
#include <NewPing.h>
#define DHTPIN 4 // Pin where the DHT sensor is connected
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
#define TRIG_PIN 5 // Ultrasonic sensor trigger pin
#define ECHO_PIN 18 // Ultrasonic sensor echo pin
NewPing sonar(TRIG_PIN, ECHO_PIN);
#define RED_LED_PIN 15 // Red LED pin
#define GREEN_LED_PIN 2 // Green LED pin
void setup() {
Serial.begin(115200);
dht.begin();
pinMode(RED_LED_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
digitalWrite(RED_LED_PIN, LOW); // Turn off both LEDs at the start
digitalWrite(GREEN_LED_PIN, LOW);
}
void loop() {
// Get distance from the ultrasonic sensor
unsigned int distance = sonar.ping_cm();
// Get temperature from DHT sensor
float temperature = dht.readTemperature();
// Check if the readings are valid
if (isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print values to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
// If distance is less than 100 cm and temperature is above 50°C
if (distance < 100 && temperature > 50) {
digitalWrite(RED_LED_PIN, HIGH); // Turn on red LED
digitalWrite(GREEN_LED_PIN, LOW); // Turn off green LED
Serial.println("Red LED ON");
} else {
digitalWrite(RED_LED_PIN, LOW); // Turn off red LED
digitalWrite(GREEN_LED_PIN, HIGH); // Turn on green LED
Serial.println("Green LED ON");
}
delay(1000); // Wait for a second before the next reading
}