Skip to content

Instantly share code, notes, and snippets.

@Nekodigi
Created August 26, 2020 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nekodigi/e774b86c1fa671c6df8baafbfb2a348d to your computer and use it in GitHub Desktop.
Save Nekodigi/e774b86c1fa671c6df8baafbfb2a348d to your computer and use it in GitHub Desktop.
#define tonePin 3
#define echoPin 4 // Echo Pin
#define trigPin 5 // Trigger Pin
double Duration = 0; //受信した間隔
double Distance = 0; //距離
void setup() {
Serial.begin( 9600 );
pinMode( echoPin, INPUT );
pinMode( trigPin, 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; //往復距離を半分にする
Distance = Duration*340*100/1000000; // 音速を340m/sに設定
Serial.print("Distance:");
Serial.print(Distance);
Serial.println(" cm");
if(Distance < 50){
double f = pow(2, Distance/12)*55;
tone(tonePin, f);
}else noTone(tonePin);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment