友情提示:680元/半年,儿童学编程,就上码丁实验室。
Arduino代码
请点击此处输入图片描述
请点击此处输入图片描述
解释一下distance=duration/58得到距离的原理:
This line is used to convert a time interval into distance.
声音在空气中传播速度大概为 340m/s, 也就是 29 微秒每厘米. 因为超声波传感器测量到的是来回。 因此,是2*29=58微秒每厘米 。
串口输出的数据如图:
串口数据
使用超声波库
Ultrasonic库对SR04测距进行了封装,使得使用更为简单,可以用Arduino的库管理工具下载。
安装完之后,其自带一个简单的例子:
请点击此处输入图片描述
然后只需要将对应的针脚更改好就行了。
如本例中使用7,8针脚
/*
* Ultrasonic Simple
* Prints the distance read by an ultrasonic sensor in
* centimeters. They are supported to four pins ultrasound
* sensors (liek HC-SC04) and three pins (like PING)))
* and Seeed Studio sesores).
*
* The circuit:
* * Module HR-SC04 (four pins) or PING))) (and other with
* three pins), attached to digital pins as follows:
* ——————— ———————
* | HC-SC04 | Arduino | | 3 pins | Arduino |
* ——————— ———————
* | Vcc | 5V | | Vcc | 5V |
* | Trig | 12 | OR | SIG | 13 |
* | Echo | 13 | | Gnd | GND |
* | Gnd | GND | ———————
* ———————
* Note: You need not obligatorily use the pins defined above
*
* By default, the distance returned by the distanceRead()
* method is in centimeters, to get the distance in inches,
* pass INC as a parameter.
* Example: ultrasonic.distanceRead(INC)
*
* created 3 Apr 2014
* by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
* modified 23 Jan 2017
* by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
* modified 03 Mar 2017
* by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
*
* This example code is released into the MIT License.
*/
#include <Ultrasonic.h>
/*
* Pass as a parameter the trigger and echo pin, respectively,
* or only the signal pin (for sensors 3 pins), like:
* Ultrasonic ultrasonic(13);
*/
Ultrasonic ultrasonic(8, 7);
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print(“Distance in CM: “);
// Pass INC as a parameter to get the distance in inches
Serial.println(ultrasonic.distanceRead());
delay(1000);
}
喜欢文章,欢迎大家转发!!!