#include <DHT.h>
#include <Servo.h>
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
Servo motorServo; // Define motorServo as object for Servo to control the Motor Servo
DHT dht(DHTPIN, DHTTYPE);
const int motorPin = 7; // Pin for the Motor Servo to digital pin 7
const int LedPin = 8; // Pin for the red LED
const int buzzerPin = 9; // Pin for the buzzer
void setup() {
motorServo.attach(motorPin);
pinMode(LedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Initialize the DHT sensor
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Check humidity
if (humidity > 70) {
digitalWrite(LedPin, HIGH); // Turn on the red LED
} else {
digitalWrite(LedPin, LOW); // Turn off the red LED
}
// Check temperature
if (temperature > 40) {
motorServo.write(180); // Set the Motor Servo angle to 180 degrees
// Sound the buzzer for half a second
tone(buzzerPin, 1000);
delay(1000);
motorServo.write(0); // Turn off the Motor Servo
noTone(buzzerPin);
// Wait for another half a second
delay(500);
} else {
motorServo.write(0); // Turn off the Motor Servo
noTone(buzzerPin); // Turn off the buzzer
}
}