# Lesson 3:超音波模組 [TOC] ## 超音波模組 ![](http://www.codedata.com.tw/wp-content/uploads/2015/06/mBlockArduino12-1.jpg) * HC-SR04 腳位從左至右分別為 Vcc、Trig、Echo 與 GND * 超音波的發射與接收依靠 Trig 與 Echo 這兩個腳位。 * 用`digitalWrite()`送出 10 微秒的 5V 高電位訊號給 Trig,觸發超音波的發射 * 接著 Echo 腳位就會處於 `5V` 高電位狀態,當接收到反射的超音波訊號時,Echo腳位就會處於 `0V` 低電位狀態 * 藉由計算Echo電位從high到LOW的時間,可知超音波來回時間而計算與物體距離。 * ![](https://i.imgur.com/N6pCtQT.png) * 函式 `pulseIn(pin, value, timeout)` :讀取pin腳的脈衝時間 ![](https://i.imgur.com/d7un2v0.png) * 實作:超音波模組 ```C++ const int Trig_Pins = 3;//trig 腳位 const int Echo_Pins = 2;// echo 腳位 float get_distance(int trig, int echo){ //計算距離 float duration; digitalWrite(trig, HIGH); delayMicroseconds(10); //給予trig 10us TTL pulse,讓模組發射聲波 digitalWrite(trig, LOW); duration = pulseIn(echo, HIGH, 5000000);//紀錄echo電位從high到low的時間,就是超音波來回的時間,若5秒內沒收到超音波則回傳0 return duration / 29 / 2; // 聲速340m/s ,換算後約每29微秒走一公分,超音波來回所以再除2 } void setup() { Serial.begin(9600); pinMode(Trig_Pins, OUTPUT); pinMode(Echo_Pins, INPUT); } void loop() { float result= get_distance( Trig_Pins, Echo_Pins); Serial.print(result); Serial.println("cm"); delay(1000); } ``` ![](https://i.imgur.com/pmIsPnB.png) * 課堂作業:利用超音波模組控制LED燈,距離5cm~30cm之間,距離越近LED燈閃爍越快