int melody[8] = {262,294,330,349,392,440,494,523};
int TRIG = 3, ECHO = 4, speaker = 7;
void setup() {
Serial.begin(9600);
pinMode(TRIG,OUTPUT);
pinMode(ECHO,INPUT);
pinMode(speaker, OUTPUT);
}
void loop() {
float distance, duration;
digitalWrite(TRIG, HIGH);
delayMicroseconds(1);
digitalWrite(TRIG,LOW);
duration = pulseIn(ECHO,HIGH);
distance = ((float)(duration*340)/10000)/2;
Serial.println(distance);
int i;
if (distance <= 32) {
i=map(distance,0,32,0,7);
tone (speaker, melody[i], 250);
delay (300);
}
else {
noTone(speaker);
}
}