Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//06_distance_speaker
//速さを測定して、速かったら鳴る
//SchooMyとかいてあるところまですすもう
#define echoPin 19
#define trigPin 18
#define SPEAKER 10
#define do 262
#define re 294
#define mi 330
#define fa 349
#define so 392
#define ra 440
#define shi 494
#define do2 523
double Duration = 0;
double Distance1 = 0;
double Distance2 = 0;
double Speed = 0;
void setup() {
Serial.begin(9600);
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
pinMode(SPEAKER, OUTPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); //超音波を出力
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
Duration = pulseIn(echoPin, HIGH); //センサからの入力
if (Duration > 0) {
Duration = Duration / 2; //往復距離を半分
Distance1 = Duration * 340 * 100 / 1000000; //音速を340m/sに設定
//Serial.print("スタート:");
//Serial.print(Distance1);
//Serial.println("cm");
}
delay(200);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); //超音波を出力
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
Duration = pulseIn(echoPin, HIGH); //センサからの入力
if (Duration > 0) {
Duration = Duration / 2; //往復距離を半分
Distance2 = Duration * 340 * 100 / 1000000; //音速を340m/sに設定
//Serial.print("フィニッシュ:");
//Serial.print(Distance2);
//Serial.println("cm");
}
delay(100);
Speed = (Distance1 - Distance2) * 5;
Serial.print("Speed:");
Serial.print(Speed);
Serial.println("cm/s");
delay(10);
//SchooMy
//プログラムはここからかえます
if ((abs(Speed) > 20) && (abs(Speed) < 100)) { //この速さの間の時は
tone(SPEAKER, do); //鳴る
delay(100); //待つ
} else {
noTone(SPEAKER); //鳴らない
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment