Arduino code: Difference between revisions

From Medien Wiki
(Created page with "int melody[32] = { 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, speake...")
 
No edit summary
Line 5: Line 5:
1047,1175,1319,1397,1568,1760,1976,
1047,1175,1319,1397,1568,1760,1976,
};
};
int TRIG = 3, ECHO = 4, speaker = 7;
int TRIG = 3, ECHO = 4, speaker = 7;
void setup() {
void setup() {
Serial.begin(9600);
Serial.begin(9600);
pinMode(TRIG,OUTPUT);
pinMode(TRIG,OUTPUT);
pinMode(ECHO,INPUT);
pinMode(ECHO,INPUT);
pinMode(speaker, OUTPUT); }
pinMode(speaker, OUTPUT); }


void loop() {
void loop() {
float distance, duration;
float distance, duration;
digitalWrite(TRIG, HIGH);
digitalWrite(TRIG, HIGH);
delayMicroseconds(1);
delayMicroseconds(1);
digitalWrite(TRIG,LOW);
digitalWrite(TRIG,LOW);


duration = pulseIn(ECHO,HIGH);
duration = pulseIn(ECHO,HIGH);
distance = ((float)(duration*340)/10000)/2;
distance = ((float)(duration*340)/10000)/2;
Serial.println(distance);
Serial.println(distance);


int i;
int i;
if (distance <= 32) {
if (distance <= 32) {
i=map(distance,0,32,0,7);
i=map(distance,0,32,0,7);
tone (speaker, melody[i], 250);
tone (speaker, melody[i], 250);
delay (300);
delay (300);
}
}
else {
else {
noTone(speaker);
noTone(speaker);



Revision as of 09:59, 1 December 2021

int melody[32] = { 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 <= 32) {

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

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

delay (300);

}

else {

noTone(speaker);

}


}