Is it possible to create a delay in program only using TCNT timer

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Is it possible to create a delay in program only using TCNT timer

3,010 Views
embedlov
Contributor I
Hi all!!
 
I have tried to use the TCNT timer to create a delay in my program.
 
MCU : 9S12XDP512
Osc.Clock: 8MHz
Bus Clock : 40MHz
 
I called the below function to make a delay by adding the required delay value "ms" to the present TCNT and then compare the TCNT value until it reaches "tCNT".
 
The code works fine. But how can i know that the required delay has been achieved?
void Delay(UINT ms)
{
 tCNT = TCNT;
 tCNT += ms;
 while (tCNT != TCNT)
 ;
}
 
I could not see the free running TCNT register getting incremented in the True time simulator.
 
Any suggestions?
 
embedlov
 
Labels (1)
0 Kudos
Reply
4 Replies

870 Views
kef
Specialist I
It's a bad idea to wait for exact match tCNT==TCNT. Even at max possible prescaler single timer tick takes just 128 bus cycles. Do some math or serve some longer interrupt and TCNT will become > tCNT.
Also " while (tCNT != TCNT)" takes more than 1 bus cycle so it won't work properly with timer prescaler =1 even if interrupts are disabled.
You can use something like this:
 
 
void Delay(UINT dly)
{
short tCNT = TCNT + dly;
 while (  (signed short)(TCNT-tCNT)  < 0);
}
 
Limitation of this code is that dly should be less than 2^15.
0 Kudos
Reply

870 Views
Lundin
Senior Contributor IV
Well... lets say that TCNT is 65535 and dly is 1. tCNT will then become 0 and the expression will be evaluated as

while( (signed short)(65535 - 0) < 0);

So the loop will break even though no time has passed.

The serious solution is to use one of the TC channels, which will save you the headache of integer overflows as well.
0 Kudos
Reply

870 Views
kef
Specialist I
(signed short)65535 is negative, it's -1 and is less than 0. So loop will continue.
 
 
Regards
0 Kudos
Reply

870 Views
Lundin
Senior Contributor IV
Oops, you are correct, I forgot the typecast.

But still, the timer channels is a better solution since they won't keep the CPU busy doing comparisons.
0 Kudos
Reply