Advanced AVR 3.0 time management - Juno Edu 1.0 + HC-SR04
No hard core math or physics. Just by adjusting the timer's compare value, I am able to get the HC-SR04 to output a very precise and responsive 8-bit value with nothing but a ruler. Distance is arbitrary, and 20mm-4000mm can be represented with an 8-bit number if precision is not as critical. Here the distance is represented in millimeter, with near pinpoint accuracy.
Because distance is proportional to ping-back-time, the speed of sound is irrelevant. The speed is the factor or ratio between distance and time, and according to the datasheet, it's us/5.8= 1 millimeter; 0.001/333=3*2=6us, so about 6us for 1 millimeter, and it's about right.
The actual formula for the timer is 16000000/(1/0.000006)=96; 95 is the actual compare value, and 96 is the number of 1-clock-cycle-cpu instructions clocked at 16MHz for one increment of the counter at 1 millimeter assuming the speed of sound is 333m/s. It's possible for the HC-SR04 to measure in 1 millimeter precision.
PS. Speed of sound is different at different ambient temperature, and 333m/s is nice because it's easier to remember.