Keil Logo


Information in this article applies to:

  • C51 All Versions
  • C166 All Versions
  • C251 All Versions


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

Did this article provide the answer you needed?
Not Sure
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.