Microchip Technology SW006022-1N Data Sheet

Page of 338
MPLAB
®
 XC16 C Compiler User’s Guide
DS52071B-page 182
 2012 Microchip Technology Inc.
11.8
ISR CONSIDERATIONS
The following sections describe how to ensure your interrupt code works as expected.
11.8.1
Sharing Memory with Mainline Code
Exercise caution when modifying the same variable within a main or low-priority ISR 
and a high-priority ISR. Higher priority interrupts, when enabled, can interrupt a multiple 
instruction sequence and yield unexpected results when a low-priority function has cre-
ated a multiple instruction Read-Modify-Write sequence accessing that same variable. 
Therefore, embedded systems must implement an “atomic” operation to ensure that 
the intervening high-priority ISR will not write to the variable from which the low-priority 
ISR has just read, but not yet completed its write.
An atomic operation is one that cannot be broken down into its constituent parts – it 
cannot be interrupted. Depending on which architecture is involved, not all C expres-
sions translate into an atomic operation. On dsPIC DSC devices, these expressions 
mainly fall into the following categories: 32-bit expressions, floating point arithmetic, 
division, and operations on multi-bit bitfields. Other factors will determine whether or 
not an atomic operation will be generated, such as memory model settings, 
optimization level and resource availability.
Consider the general expression:
  foo = bar op baz;
The operator (op) may or may not be atomic, based on the architecture of the device. 
In any event, the compiler may not be able to generate the atomic operation in all 
instances, depending on factors that may include the following:
• availability of an appropriate atomic machine instruction
• resource availability - special registers or other constraints
• optimization level, and other options that affect data/code placement
Without knowledge of the architecture, it is reasonable to assume that the general 
expression requires two reads, one for each operand and one write to store the result. 
Several difficulties may arise in the presence of interrupt sequences, depending on the 
particular application.