ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 58

Project: Ultrasonic Distance Meter

Time a sound echo.

An ultrasonic sensor sends a short burst and raises a pin until the echo returns. Measure how long that pin stays high with a timer.

Sound travels about 343 metres per second in air, and the pulse covers the distance twice, so distance equals time multiplied by 343, divided by 2.

Show the result on a display, and average several readings to smooth it.

EXAMPLE
uint32_t cm_from_us(uint32_t us) {
    return us * 343 / 20000;   /* microseconds to centimetres */
}