/*
  HC-SR04 Ultrasonic Sensor Example.

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

  Copyright (C) 2021, Uri Shaked
*/
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define ECHO_PIN 2
#define TRIG_PIN 3
#define LEDRED 13
#define LEDGREEN 12

void setup() {
  Serial.begin(115200);
  pinMode(LEDRED, OUTPUT);
  pinMode(LEDGREEN, OUTPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  digitalWrite(LEDRED,LOW);
  digitalWrite(LEDGREEN,LOW);
  lcd.init();                      // initialize the lcd
  // Print a message to the LCD.
  lcd.backlight();
}

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)
  {
      digitalWrite(LEDRED, HIGH);
      digitalWrite(LEDGREEN, LOW);
      Serial.println("LED RED ON / LED GREEN OFF");
      delay(1000);
  }
  if(distance > 100)
  {
      digitalWrite(LEDRED, LOW);
      digitalWrite(LEDGREEN, HIGH);
      Serial.println("LED RED  OFF / LED GREEN ON");
      delay(1000);
  }

  Serial.print("Measured distance: ");
  Serial.println(distance);

  lcd.setCursor(0, 0);             //row0
  lcd.print("Distance");
  lcd.setCursor(0, 1);             //row1
  lcd.print(distance);

  delay(100);
}