#include <DHT.h>
#include <Servo.h>
#define DHTPIN 2 // what digital pin we're connected to for DHT22
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
Servo myServo; // create servo object to control a servo
void setup() {
myServo.attach(9); // attaches the servo on pin 9 to the servo object
dht.begin();
Serial.begin(9600);
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading humidity
float h = dht.readHumidity();
// Check if any reads failed and exit early (to try again).
if (isnan(h)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Map the humidity value to a range from 0 to 180
int angle = map(h, 0, 100, 0, 180);
angle = constrain(angle, 0, 180); // Make sure the angle is within the servo's limit
myServo.write(angle); // Move the servo to the angle based on humidity
// Print the humidity and servo angle to the Serial Monitor
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("%\t");
Serial.print("Servo Angle: ");
Serial.println(angle);
}