3
This sketch reads a PING))) ultrasonic rangefinder and returns the
4
distance to the closest object in range. To do this, it sends a pulse
5
to the sensor to initiate a reading, then listens for a pulse
6
to return. The length of the returning pulse is proportional to
7
the distance of the object from the sensor.
9
based on the original code from the tutorial at:
10
http://www.arduino.cc/en/Tutorial/Ping
12
This example code is in the public domain.
19
long duration, inches, cm;
22
//pinMode(13, OUTPUT);
23
pinMode(pingPin, OUTPUT);
24
pinMode(inPin, INPUT);
28
long microsecondsToInches(long microseconds)
30
// According to Parallax's datasheet for the PING))), there are
31
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
32
// second). This gives the distance travelled by the ping, outbound
33
// and return, so we divide by 2 to get the distance of the obstacle.
34
return microseconds / 74 / 2;
37
long microsecondsToCentimeters(long microseconds)
39
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
40
// The ping travels out and back, so to find the distance of the
41
// object we take half of the distance travelled.
42
return microseconds / 29 / 2;
47
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
48
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
49
//pinMode(pingPin, OUTPUT);
50
digitalWrite(pingPin, LOW);
52
digitalWrite(pingPin, HIGH);
53
delayMicroseconds(10);
54
digitalWrite(pingPin, LOW);
55
//delayMicroseconds(2);
58
// pulse whose duration is the time (in microseconds) from the sending
59
// of the ping to the reception of its echo off of an object.
61
duration = pulseIn(inPin, HIGH);
63
// convert the time into a distance
64
inches = microsecondsToInches(duration);
65
cm = microsecondsToCentimeters(duration);
67
Serial.print("Distance: [");
69
Serial.print("]inches. [");
71
Serial.print("]cm\r\n");