#include <Servo.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);

#define PIN_TRIG 8
#define PIN_ECHO 9

#define tombol  2
#define tombolp 11
#define tombolm 10

#define ledm    3
#define ledk    4
#define ledh    5

#define buzzer  6

int status1, stat,statp,statm,nilai;

Servo servo;

void setup()
{
  servo.attach(7);
  servo.write(0);

  lcd.init();
  lcd.backlight();

  lcd.setCursor(4,0);
  lcd.print("~POLNES~");
  lcd.setCursor(2,1);
  lcd.print("~INTALUONES~");
  delay(500);
  lcd.clear();

  pinMode(tombol,   INPUT_PULLUP);
  pinMode(tombolp,  INPUT_PULLUP);
  pinMode(tombolm,  INPUT_PULLUP);

  pinMode(PIN_TRIG, OUTPUT);
  pinMode(PIN_ECHO, INPUT);

  pinMode(ledm ,    OUTPUT);
  pinMode(ledk ,    OUTPUT);
  pinMode(ledh ,    OUTPUT);

  pinMode(buzzer ,  OUTPUT);
  noTone(buzzer);

  digitalWrite(ledm, 1);
  digitalWrite(ledk, 0);
  digitalWrite(ledh, 0);
}

void loop()
{
  display();
  ultrasonik();
  lampu();
}

void lampu()
{
  status1 = digitalRead(tombol);
  if(status1 == 0)
  {
    digitalWrite(ledm, 1);
    delay(1000);
    digitalWrite(ledm, 0);
    digitalWrite(ledk, 1);
    delay(500);
    digitalWrite(ledk, 0);
    tone(buzzer, 1000);
    servo.write(180);
    digitalWrite(ledh, 1);
    delay(1000);
    digitalWrite(ledh, 0);
    digitalWrite(ledm, 1);
    noTone(buzzer);
    servo.write(0);
  }
}

void ultrasonik()
{
  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(PIN_TRIG, LOW);
  int duration = pulseIn(PIN_ECHO, HIGH);
  duration = duration / 58;
  delay(100);

  if(duration <= 100 && stat == 0)
  {
    digitalWrite(ledm, 1);
    delay(1000);
    digitalWrite(ledm, 0);
    digitalWrite(ledk, 1);
    delay(500);
    digitalWrite(ledk, 0);
    tone(buzzer, 1000);
    servo.write(180);
    digitalWrite(ledh, 1);
    delay(1000);
    digitalWrite(ledh, 0);
    digitalWrite(ledm, 1);
    noTone(buzzer);
    servo.write(0);
    stat = 1;
  }

  if(duration >= 100)
  {
    stat = 0;
  }
}

void display()
{
  statp = digitalRead(tombolp);
  statm = digitalRead(tombolm);
  lcd.setCursor(0,0);
  lcd.print("nilai : ");
  
  if(statp == 0)
  {
    nilai = nilai + 1;
  }
  if(statm == 0)
  {
    nilai = nilai - 1;
  }

  lcd.print(nilai);
  lcd.print("  ");

}