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

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

Re: [avr-gcc-list] Simple question


From: David Brown
Subject: Re: [avr-gcc-list] Simple question
Date: Mon, 31 Mar 2003 12:16:32 +0200

First the obvious RTFM point - "counter" must be declared as "volatile", or
nothing will work (read the avrlib manual, or look through the mailing list
archives, or read a book on C in embedded systems if you don't understand
the need for "volatile").

Now for the more interesting trick of getting the delay to work properly
despite overflows.  First, the simple version using 8-bit counters:

signed char counter = 0;
INTERRUPT(SIG_OUTPUT_COMPARE2) {
    counter++;
}

void pause (signed char delay) {
    signed char startCounter = counter;
    while ((counter - startCounter) < delay) ;
}

As long as your delays are less than 128 counts, the overflows disappear in
the subtraction.  However, this does not expand directly to 16-bit counters,
since they are subject to race conditions (i.e., the "pause" function reads
one byte of the counter, then the interrupt is called, then it reads the
second byte - which might be invalid).

A safe version for 16-bit would be:

s16 counter = 0;
INTERRUPT(SIG_OUTPUT_COMPARE2) {
    counter++;
}


void pause (s16 delay) {
    s16 startCounter, thisCounter;
    cli();
    startCounter = counter;
    sei();
    while (1) {
        cli();
        thisCounter = counter;
        sei();
        if ((thisCounter - startCounter) >= delay) break;
    };
}




> A very basic question... im just having one of those days where i cant see
the obvious
> answer.
>
> I want to do somthing like:
>
> u16 counter=0;
>
> void main(void)
> {
> u16 delay;
> while(1)
> {
> if (counter >= delay)
> {
> //do stuff
> delay = counter + 1000;
> }
> }
> }
>
> INTERRUPT(SIG_OUTPUT_COMPARE2)
> {
> counter++;
> }
>
> But obviously this wont handle counter overflows too well.  Whats the best
way to deal with
> the overflows, so that the delay still functions properly?  I only want to
have the counter
> increment in the INT as itll be running rather fast, and will chew too
much processor time
> if i start putting compares in there.
>
> Thanks for any tips.
> Mark.
>
> _______________________________________________
> avr-gcc-list mailing list
> address@hidden
> http://www.avr1.org/mailman/listinfo/avr-gcc-list




reply via email to

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