Debian Codegraph @

examples/06.Sensors/Ping/Ping.ino

raw
1 /*
2 Ping))) Sensor
3
4 This sketch reads a PING))) ultrasonic rangefinder and returns the distance
5 to the closest object in range. To do this, it sends a pulse to the sensor to
6 initiate a reading, then listens for a pulse to return. The length of the
7 returning pulse is proportional to the distance of the object from the sensor.
8
9 The circuit:
10 - +V connection of the PING))) attached to +5V
11 - GND connection of the PING))) attached to ground
12 - SIG connection of the PING))) attached to digital pin 7
13
14 created 3 Nov 2008
15 by David A. Mellis
16 modified 30 Aug 2011
17 by Tom Igoe
18
19 This example code is in the public domain.
20
21 https://www.arduino.cc/en/Tutorial/BuiltInExamples/Ping
22 */
23
24 // this constant won't change. It's the pin number of the sensor's output:
25 const int pingPin = 7;
26
27 void setup() {
28 // initialize serial communication:
29 Serial.begin(9600);
30 }
31
32 void loop() {
33 // establish variables for duration of the ping, and the distance result
34 // in inches and centimeters:
35 long duration, inches, cm;
36
37 // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
38 // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
39 pinMode(pingPin, OUTPUT);
40 digitalWrite(pingPin, LOW);
41 delayMicroseconds(2);
42 digitalWrite(pingPin, HIGH);
43 delayMicroseconds(5);
44 digitalWrite(pingPin, LOW);
45
46 // The same pin is used to read the signal from the PING))): a HIGH pulse
47 // whose duration is the time (in microseconds) from the sending of the ping
48 // to the reception of its echo off of an object.
49 pinMode(pingPin, INPUT);
50 duration = pulseIn(pingPin, HIGH);
51
52 // convert the time into a distance
53 inches = microsecondsToInches(duration);
54 cm = microsecondsToCentimeters(duration);
55
56 Serial.print(inches);
57 Serial.print("in, ");
58 Serial.print(cm);
59 Serial.print("cm");
60 Serial.println();
61
62 delay(100);
63 }
64
65 long microsecondsToInches(long microseconds) {
66 // According to Parallax's datasheet for the PING))), there are 73.746
67 // microseconds per inch (i.e. sound travels at 1130 feet per second).
68 // This gives the distance travelled by the ping, outbound and return,
69 // so we divide by 2 to get the distance of the obstacle.
70 // See: https://www.parallax.com/package/ping-ultrasonic-distance-sensor-downloads/
71 return microseconds / 74 / 2;
72 }
73
74 long microsecondsToCentimeters(long microseconds) {
75 // The speed of sound is 340 m/s or 29 microseconds per centimeter.
76 // The ping travels out and back, so to find the distance of the object we
77 // take half of the distance travelled.
78 return microseconds / 29 / 2;
79 }