#include <Servo.h> //uses servo and DHT libraries
#include <DHT.h>
// DHT sensor setup
#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE); //intialises DHT object with sensor type and pins
// Creates a servo motor to control the servo angle
Servo servo;
void setup() {
servo.attach(5); // Attach servo to pin 5
dht.begin(); // Start the DHT sensor
Serial.begin(400); //Starts serial conversation
}
void loop() {
// Read the temperature from the DHT sensor
float temp = dht.readTemperature();
// Check if the reading is valid
if (isnan(temp)) {
delay(2000); // Wait before trying again
return;
}
int servoAngle; // Variable to hold the servo angle
// Map the temperature range (-40°C to +80°C) to the servo angle range (0° to 180°)
servoAngle = map(constrain(temp, -40, 80), -40, 80, 0, 180);
// Move the servo to the corresponding angle
servo.write(servoAngle);
//Prints out the info about temp and corresponding angle
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print("℃ --> Angle: ");
Serial.print(servoAngle);
Serial.println("º");
delay(1000); // Wait 1 second before the next reading
}