#define PIN_TRIG 3
#define PIN_ECHO 2

// declaring variables
const int tonePin = 8;
unsigned long previousMillis = 0;
 long pauseBetweenNotes = 100;   // interval between notes (ms)
 long noteDuration = 100;        // (ms)
boolean outputTone = false;                // Records current state
const int MelodyLength = 1;
int Melody[MelodyLength] = {1000};
int MelodyIndex = 0;
unsigned long currentMillis;


void setup() {
  Serial.begin(115200);
  pinMode(PIN_TRIG, OUTPUT);
  pinMode(PIN_ECHO, INPUT);
      pinMode(11,OUTPUT);
    digitalWrite(11,HIGH);
}

void loop() {

  
  // Start a new measurement:
  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(PIN_TRIG, LOW);


  // Read the result:
  int duration = pulseIn(PIN_ECHO, HIGH);
  float distance = duration / 58 ;
  // Serial.print("Distance in CM: ");
  // Serial.println(duration / 58);
  // Serial.print("Distance in inches: ");
  // Serial.println(duration / 148);
  Serial.println(distance);
  if (distance < 350){
      noteLoop();
      pauseBetweenNotes = map(distance, 10, 400, 10, 250);
      noteDuration = map(distance, 10, 400, 10, 250);
      Melody[0] = map(distance, 10, 400, 1500, 500);

  }
  else
  {
    noTone(8);
  }


  //tone(8, duration / 58, 500);
  // if (distance < 20){
  //   tone(8, 1000, 500);
  // }
  // else if (distance < 50){
  //   tone(8, 800, 500);
  // }
  //  else if (distance < 100){
  //   tone(8, 600, 500);
  // }
  //  else if (distance < 150){
  //   tone(8, 400, 500);
  // }
  //  else if (distance < 200){
  //   tone(8, 200, 500);
  // }
  //    else if (distance < 300){
  //   tone(8, 150, 500);
  // }
  // else{
  //   noTone(8);
  // }

   delay(1);
}



void noteLoop() {
  currentMillis = millis();
  PlayMelody();
}

void PlayMelody() {
  if (outputTone) {
    // We are currently outputting a tone
    // Check if it's been long enough and turn off if so
    if (currentMillis - previousMillis >= noteDuration) {
      previousMillis = currentMillis;
      noTone(tonePin);
      outputTone = false;
    }
  } else {
    // We are currently in a pause
    // Check if it's been long enough and turn on if so
    if (currentMillis - previousMillis >= pauseBetweenNotes) {
      previousMillis = currentMillis;
      tone(tonePin, Melody[MelodyIndex]);
      outputTone = true;
      //Update to play the next tone, next time
      MelodyIndex = MelodyIndex + 1;
      if (MelodyIndex >= MelodyLength) {
        MelodyIndex = 0;
      }
    }
  }
}