avr-gcc-list
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [avr-gcc-list] BUG? Comparing of words error.


From: Dave Hylands
Subject: Re: [avr-gcc-list] BUG? Comparing of words error.
Date: Wed, 18 Jan 2006 11:21:23 -0800

Hi Flemming,

> I noticed the problem using this code:
> ------------
>
> unsigned short RotCount;
>
> SIGNAL(SIG_INTERRUPT0){
>         RotCount++;
> }
>
> void test(void){
>         while (1){
>                 RotCount = 0;
>                 while (RotCount < 1000) {}
>                 RotCount = 0;
>                 while (RotCount < 2000) {}
>         }
> }
> ------------
>
> My problem is that the two inner whiles sometimes exists prematurly.
> The one counting to 1000 sometimes exists at 768.
> The one counting to 2000 sometimes exists at 1792.
> Sometimes, means once every 5 to 20 loops.

Firstly, RotCount needs to be declared as volatile.

Secondly, because RotCount is a 16 bit value, you need to fetch all 16
bits in an atomic fashion.

So I'd write a function like:

#include <avr/interrupt.h>

uint16_t GetRotCount( void )
{
    uint16_t ret;
    uint8_t sreg = SREG;
    cli();
    ret = RotCount;
    SREG = sreg;
    return ret;
}

and then use:

while (GetRotCount() < 1000 ) {}

Similarly, you should disable interrupts while setting RotCount to
zero (to ensure that both 8 bit bytes get set properly and that the
interrupt doesn't increment incorrectly).

--
Dave Hylands
Vancouver, BC, Canada
http://www.DaveHylands.com/




reply via email to

[Prev in Thread] Current Thread [Next in Thread]