Last active
August 20, 2019 02:18
-
-
Save baobao/aaea3c62ae39755aef2c6068b8c4f713 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
// コメントアウトを外すと超音波センサーの結果を出力 | |
//#define MEASUREMENT | |
// 出力ピン | |
int trigPin = 6; | |
// インプットピン | |
int echoPin = 7; | |
// スピーカーピン | |
int tonePin = 8; | |
// LEDピン | |
int ledPin = 12; | |
// しきい値を100mmとする | |
int threshold = 100; | |
void setup() | |
{ | |
Serial.begin(9600); | |
pinMode(trigPin, OUTPUT); | |
pinMode(echoPin, INPUT); | |
pinMode(ledPin, OUTPUT); | |
pinMode(tonePin, OUTPUT); | |
} | |
void loop() | |
{ | |
// リセット | |
digitalWrite(trigPin, LOW); | |
delayMicroseconds(2); | |
// 超音波を100μ秒照射 | |
digitalWrite(trigPin, HIGH); | |
delayMicroseconds(100); | |
// 超音波を照射停止 | |
digitalWrite(trigPin, LOW); | |
// duration : エコーが返って来た時間(マイクロ秒) | |
float duration = pulseIn(echoPin, HIGH); | |
// ターゲットまでの距離を算出(ミリメートル) | |
unsigned int distance = int(duration * 340 * 0.5 * 0.001); | |
#if MEASUREMENT | |
Serial.print("時間 : "); | |
Serial.print(duration); | |
Serial.print("μs / 距離 : "); | |
Serial.print(distance); | |
Serial.print("mm"); | |
Serial.print("\n"); | |
#endif | |
bool isOutput = distance < threshold; | |
digitalWrite(ledPin, isOutput ? HIGH : LOW); | |
if (isOutput) | |
{ | |
// 近づいたら音を鳴らす | |
tone(tonePin, 232, 30); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment