Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: [AVR-Chat] Another C-ish question

2009-03-25 by David Kelly

On Mar 24, 2009, at 1:36 PM, David VanHorn wrote:

> I frequently end up using a bunch of timers in a 1mS ISR, that are
> decremented to zero by the ISR, and set by some other task.
>
> The code would end up looking like this:
>
> if (0 < Timer1) Timer1--;
> if (0 < Timer2) Timer2--;
> and so on.
>
> Is there a more efficient way to handle those?
> Generally they will be living in SRAM, but I wouldn't rule out them
> living in registers for small apps.

I write same thing, but differently. Guessing the compiler generates  
the same code as you have written:

if( timer1 )
	timer1--;
if( timer2 )
	timer2--;

Have seen others write this way but I'm certain its slower unless you  
don't know in advance how many timers are needed:

for( i = 0 ; i < number_of_active_timers ; i++ )
	if( timer[i] )
		timer[i]--;

When I need a coarser but longer running timer:

if( timer_100ms && (--internal_timer_100ms == 0) ) {
	timer_100ms--;
	internal_timer_100ms = 100;
}

The "if" is evalated left to right and stops once the expression must  
be true or false. Perhaps clearer to write this way which should  
generate exactly the same code:

if( timer_100ms ) {
	if( --internal_timer_100ms == 0 ) {
		timer_100ms--;
		internal_timer_100ms = 100;
	}
}

When timer_100ms reaches 0 then internal_timer_100ms should be 100,  
initialized for the next use.

But more often I need to count off minutes or seconds, so I make an  
internal timer that counts down to seconds, and then place my  
software seconds timers in that group, Perhaps I need minutes as well  
so I put another internal timer counting 60 seconds before handling  
my minutes timers.

It looks like it takes a lot of time. Perhaps it does if one must  
count in ms resolution.

If one needs fine resolution consider running a hardware timer with a  
divisor and count interrupts on overflow. When your event occurs you  
can read the hardware timer and the software overflow interrupt  
counter to know the time very precisely.

--
David Kelly N4HHE, dkelly@HiWAAY.net
========================================================================
Whom computers would destroy, they must first drive mad.

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.