#include <DHT.h>
#include <Servo.h> // Include the Servo library
// Constants
#define DHTPIN 2 // Digital pin connected to the DHT22 sensor
#define DHTTYPE DHT22 // Type of DHT sensor
#define BUZZER_PIN 5 // Digital pin connected to the buzzer
#define LED_PIN 10 // Digital pin connected to the LED
#define SERVO_PIN 9 // Digital pin connected to the servo motor
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
Servo myservo; // Create a Servo object
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize DHT sensor
dht.begin();
// Initialize buzzer, LED, and servo pins as outputs
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
myservo.attach(SERVO_PIN); // Attach the servo to the specified pin
// Turn off the buzzer, LED, and set the initial servo position
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(LED_PIN, LOW);
myservo.write(90); // Set the initial servo position (90 degrees)
}
void loop() {
// Read temperature and humidity from DHT sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if the readings are valid
if (!isnan(humidity) && !isnan(temperature)) {
// Print temperature and humidity to the serial monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% Temperature: ");
Serial.print(temperature);
Serial.println("°C");
// Check if temperature is above a threshold
if (temperature > 25.0) {
// Turn on the LED
digitalWrite(LED_PIN, HIGH);
// Generate a tone on the buzzer
tone(BUZZER_PIN, 1000); // You can adjust the frequency as needed
// Move the servo to a specific position (e.g., 180 degrees)
myservo.write(180); // Rotate the servo to 180 degrees
delay(1000); // Delay for 1 second
// Turn off the LED, stop the buzzer tone, and return the servo to the initial position
digitalWrite(LED_PIN, LOW);
noTone(BUZZER_PIN);
myservo.write(90); // Return the servo to the initial position (90 degrees)
}
} else {
// Print an error message if the sensor readings are invalid
Serial.println("Error: Unable to read from DHT sensor.");
}
// Delay for a moment before taking the next reading
delay(2000); // Delay for 2 seconds
}