Created
June 24, 2019 23:46
-
-
Save likersacademia/197e2af51224ba2c817a3999df697a94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//近づいて5秒立ったら音が鳴る | |
#define echoPin 19 | |
#define trigPin 18 | |
#define SPEAKER 10 | |
double Duration = 0; | |
double Distance = 0; | |
int count = 0; | |
void setup() { | |
Serial.begin(9600); | |
pinMode(echoPin,INPUT); | |
pinMode(trigPin,OUTPUT); | |
pinMode(SPEAKER,OUTPUT); | |
} | |
int flag_speaker = 0; // speakerから音を出すのためのフラグ | |
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; //往復距離を半分 | |
Distance = Duration*340*100/1000000; //音速を340m/sに設定 | |
Serial.print("Distance:"); | |
Serial.print(Distance); | |
Serial.println("cm"); | |
} | |
//ここからプログラムを変更することができます。 | |
if (Distance < 10) { //距離を設定します。(Distance < 10なので、10より小さくなったときです) | |
count++; | |
Serial.println( count ); | |
}else{ | |
count=0; | |
noTone(SPEAKER); | |
} | |
if (count > 5){ //距離を設定します | |
if( flag_speaker == 0 ){ // フラグが0ならば音が消える | |
tone(SPEAKER,604) ; // 1) 数字をかえてみよう | |
delay(200); // 1) 数字をかえてみよう | |
flag_speaker++; | |
}else{ // フラグが1ならば音が消える | |
noTone(SPEAKER); | |
flag_speaker = 0; | |
} | |
} | |
delay(1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment