37/317
2 - How does a typical microcontroller work?
The following example shows:
What happens when the data are desynchronized.
Let us assume the main program wants to increment the word variable
reg (16-bit register in
page zero), that currently contains
42FF hex. The following code will be used:
; word variable reg contains 42FF hex
; increment word variable reg by 1
inc reg+1 ; add 1 to the low byte; low
byte is incremented. reg = 4200
hex
jrne endinc ; increment high byte if carry
endinc : ... ; here the program continues
; both bytes are incremented. reg = 4300 hex
If an interrupt service routines uses the value of reg, and if the interrupt request occurs for ex-
ample at the first line of the code above, the interrupt service routine will see that
reg is 4200
while it is actually either 42FF or 4300. This error may have serious consequences.
How to make the handling atomic.
To avoid thissituation, it is sufficient to mask out all the interrupts, by changingthe code as fol-
lows:
; increment word variable X by 1
sim ; prevent interrupts from
occurring
inc reg+1 ; add 1 to the low byte
jrne endinc ; increment high byte if carry
endinc rim ; allow interrupts to occur
... ; here the program continues
; both bytes are incremented. reg = 4300 hex, now the interrupt can be
performed
All interrupt requests that occur between the SIM and the RIM instructions are delayed for the
duration of that piece of code. If this would cause an excessive latency for one particular inter-
rupt that does not use that data, it is possible to mask out the specific interrupt source whose
service routine actually uses this value.
This example mentions the case where the data is written by the main program, and read by
theinterruptserviceroutine.Actually,thereversecaseisalsoasourceofproblem:ifthemain
program reads the data, and the interrupt service routine writes it, the main program may start