// 超音波腳位定義
const int trigPin = 7; // 超音波感測器 Trig 腳位
const int echoPin = 6; // 超音波感測器 Echo 腳位
// 蜂鳴器腳位定義
const int buzzerPin = 13; // 蜂鳴器接腳位
// 取得距離(單位:公分)
long getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000UL); // 加入逾時避免卡住
if (duration == 0) return -1; // 逾時視為無效
long distance = duration * 0.034 / 2; // 聲速換算
return distance;
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
Serial.begin(9600); // 顯示距離用
}
void loop() {
long distance = getDistance();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance > 100 || distance <= 0) {
noTone(buzzerPin); // 超過範圍或無效值則靜音
delay(300);
} else if (distance <= 15) {
// 15 公分內 → 長鳴
tone(buzzerPin, 1000); // 持續鳴叫
delay(50); // 小延遲避免過度刷新
} else {
// 根據距離決定嗶嗶間隔
int beepDelay;
if (distance > 80) {
beepDelay = 600; // 很遠 → 慢速嗶嗶
} else if (distance > 50) {
beepDelay = 400; // 中距離 → 中速嗶嗶
} else if (distance > 30) {
beepDelay = 200; // 接近 → 快速嗶嗶
} else {
beepDelay = 50; // 非常近 → 幾乎連續嗶嗶
}
tone(buzzerPin, 1000); // 播放固定頻率嗶聲
delay(100); // 嗶聲持續時間
noTone(buzzerPin); // 停止
delay(beepDelay); // 間隔時間依距離而定
}
}
留言
張貼留言