Recipe
Turn an echo time into a distance
Use when: an ultrasonic module reports a round-trip echo time
Goal: the distance to the target in centimetres, corrected for air temperature
Taught in Distance and proximity
-
1
If the measured time is 0, report "no echo" and stop.
Example
pulseInreturned 0 after its 30,000 µs timeout.Why: 0 means nothing came back in time, not that the target is touching the sensor.
-
2
c \approx 331.3 + 0.606\,T m/s, with T in °C.
Example
At 25 °C: c = 331.3 + 15.15 = 346.5 m/s.
Why: sound is faster in warm air, and a fixed 20 °C value is off by about 0.17% per degree.
-
3
d = t \times c / 2, with t in seconds and d in metres; multiply by 100 for centimetres.
Example
t = 1166 µs: d = 0.001166 \times 346.5 / 2 = 0.2020 m, about 20.2 cm.
Why: the echo time covers the distance twice, out and back.
Common mistakes
- Forgetting to halve: every distance comes out twice as far.
- Mixing units: µs times m/s gives micrometres until you scale it.
- Treating 0 as a real distance.