企石镇做网站中国最新消息今天
Arduino示例代码讲解:Ping
- Ping
- 功能概述
- 硬件部分:
- 软件部分:
- 代码逐行解释
- 定义常量
- `setup()` 函数
- `loop()` 函数
- `microsecondsToInches()` 函数
- `microsecondsToCentimeters()` 函数
- 工作原理
Ping
这段代码是一个Arduino示例程序,用于读取Parallax PING)))超声波测距传感器的数据,并计算出距离最近物体的距离。它将距离值通过串行通信发送到计算机,适用于需要测量距离的场景。
/* Ping))) SensorThis sketch reads a PING))) ultrasonic rangefinder and returns thedistance to the closest object in range. To do this, it sends a pulseto the sensor to initiate a reading, then listens for a pulseto return. The length of the returning pulse is proportional tothe 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 7http://www.arduino.cc/en/Tutorial/Pingcreated 3 Nov 2008by David A. Mellismodified 30 Aug 2011by Tom IgoeThis 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