// 以国际标准音A-la-440HZ为准:do的频率为261.6HZ,re的频率为293.6HZ,
// mi的频率为329.6HZ,fa的频率为349.2HZ,sol的频率为392HZ,la的频率为440HZ,
// si的频率为493.8HZ。
// 在仿真平台为了操作方便,每个音符对应30-40cm,实际平台为了减少干扰,可以20或者10

const int trig = 13;
const int echo = 12;
const int buzzer = 11;
int delaytime = 500;

float dis(int Trig, int Echo) {
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);
  return (pulseIn(Echo, HIGH) / 58.0);
}


void setup() {
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);
}

void loop() {
  float distance = dis(trig, echo);
  Serial.println(distance);
  switch (int(distance) / 40) {
    case 0:
      tone(buzzer, 261.1, 250);
      delay(delaytime);
      break;
    case 1:
      tone(buzzer, 293.6, 250);
      delay(delaytime);
      break;
    case 2:
      tone(buzzer, 329.6, 250);
      delay(delaytime);
      break;
    case 3:
      tone(buzzer, 349.2, 250);
      delay(delaytime);
      break;
    case 4:
      tone(buzzer, 392, 250);
      delay(delaytime);
      break;
    case 5:
      tone(buzzer, 440, 250);
      delay(delaytime);
      break;
    case 6:
      tone(buzzer, 493.8, 250);
      delay(delaytime);
      break;
  }
}