3.4.4 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 9.9.2 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 issues relates to whether the compiler/device can access the data atomically. With 32-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 assembler list file (see the MPLAB® XC32 Assembler, Linker and Utilities User’s Guide, DS50002186, for more information). 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 17.8 Enabling/Disabling Interrupts for more information. When writing to Special Function Registers (SFRs), use the SET/CLR/INV registers as described in 7.4 ID Locations.