Energia

## volatile keyword

volatile is a keyword known as a variable qualifier, it is usually used before the datatype of a variable, to modify the way in which the compiler and subsequent program treats the variable.

Declaring a variable volatile is a directive to the compiler. The compiler is software which translates your C/C++ code into the machine code, which are the real instructions for the LaunchPad.

Specifically, it directs the compiler to load the variable from RAM and not from a storage register, which is a temporary memory location where program variables are stored and manipulated. Under certain conditions, the value for a variable stored in registers can be inaccurate.

A variable should be declared volatile whenever its value can be changed by something beyond the control of the code section in which it appears, such as a concurrently executing thread. In Energia, the only place that this is likely to occur is in sections of code associated with interrupts, called an interrupt service routine.

#### Example

    volatile int state = HIGH;
    volatile int flag = HIGH;
    int count = 0;

    void setup()
    {
      Serial.begin(9600);

      pinMode(GREEN_LED, OUTPUT);
      digitalWrite(GREEN_LED, state);
      attachInterrupt(PUSH2, blink, FALLING); // Interrupt is fired whenever button is pressed
    }

    void loop()
    {
      digitalWrite(GREEN_LED, state); //LED starts ON
      if(flag) {
        count++;
        Serial.println(count);
        flag = LOW;
      }
    }

    void blink()
    {
      state = !state;
      flag = HIGH;
    }

#### See also

- AttachInterrupt

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Energia Reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Energia reference is based on Arduino reference. Code samples in the reference are released into the public domain.

©Energia | Edit Page | Page History | Printable View | All Recent Site Changes