This is how to use the HC-SR04 Ultrasonic Distance Sensor. This is the most ubiquitous ultrasonic sensor for Arduino.
It works by sending out Ultrasonic pulses (higher-frequency-than-sound) and timing how long it takes for the echo to return. Like a repetitive “ping”.
Wire the sensor as shown above.
Vcc -> 5V
Trig -> D12
Echo -> D11
Gnd -> Gnd
The code below triggers the HC-SR04 to send out Ultrasonic Pulses by pulsing D12 (Trig). It then measures the time until the response has been received onto D11 (Echo).
We’re going to use the NewPing library to do the timing behind the scenes.
You can get that from here. Add the library to the Arduino IDE (1.0.5) : Sketch -> Import Library -> Add Library…
Here’s some example code. Open the Serial Monitor to see the distance.
(You can get this code from File -> Examples -> NewPing -> NewPingExample)