超音波倒車雷達

 // 腳位定義

const int trigPin = 7;     // 超音波感測器 Trig 腳位

const int echoPin = 6;     // 超音波感測器 Echo 腳位

const int buzzerPin = 8;   // 蜂鳴器腳位


// 取得距離(單位:公分)

long getDistance() {

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);


  long duration = pulseIn(echoPin, HIGH);

  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 > 70) {

    // 安全距離:不發聲

    noTone(buzzerPin);

    delay(500);

  } else if (distance > 30) {

    // 中距離:慢速嗶嗶

    tone(buzzerPin, 1000); // 發出聲音

    delay(100);

    noTone(buzzerPin);     // 停止聲音

    delay(500);            // 間隔時間

  } else if (distance > 10) {

    // 接近:中速嗶嗶

    tone(buzzerPin, 1000);

    delay(100);

    noTone(buzzerPin);

    delay(300);

  } else {

    // 非常接近:快速嗶嗶

    tone(buzzerPin, 1000);

    

  }

}


留言