#include<Servo.h>
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);/*
 * LCD RS pin to digital pin 7
 * LCD Enable pin to digital pin 8
 * LCD D4 pin to digital pin 9
 * LCD D5 pin to digital pin 10
 * LCD D6 pin to digital pin 11
 * LCD D7 pin to digital pin 12
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
*/

int echoPin = 3;  // pin connected to Echo Pin in the ultrasonic distance sensor
int trigPin  = 2; // pin connected to trig Pin in the ultrasonic distance sensor
Servo servo;

void setup()
{
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  lcd.begin(16, 2);
  lcd.clear();
  Serial.begin(9600);
  servo.attach(9);
  delay(1000);
  
}

void loop()
{
  lcd.setCursor(0,0);
  lcd.setCursor(0,1);
  int distance = ping(echoPin);
  if(distance <= 20)
  {
   
    servo.write(165);
    lcd.print("Fan on!");
    delay(500);
  }
  else
  {
    lcd.print("Too far away");
    delay(500);
  }
}

//for distance sensor
int ping(int echoPin) 
{ 
   // establish variables for duration of the ping, 
   // and the distance result in inches and centimeters: 
   long duration, cm; 
   // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. 
   // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: 
   pinMode(trigPin, OUTPUT); 
   digitalWrite(trigPin, LOW); 
   delayMicroseconds(2); 
   digitalWrite(trigPin, HIGH); 
   delayMicroseconds(5); 
   digitalWrite(trigPin, LOW); 

   pinMode(echoPin, INPUT); 
   duration = pulseIn(echoPin, HIGH); 

   // convert the time into a distance 
   cm = microsecondsToCentimeters(duration); 
   return cm ; 
}

long microsecondsToCentimeters(long microseconds) 
{ 
   // The speed of sound is 340 m/s or 29 microseconds per centimeter. 
   // The ping travels out and back, so to find the distance of the 
   // object we take half of the distance travelled. 
   return microseconds / 29 / 2; 
}
$abcdeabcde151015202530354045505560fghijfghij