GENERAL: INCONSISTENT VALUES ON VOLATILE VARIABLES
Information in this article applies to:
My application accesses volatile variables that are modified by interrupt service routines. I get inconsistent values when I perform calculations based on this variables. I tried using the volatile keyword to disable optimizations, but it does not solve my problem. The only solution seems to be to disable interrupts. What is the reason for that behaviour?
The Compiler generates several CPU instructions to access multi-byte variables. When multi-byte variables are modified by interrupt routines, there is a potential that the interrupt occurs in the middle of the variable access.
volatile int value; // variable gets modified in an interrupt routine if (value == 0x100) i = 0;
is translated to:
CLR A CJNE A,value+01H,?C0002 // problem occurs when interrupt occurs between MOV A,value // this two lines. CJNE A,#01H,?C0002 CLR A MOV i,A MOV i+01H,A
As you can see the 8051 needs two instructions to access the variable value. If value gets modified by an interrupt between these two memory accesses the value may be inconsistent and may lead to wrong calculation results of your algorithms. You need disable the interrupt that modifies value to ensure that you get consistent values.
Last Reviewed: Tuesday, June 1, 2004
of your data.