How Do I Share Data Between Interrupt and Main-line Code?

Variables accessed from both interrupt and main-line code can easily become corrupted or mis-read by the program. The volatile qualifier (see Volatile Type Qualifier) tells the compiler to avoid performing optimizations on such variables. This will fix some of the issues associated with this problem.

The other issue relates to whether the compiler/device can access the data atomically. With 8-bit PIC devices, this is rarely the case. An atomic access is one where the entire variable is accessed in only one instruction. Such access is uninterruptible. You can determine if a variable is being accessed atomically by looking at the assembly code the compiler produces in the assembly list file (see Assembly List Files). If the variable is accessed in one instruction, it is atomic. Since the way variables are accessed can vary from statement to statement it is usually best to avoid these issues entirely by disabling interrupts prior to the variable being accessed in main-line code, then re-enable the interrupts afterwards (see Enabling Interrupts).