Timer in C

Thread Starter

Bob T.

Joined Oct 22, 2012
35
Hello every one ....
I want to make a sonar range finder and i used an amplifier for a larger distance detecting.
The problem is that i dont know how to use the timer in C.

I am using pic16f877A, 20MHz
Thank you .............
Need help...........
 

mitko89

Joined Sep 20, 2012
127
If you know the control registers for the timer, just fill them in as ordinary variables. Check the header file and see the names and structure of the registers you need. C is much closer to assembly than any other language of high level.
 

JohnInTX

Joined Jun 26, 2012
4,787
The best way to do this is to use ECCP1 configured to capture an edge (see CCPCON1 modes 0100 or 0101). Design the circuit so that the echo from the sonar drives the capture input. Configure the capture to use TMR1.

To run it:
Clear the timer, generate the ping pulse, clear CCP1IF then start the timer. When the echo is detected, the current value of the timer will be captured and CCP1IF will be set. The value in the capture registers will be the value of the timer when the echo arrived.

Determine the max time (in uSEC) for the max range allowed and convert to timer counts. The count rate will be the XTAL freq / 4 / (an optional prescaler). The count corresponding to the max range must fit into 16 bits.

You can use TMR1IF to see if the timer has overflowed (this can happen if you don't get an echo and is a useful indication).

How does that sound so far?
 

JohnInTX

Joined Jun 26, 2012
4,787
Sure. If you are getting acceptable performance, then its OK.

I use the ECCP to avoid the overhead of the timer continuing to run between the time the return pulse is detected and the time I get around to reading the time. The ECCP does this automatically by latching the timer value when the echo is received and interrupting the processor, allowing the program the time it needs to get around to servicing the echo.

As long as your ranges are stable and you have time to do other processing as needed, you are good to go. If not, we can help you configure the ECCP.

Have fun.
 
Top