GPIO - 通過超聲波模組測量距離

材料準備

  • AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1

  • HC-SR04 Ultrasonic x 1

  • 降壓電阻 或 Level converter

範例説明

HC-SR04 is a module that uses ultrasound to measure the distance. It looks like a pair of eyes in its appearance, therefore it’s often installed onto robot-vehicle or mechanical bugs to be their eyes. The way it works is that first we “toggle high” the TRIG pin (that is to pull high then pull low). The HC-SR04 would send eight 40kHz sound wave signal and pull high the ECHO pin. When the sound wave returns back, it pull low the ECHO pin.

../../../../_images/image149.png

Assume the velocity of sound is 340 m/s, the time it takes for the sound to advance 1 cm in the air is 340*100*10^-6 = 29 us. The sound wave actually travels twice the distance between HC-SR04 and the object, therefore the distance can be calculated by (time/29) / 2 = time / 58. The working voltage of HC-SR04 is 5V. When we pull high the ECHO pin to 5V, the voltage might cause damage to the GPIO pin of Ameba. To avoid this situation, we need to drop the voltage as follows:

AMB21 / AMB22 接線的方式如下

../../../../_images/image246.png

AMB23 接線的方式如下

../../../../_images/image2-13.png

BW16 接線的方式如下

../../../../_images/image2-3.png

BW16-TypeC Wiring Diagram:

../../../../_images/image2-4.png

We pick the resistors with resistance 1:2, in the example we use 10kΩ and 20kΩ. If you do not have resistors in hand, you can use level converter instead.The TXB0108 8 channel level converter is a suitable example:

AMB21 / AMB22 接線的方式如下

../../../../_images/image331.png

AMB23 接線的方式如下

../../../../_images/image3-13.png

BW16 接線的方式如下

../../../../_images/image3-33.png

BW16-TypeC Wiring Diagram:

../../../../_images/image3-4.png

Next, open the sample code in “File” “Examples” “AmebaGPIO” “HCSR04_Ultrasonic”

../../../../_images/image423.png

編譯並上傳到Ameba,完成之後按下Reset按鈕。打開Serial Monitor,可以看到每兩秒量出一筆數據。

../../../../_images/image516.png

因為HC-SR04使用超音波反射的方式,所以如果遇到表面粗糙或柔軟,音波可能會散射或被吸引,因而影響實驗數據,所以可以先找表面平整的物體做測試。

程式碼説明

每次測量時,將TRIG pin pull high 10us之後再pull low告訴HC-SR04準備測量:

digitalWrite(trigger_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin, LOW);

之後使用pulseIn測量ECHO pin pull high的時間

duration = pulseIn (echo_pin, HIGH);

再根據公式算出距離並印在Serial Monitor上

distance = duration / 58;