kinjalgp said:
You really need to use interrupt in this case. When you send the ultrasonic pulse, turn on the timer and wait for echo-interrupt to arrive. In the interrupt handler, turn-off the timer. The remaining timer value will be directly proportional to the pulse-delay.
For 89C52, the timer increments every 12 clock cycles. Now its easy for you to calculate exact time between send and received pulses.
Basically that's my second proposal from some days ago except that you use an internal timer to count instead of external pulses form an oscillator.
kinjalgp, you need:
1) An internal timer to count time.
2) An edge sensitive interrupt driven input on your µC to check for the echo pulse
3) An output pin to enable the US pulse
How to do it:
A) In the main loop
If previous US pulse was finished ("blnPulseAnalysed" high) then
1) Set output pin to send an new US pulse
2) Start internal timer
3) Enable interrupt on P3.2 so that the pin can detect the echo pulse
4) Reset bit "blnPulseAnalysed"
Endif
Do all other things that needs to be done, but for the US part you're finished for now in your main loop.
B) In the ISR of P3.2
1) Stop internal timer
2) Read internal timer and convert it to TOF
3) Disable interrupt on P3.2
4) Set bit "blnPulseAnalysed" so that your main code knows that the pulse was analysed and he can send a new one, display the result, ...
RETI
Try to convert this "flowchart" to code and let us know what you made of it...
One thing is for sure, you need to remove the line
Code:
while (TF0 == 0); // Loop until Timer 0 overflows (TF0 == 1)
in your previous code.