Ultrasonic Distance Sensor

Ultrasonic sensors can be used to measure the distances to hard (preferably stationary)

This packet shows how to use one particular ultrasonic sensor, the HC-SR04. It is rated to
be able to detect objects as near as 2cm and as distant as 400cm, with a precision of ±0.3cm.

How ultrasonic sensors work

Ultrasonic sensors emit a high frequency (i.e., “ultra-sonic”) sound wave, and then
measure the amount of time it takes for that sound wave to reflect off some surface
back to it. Therefore, ultrasonic sensors have two parts: a sender and a receiver:

The sender, aka trigger
This component is activated by setting it at a HIGH state for 10 µs. This causes
the trigger unit to emit a high-frequency sound wave consisting of 8 pulses. This
sound wave will bounce off nearby objects.
The receiver, aka echo
This component detects sound waves at the “correct” frequency (i.e., the frequency
used by the trigger). When it makes a detection, it reports a long int value which
is twice the time t it takes sound to travel to that object.

Since the speed of sound is (roughly) constant at 0.034 cm/µs, the
distance to the detected object is:

distance = t ∗ 0.034 / 2;

(Divide by a factor of 2 because the travel time t includes both the
time for the sound wave to reach the obstacle plus the time to return
from it.)

Applications of ultrasonic sensors

These sensors are especially useful for detecting the distances to objects that
may be moving toward or away from the observer, but not across the field of view
of the observer. For example, they are useful in robots to detect when the robot
is approaching a wall. They are useful in manufacturing to measure the height
of a growing or shrinking pile of “stuff”.

Ultrasonic sensors can succeed in measuring distances to objects that are difficult to
“see” either because they are in unlit areas or because their color resembles the surroundings.

However, ultrasonic sensors are a poor choice when the target being tracked
is made of some soft material; such objects will not reflect the sound
wave very efficiently.