When the volatile attribute is used on a global variable, the compiler
will not
optimize away accesses to that variable.
If you are using a global variable to communicate between an ISR and a
"main" routine,
you probably need to use the volatile keyword in the variable
declaration in order to
ensure that the compiler doesn't get fooled into optimizing away
important parts of
your code.
A more subtle issue is ensuring atomic accesses to multi-byte variables
(or data
structures). A common example is an ISR that does serial receive into a
char
buffer and updates a pointer into that buffer). The problem is that if
the main
routine does not protect it's accesses to to the shared global
variables with
cli() and sei() (and they're not already atomic [single-cycle]
instructions)
it is possible for the main routine to read or corrupt the values of
these
variables.
Chip
If the main
function has interrupts turned off (either globally, or the specific ISR
interrupt enable), then it can happily use a non-volatile variable
shared with the ISR.
I think may cause trouble. When the compiler optimizes your code, it
might make assumptions about the non-volatile variable that are not true?
The main routine may have loaded a register with your variable a while
before disabling interrupts. Now your main routine may have an old value
for that variable.
Keith
On Thu, 15 Sep 2005, David Brown wrote:
----- Original Message -----
From: "Lars Noschinski" <[EMAIL PROTECTED]>
* Lars Noschinski <[EMAIL PROTECTED]> [2005-09-06 21:59]:
You must declare the global variable as volatile (or as register), if
you want to modify in an ISR.
Wrong - that's neither necessary nor complete (there is just as much of an
issue reading variables as writing them).
Speaking of this, if I have an variable which is initialized during
startup and only accessed /in/ an ISR, am I on the safe side, if don't
declare it as volatile, right?
Right.
The point is that you need to use "volatile" if the data may change or be
used without the compiler knowing it. If a function uses a variable, and
may be interrupted by an ISR which also uses that same variable, then the
variable should be volatile - but otherwise, there is no need for it to be
volatile. So a variable that is only used in an ISR is safe. If the main
function has interrupts turned off (either globally, or the specific ISR
interrupt enable), then it can happily use a non-volatile variable shared
with the ISR.
mvh.,
David.
_______________________________________________
AVR-GCC-list mailing list
[email protected]
http://lists.nongnu.org/mailman/listinfo/avr-gcc-list
_______________________________________________
AVR-GCC-list mailing list
[email protected]
http://lists.nongnu.org/mailman/listinfo/avr-gcc-list
|
_______________________________________________
AVR-GCC-list mailing list
[email protected]
http://lists.nongnu.org/mailman/listinfo/avr-gcc-list