/*
  HC-SR04 Ultrasonic Sensor Example.

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

  Copyright (C) 2021, Uri Shaked
*/
#define LED 12
#define ECHO_PIN 18
#define TRIG_PIN 5
#define SOUND_SPEED 0.034
#define Btn 2

long duration;
float distance;

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(Btn, INPUT);
}

float readDistanceCM() {
  // Clear TRIG_PIN
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  // Set TRIG_PIN HIGH State 10ms
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  duration = pulseIn(ECHO_PIN, HIGH);
  return duration * SOUND_SPEED / 2;
}

void loop() {
  int Brake = digitalRead(Btn);
  Serial.print("Brake : ");Serial.println(Brake);
  distance = readDistanceCM();
  // วัดระยะจากดิสเบรก
  bool isNearby = distance < 10;
    Serial.println(isNearby);

  digitalWrite(LED, isNearby);

  Serial.print("Measured distance: ");
  Serial.println(readDistanceCM());
  delay(100);
  // จำลองการรับโหมด 0 / 1 จาก Blynk
  int Mode = 0; // รับโหมดจาก Blynk | 1=Day  0=Night

  if(Mode){
      while(Brake || distance < 10){
        distance = readDistanceCM();
        Brake = digitalRead(Btn);
        digitalWrite(LED, 1);
        if(Brake==0 && distance >= 10) break;
      }

  }
  else if(Mode==0){
      while(Brake || distance < 10){
        distance = readDistanceCM();
        Brake = digitalRead(Btn);
        digitalWrite(LED, 1);
        if(Brake==0 && distance >= 10) break;
      }
      if(Brake == 0){
        NightMode();
      }
  }
}

void NightMode(){
    digitalWrite(LED, 1);
    delay(150);
    digitalWrite(LED, 0);
    delay(150);
}