#include <DHT.h>
#include <Servo.h>
// Define pins and sensor type
#define DHTPIN 2 // DHT sensor connected to digital pin 2
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define LEDPIN 13 // LED connected to digital pin 13 (built-in LED)
#define SERVOPIN 9 // Servo motor connected to digital pin 9
// Initialize DHT sensor and Servo objects
DHT dht(DHTPIN, DHTTYPE);
Servo myServo;
void setup() {
Serial.begin(9600);
dht.begin();
myServo.attach(SERVOPIN); // Attach the servo to the pin
pinMode(LEDPIN, OUTPUT);
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read humidity
float h = dht.readHumidity();
// Check if any reads failed and exit early (to try again)
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print the values to the Serial Monitor
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C");
// Control the LED based on temperature
if (t > 25.0) { // If temperature is above 25 degrees Celsius
digitalWrite(LEDPIN, HIGH);
} else {
digitalWrite(LEDPIN, LOW);
}
// Control the servo motor based on humidity
// Map humidity (0-100) to servo angle (0-180)
int pos = map(h, 0, 100, 0, 180);
myServo.write(pos);
}