Volatile

From Microduino Wiki
Revision as of 02:13, 22 August 2016 by Fengfeng (talk) (Created page with "Volatile variables(volatile)keyword <br> The keyword volatile is variable modifier, generally used in front of a variable to tell the compiler and the next program how to...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Volatile variables(volatile)keyword

The keyword volatile is variable modifier, generally used in front of a variable to tell the compiler and the next program how to treat with this variable.

The declaration of a volatile variable is a command of the compiler, which is a software transform your C/C++ codes into machine codes. Machine code in the real command that the chip Atmega on arduino can identify.

In particular, it indicates the compiler to read variables from RAM rather than the memory register, which is a temporary place where the program stores and operates variables. In some cases, the variables stored in the memory register may be inaccurate.

If the code segment where a variable is is likely to result in the change of the variable, you should declare this variable as volatile, such as parallel multi-thread etc. In arduino, the only possible place for this phenomenon is the code segment related to interrupt, which becomes the interrupt service program.

  • Example
//When the state of the interrupt pin changes, switch the LED on or off. 
 
int pin = 13;
volatile int state = LOW;
 
void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
}
 
void loop()
{
  digitalWrite(pin, state);
}
 
void blink()
{
  state = !state;
}

[Return to Arduino Syntax Manual]