Skip to content

Commit de455ae

Browse files
authored
Merge pull request #712 from Granjow/patch-1
Update volatile.adoc: Add explanation to examples
2 parents 2af27e5 + 34c5c08 commit de455ae

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

Language/Variables/Variable Scope & Qualifiers/volatile.adoc

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,34 +55,47 @@ There are several ways to do this:
5555
=== Example Code
5656
// Describe what the example code is all about and add relevant code ►►►►► THIS SECTION IS MANDATORY ◄◄◄◄◄
5757

58+
The `volatile` modifier ensures that changes to the `state` variable are immediately visible in `loop()`. Without the `volatile` modifier, the `state` variable may be loaded into a register when entering the function and would not be updated anymore until the function ends.
5859

5960
[source,arduino]
6061
----
61-
// toggles LED when interrupt pin changes state
62+
// Flashes the LED for 1 s if the input has changed
63+
// in the previous second.
6264
63-
int pin = 13;
64-
volatile byte state = LOW;
65+
volatile byte changed = 0;
6566
6667
void setup() {
67-
pinMode(pin, OUTPUT);
68-
attachInterrupt(digitalPinToInterrupt(2), blink, CHANGE);
68+
pinMode(LED_BUILTIN, OUTPUT);
69+
attachInterrupt(digitalPinToInterrupt(2), toggle, CHANGE);
6970
}
7071
7172
void loop() {
72-
digitalWrite(pin, state);
73+
if (changed == 1) {
74+
// toggle() has been called from interrupts!
75+
76+
// Reset changed to 0
77+
changed = 0;
78+
79+
// Blink LED for 200 ms
80+
digitalWrite(LED_BUILTIN, HIGH);
81+
delay(200);
82+
digitalWrite(LED_BUILTIN, LOW);
83+
}
7384
}
7485
75-
void blink() {
76-
state = !state;
86+
void toggle() {
87+
changed = 1;
7788
}
7889
----
7990

91+
To access a variable with size greater than the microcontroller’s 8-bit data bus, use the `ATOMIC_BLOCK` macro. The macro ensures that the variable is read in an atomic operation, i.e. its contents cannot be altered while it is being read.
8092

8193
[source,arduino]
8294
----
8395
#include <util/atomic.h> // this library includes the ATOMIC_BLOCK macro.
8496
volatile int input_from_interrupt;
8597
98+
// Somewhere in the code, e.g. inside loop()
8699
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
87100
// code with interrupts blocked (consecutive atomic operations will not get interrupted)
88101
int result = input_from_interrupt;

0 commit comments

Comments
 (0)