While declaring variables shared between the (main) loop and and ISR as 'volatile' is necessary, it is not sufficient in the general case: care must also be taken to avoid race conditions, ie. uncontrolled access to such shared variables by the two threads of control, loop() and ISR, resulting in data and behaviour inconsistencies.
To make an overly simple example:
volatile uint16_t ctr = 0xFFFF;
ISR(SOME_vector) {
ctr--;
}
void loop() {
// do stuff
if (ctr == 0xFFF) {
// handle case
}
// do more stuff
}
is calling for trouble, as the 16-bit value can not be handled in atomic fashion on an 8-bit CPU as use on the Arduino. So it could happen that the compare operation (ctr == 0xFF) in loop() get's interrupted by the ISR, doing the decrement (ctr--), then loop() continues its comparison...
loop() could temporarily disable the interrupts with cli() and sei():
#include <avr/interrupt.h>
void loop() {
// do stuff
cli(); // disable all interrupts
if (ctr == 0xFFF) {
// handle case
}
sei(); // enable interrupts
// do more stuff
}
but this is dangerous as well, as sei() will forcibly enable the interrupts, but they might have been disabled in another location in the code (consider a somewhat more complex program than the above...), hence just enabling them might result in unexpected behavior.
What you find in the Arduino libs (eg. in digitalWrite()) is something along these lines to overcome this issue:
#include <avr/interrupt.h>
#uint8_t _SREG;
void loop() {
// do stuff
_SREG = SREG; // save the current (interrupt) state
cli();
if (ctr == 0xFFF) {
// handle case
}
SREG = _SREG; // restore (interrupt) state
// do more stuff
}
Better. However, when the ISR is triggered right after the saving the state (_SREG = SREG) and disabling interrupts, we have the inconsistency issue again.
So what the AVR library provides and recommends, is using a macro to define atomic blocks like so:
#include <avr/atomic.h>
volatile uint16_t ctr = 0xFFFF;
ISR(SOME_vector) {
ctr--;
}
void loop() {
// do stuff
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
if (ctr == 0xFFF) {
// handle case
}
}
// do more stuff
}
which will handle the issue properly, ie. disabling interrupts as well as restoring the previous state. Of course, if handling the case in loop() takes too long with interrupts disabled, you'd make local copies of the shared variables in the atomic section, leave the atomic section, and handle the case outside.
See http://www.nongnu.org/avr-libc/user-manual/index.html for more info and more possibilities.