#include <LiquidCrystal_I2C.h>

#define btn 8
#define led 9
#define echo 6
#define trigger 7

LiquidCrystal_I2C lcd(0x27, 20,4);
bool btn_durum = false;
int olcum = 0;

void setup() {
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();

  pinMode(btn, INPUT);
  pinMode(led, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(trigger, OUTPUT);
}

void loop() {
  btn_durum = digitalRead(btn);

  if(btn_durum){
    olcum = uzunluk();
    lcd.clear();

    digitalWrite(led, HIGH);
    ortaliYazdir("Mesafe",1);
    ortaliYazdir(String(olcum),2);
    Serial.println(String(olcum));

    delay(100);
  }
  else{
    digitalWrite(led, LOW);
    delay(100);
  }
}

int uzunluk(){
  long sure, mesafe;

  digitalWrite(trigger, LOW);
  delayMicroseconds(2);
  digitalWrite(trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigger, LOW);

  sure = pulseIn(echo, HIGH);
  mesafe = sure/58.2;
  delay(50);

  return mesafe;
}

int ortaliYazdir(String txt, int iIndex){
  int ilkIndis = (20-txt.length())/2;

  lcd.setCursor(ilkIndis,iIndex-1);
  lcd.print(txt);
}
