Arduino示例代码讲解:Ping
Arduino示例代码讲解:Ping
- Ping
-
- 功能概述
-
-
- 硬件部分:
- 软件部分:
-
- 代码逐行解释
-
-
- 定义常量
- `setup()` 函数
- `loop()` 函数
- `microsecondsToInches()` 函数
- `microsecondsToCentimeters()` 函数
-
- 工作原理
Ping
这段代码是一个Arduino示例程序,用于读取Parallax PING)))超声波测距传感器的数据,并计算出距离最近物体的距离。它将距离值通过串行通信发送到计算机,适用于需要测量距离的场景。
/* Ping))) Sensor
This sketch reads a PING))) ultrasonic rangefinder and returns the
distance to the closest object in range. To do this, it sends a pulse
to the sensor to initiate a reading, then listens for a pulse
to return. The length of the returning pulse is proportional to
the distance of the object from the sensor.
The circuit:
* +V connection of the PING))) attached to +5V
* GND connection of the PING))) attached to ground
* SIG connection of the PING))) attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping
created 3 Nov 2008
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
*/
// this constant won't change. It's the pin number
// of the sensor's output:
const int pingPin = 7;
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite