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

volatile int mode_pin;
volatile int button_pin;
volatile int servo_state;
volatile int dis;
volatile int bai;
volatile int shi;
volatile int ge;
LiquidCrystal_I2C mylcd(0x27,16,2);
Servo servo_9;

float checkdistance_7_6() {
  digitalWrite(7, LOW);
  delayMicroseconds(2);
  digitalWrite(7, HIGH);
  delayMicroseconds(10);
  digitalWrite(7, LOW);
  float distance = pulseIn(6, HIGH) / 58.00;
  delay(10);
  return distance;
}

boolean mixly_digitalRead(uint8_t pin) {
  pinMode(pin, INPUT);
  boolean _return =  digitalRead(pin);
  pinMode(pin, OUTPUT);
  return _return;
}

void sound_play() {
  tone(10,500);
  delay(200);
  noTone(10);
  delay(100);
  tone(10,500);
  delay(200);
  noTone(10);
  delay(100);
  tone(10,500);
  delay(200);
  noTone(10);
}

void setup(){
  mode_pin = 4;
  button_pin = 5;
  servo_state = 0;
  dis = 0;
  bai = 0;
  shi = 0;
  ge = 0;
  mylcd.init();
  mylcd.backlight();
  pinMode(mode_pin, INPUT);
  pinMode(button_pin, INPUT);
  mylcd.clear();
  pinMode(7, OUTPUT);
  pinMode(6, INPUT);
  servo_9.attach(9);
  pinMode(10, OUTPUT);
}

void loop(){
  dis = checkdistance_7_6();
  bai = dis / 100;
  shi = (long) ((dis / 10)) % (long) (10);
  ge = (long) (dis) % (long) (10);

  mylcd.setCursor(1-1, 1-1);
  mylcd.print("Dis: ");
  mylcd.setCursor(7-1, 1-1);
  mylcd.print(bai);
  mylcd.setCursor(8-1, 1-1);
  mylcd.print(shi);
  mylcd.setCursor(9-1, 1-1);
  mylcd.print(ge);
  mylcd.setCursor(10-1, 1-1);
  mylcd.print(" ");
  mylcd.setCursor(11-1, 1-1);
  mylcd.print("cm");
  delay(50);
  if (mixly_digitalRead(mode_pin) == 0) {
    if (dis < 100 && servo_state == 0) {
      mylcd.setCursor(1-1, 2-1);
      mylcd.print("WELCOME!");
      servo_9.write(90);
      delay(0);
      servo_state = 1;
      sound_play();

    } else if (dis >= 100 && servo_state == 1) {
      mylcd.setCursor(1-1, 2-1);
      mylcd.print("--------");
      servo_9.write(0);
      delay(0);
      servo_state = 0;
    }

  } else {
    if (mixly_digitalRead(button_pin) == 0) {
      delay(10);
      if (mixly_digitalRead(button_pin) == 0) {
        if (servo_state == 0) {
          mylcd.setCursor(1-1, 2-1);
          mylcd.print("WELCOME!");
          servo_9.write(90);
          delay(0);
          servo_state = 1;
          sound_play();

        } else {
          mylcd.setCursor(1-1, 2-1);
          mylcd.print("--------");
          servo_9.write(0);
          delay(0);
          servo_state = 0;

        }
        while (mixly_digitalRead(button_pin) == 0) {
        }

      }

    }

  }

}