#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>

#include <VarSpeedServo.h> 

// Define pins and constants
#define DHTPIN 2
#define DHTTYPE DHT22

VarSpeedServo myservo;  // create servo object to control a servo 
                        // a maximum of eight servo objects can be created 
 
const int servoPin = 9; // the digital pin used for the servo

LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize the I2C LCD
DHT dht(DHTPIN, DHTTYPE);           // Initialize the DHT22 sensor

void setup() {
  // Initialize the LCD
  lcd.init();
  lcd.clear();         
  lcd.backlight();      // Make sure backlight is on

  // Initialize the DHT22 sensor
  dht.begin();

  // Attach the servo motor to pin 9
  myservo.attach(servoPin);  // attaches the servo on pin 9 to the servo object
  myservo.write(0,255,true); // set the intial position of the servo, as fast as possible, wait until done

  // Display a welcome message
  lcd.setCursor(0, 0);
  lcd.print("Temp & Humidity");
  delay(2000);
  lcd.clear();
}

void loop() {
  // Read temperature and humidity
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  // Check if the readings are valid
  if (isnan(temperature) || isnan(humidity)) {
    lcd.setCursor(0, 0);
    lcd.print("Sensor Error!");
    delay(1000);
    return;
  }

  // Display temperature and humidity on the LCD
  lcd.setCursor(0, 0);
  lcd.print("Temp: ");
  lcd.print(temperature, 1);
  lcd.print("C");

  lcd.setCursor(0, 1);
  lcd.print("Hum: ");
  lcd.print(humidity, 1);
  lcd.print("%");

  // Control the servo based on temperature
  int servoPosition = map(temperature, -40, 80, 0, 180); // Map 0-50°C to 0-180 degrees
  servoPosition = constrain(servoPosition, 0, 180);    // Ensure the position is valid
  // myServo.write(servoPosition);
  myservo.write(servoPosition,30,true); 

  // Wait for 1 second before the next update
  delay(1000);
}
$abcdeabcde151015202530fghijfghij