ARM Technical Support Knowledge Articles

INCONSISTENT VALUES ON VOLATILE VARIABLES

Applies to: General Topics

Answer


Information in this article applies to:


QUESTION

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?

ANSWER

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.

Example:

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.

SEE ALSO

Article last edited on: 2004-06-01 08:26:07

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential