Skip to content

Instantly share code, notes, and snippets.

@gskielian
Created July 13, 2013 21:53
Show Gist options
  • Select an option

  • Save gskielian/5992363 to your computer and use it in GitHub Desktop.

Select an option

Save gskielian/5992363 to your computer and use it in GitHub Desktop.
long getDistance() {
long duration, d1, d2, d3, cm;
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(80); // was 10
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
// get 3 readings, use middle one to avoid noise.
d1 = pulseIn(echoPin, HIGH);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(80); // was 10
digitalWrite(trigPin, LOW);
d2 = pulseIn(echoPin, HIGH);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(80); // was 10
digitalWrite(trigPin, LOW);
d3 = pulseIn(echoPin, HIGH);
if (d1 < d2 && d2 < d3) {
duration = d2;
}
if (d1 < d3 && d3 < d2) {
duration = d3;
}
if (d2 < d3 && d3 < d1) {
duration = d3;
}
if (d2 < d1 && d1 < d3) {
duration = d1;
}
if (d3 < d2 && d2 < d1) {
duration = d2;
}
if (d3 < d1 && d1 < d2) {
duration = d1;
}
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
return cm;
}
long microsecondsToCentimeters(long microseconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment