Page 184 - Embedded Microprocessor Systems Real World Design
P. 184
The result could be a path through the decision tree that appears impossible when
you try to debug it. In cases where an ISR can change a memory location, never
assume it will be the same on two separate reads outside the ISR. If the polling loop
(or another ISR, if nested interrupts are used) needs to use the value twice, read
it once, then store it in a register or a temporary memory location for subsequent
use:
Read location X
Store it in location Y
If Y = 0, do something
Read location Y again
If Y = 1, do something different
Read location Y again
If Y = 2, do a third thing
and so on
Now changes to Xdo not affect what the loop does. This scenario may seem
unlikely, but remember that some simple microcontrollers have no compare-
with-immediate-data instruction. On these processors, the only way to test for a
specific value is to exclusive-OR the variable (X in this case) with the desired value
and check for a zero result. Then X must be read again for the next test.
HigWLow Pairs
Sometimes you have a counter that is reset outside the ISR and incremented inside
the ISR (this violates the rule about having the variable written by both ISR and
non-ISR code, but sometimes it must happen in this way). Consider the following
code, which might be used to keep track of the position of a rotating wheel. This
wheel has a sensor in one spot, which indicates the home position. Wheel position
is calculated with reference to home.
Won-ISR code:
When home sensor detected,
Reset high byte of position count
Reset low byte of position count
ISR code:
Increment low byte of count
If low byte rolled over from FT to 00, increment high byte of
count.
This is typical of a l6bit counter implemented on an 8-bit processor, although
the same principle applies to a 32-bit counter on a 16-bit processor. Suppose the
Interrupts in Embedded Systems 165