int hcTrigerPin = 11;
int hcEchoPin = 10;
int speakerPin = 7;
void setup() {
Serial.begin(9600);
pinMode(hcTrigerPin, OUTPUT);
pinMode(hcEchoPin, INPUT);
pinMode(speakerPin, OUTPUT);
}
void loop() {
long duration, distance;
// 發送超音波脈衝
digitalWrite(hcTrigerPin, HIGH);
delayMicroseconds(10);
digitalWrite(hcTrigerPin, LOW);
// 接收回音時間
duration = pulseIn(hcEchoPin, HIGH);
// 計算距離(公分)
distance = duration * 0.0343 / 2; // 可微調
// 使用 map 函數設定蜂鳴器的音調頻率(頻率範圍可自行調整)
int toneFrequency = 392; // 距離越近,頻率越高
int beepDelay = map(distance, 0, 200, 0, 1000); // 距離越近,間隔越短
// 播放聲音
if (distance < 200){
tone(speakerPin, toneFrequency);
digitalWrite(LED_BUILTIN, HIGH);
delay(200);
noTone(speakerPin); // 停止聲音
digitalWrite(LED_BUILTIN, LOW);
}
// 顯示距離
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(beepDelay); // 每次讀取延遲 100 毫秒
}