/*
  HC-SR04 Ultrasonic Sensor Example.

  Turn the LED on when an object is within 100cm range.

  Copyright (C) 2021, Uri Shaked

*/
#include <Servo.h>


#include <LiquidCrystal_I2C.h>

#define I2C_ADDR    0x27
#define LCD_COLUMNS 20
#define LCD_LINES   4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);

#define ECHO_PIN 2
#define TRIG_PIN 3

int LED1 = 13;

Servo servoku;


void setup() {
  Serial.begin(115200);
  pinMode(LED1, OUTPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  lcd.init();
  lcd.backlight();
  servoku.attach(5);
}

float readDistanceCM() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  int duration = pulseIn(ECHO_PIN, HIGH);
  return duration * 0.034 / 2;
}



void loop() {
  float distance = readDistanceCM();
  
  if(distance > 100){
    kedip();
    servoku.write(90);
    lcd.setCursor(0, 0);
    lcd.print("SERVO DINAIKKAN ");

  }  
  else{
    lcd.clear();
    digitalWrite(LED1, LOW);
    servoku.write(0); 
  }
  Serial.print("Measured distance: ");
  Serial.println(readDistanceCM());
 
}

void kedip() {
      digitalWrite(LED1, HIGH);
      delay(500);
      digitalWrite(LED1, LOW);
      delay(500);

}