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;