Arduino code

From Medien Wiki

// 초음파센서와 피에조 스피커. 거리에 따라 (4cm마다) 도레미파솔라시도(4 옥타브) 소리내기.

int melody[28] = 131,147,165,175,196,220,247,// 도레미파솔라시 262,294,330,349,392,440,494,// 도레미파솔라시 523,587,659,698,784,881,988,// 도레미파솔라시 1047,1175,1319,1397,1568,1760,1976,// 도레미파솔라시 };

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 <= ) {

i=map(distance,0,32,0,7);

tone (speaker, melody[i], 250);

delay (300);

}

else {

noTone(speaker);

}


}