Software
Downloadable Code Files.txt
This device uses TIM2 and TIM14 to generate pulses and measure the time of flight (TOF).
​
TIM2 is set up the the PWM mode and used to generate 8 pulses. In code we assume the minimum time we can measure is 700us because, like a bell, the transducer rings and dies out after the pulses stop (Figure 1).
Transducer 1 and 2

Tx
Rx
Ringing time
Object Seen
Figure 1
TIM14 is set up in input capture mode which allows the timer to run until the receiver send back pulses. When it does, using TIM14_IRQHandler(); the first stop pulse after 700us is captured and the time is recorded.
​
distance = (speed_of_sound_cm*(TIM14_us + 700us)/1000000)/2;
distance = (34300.0584*(EchoTime)/1000000)/2;
​
There is also some error handling where if the distance is larger than 200cm or less than 10cm the distance will be equal to -2 or -1. If there is no return signal for 50ms (1500cm) the code will rerun.

Object Seen, Record time of first pulse.
Ignore all pulses for 700us
Start Time