# Arduino: Sonar Rangefinder

This sonar rangefinder is called an HC-SR04. It's cheap (around \$5) and easy to use.

A sonar rangefinder sends out a pulse of sound, too high to hear, then listens for the echo and times how long it takes. This is the same way bats and dolphins find their way around.

The rangefinder has four pins:
The one labeled VCC goes to the 5v pin on the Arduino.
The one labeled GND goes to ground (Gnd).
The other two go to two digital pins on the Arduino -- say, 7 and 8.

To operate it, set the Trig pin high for 10 microseconds. You can use delayMicroseconds(10) for that.
Then read the Echo pin and time how long the signal stays high: you can use an Arduino library routine called pulseIn() for that.

The code looks like this:

```    // Send the trigger high for 10 microseconds or more
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);

// Now read how many microseconds the echo pin stays high:
int duration = pulseIn(echoPin, HIGH);

// Divide by 140 to convert to inches (approximately)
int distance = duration / 140;
```

In practice, sometimes it might get bogus readings now and then. So it's a good idea to read it several times and average the readings, like this:

```    int duration = 0;
for (int i=0; i < num_reads; ++i)
{
// Send the trigger high for 10 microseconds or more
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);

// Now read how many microseconds the echo pin stays high:
duration += pulseIn(echoPin, HIGH);    // microseconds
}
// Take the average, then divide by 140 to convert to inches:
distance = duration / num_reads / 140;
```