aboutsummaryrefslogtreecommitdiffstats
path: root/docs/source/lang/volatile.rst
blob: a0ef67112cb084eb8468e40d25d005c1d8bad532 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
.. _lang-volatile:

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 Atmega chip
in the Arduino.



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 the
Arduino, the only place that this is likely to occur is in sections
of code associated with interrupts, called an interrupt service
routine.



Example
-------

::

    // toggles LED when interrupt pin changes state

    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;
    }



See also
--------


-  `AttachInterrupt <http://arduino.cc/en/Reference/AttachInterrupt>`_




.. include:: cc-attribution.txt