超音波感測器 範例
2025/01/29 21:56
瀏覽39
迴響0
推薦0
引用0
const int pingPin = 7; // PING))) 的 SIG 腳位連接到 D7
void setup() {
Serial.begin(9600); // 初始化 Serial Monitor
}
void loop() {
// 發送超音波脈衝並測量回傳時間
long duration = getPingDuration(pingPin);
// 計算距離(單位:公分)
float distance = duration * 0.0343 / 2;
// 輸出距離到 Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // 延遲 500 毫秒
}
// 函數:讀取 PING))) 的回傳時間
long getPingDuration(int pin) {
// 設置 pin 為輸出模式
pinMode(pin, OUTPUT);
// 發送 2 微秒的低電平脈衝以確保觸發
digitalWrite(pin, LOW);
delayMicroseconds(2);
// 發送 5 微秒的高電平脈衝以觸發超音波
digitalWrite(pin, HIGH);
delayMicroseconds(5);
digitalWrite(pin, LOW);
// 設置 pin 為輸入模式以讀取回傳信號
pinMode(pin, INPUT);
// 使用 pulseIn 函數測量回傳時間
return pulseIn(pin, HIGH);
}
你可能會有興趣的文章:
限會員,要發表迴響,請先登入



