You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Language/Variables/Variable Scope & Qualifiers/volatile.adoc
+20-10Lines changed: 20 additions & 10 deletions
Original file line number
Diff line number
Diff line change
@@ -55,42 +55,52 @@ There are several ways to do this:
55
55
=== Example Code
56
56
// Describe what the example code is all about and add relevant code ►►►►► THIS SECTION IS MANDATORY ◄◄◄◄◄
57
57
58
-
Use a `volatile byte` to store the pin state in a single byte:
58
+
The `volatile` modifier ensures that changes to the `state` variable are immediately visible in `loop()`. Without the `volatile` modifier, the `state` variable would be loaded into a register when entering the function and would not be updated anymore until the function ends.
59
59
60
60
[source,arduino]
61
61
----
62
-
// toggles LED when interrupt pin changes state
62
+
// Flashes the LED for 1 s if the input has changed
digitalWrite(LED_BUILTIN, changedInTheMeantime ? HIGH : LOW);
74
85
}
75
86
76
-
void blink() {
87
+
void toggle() {
77
88
state = !state;
78
89
}
79
90
----
80
91
81
-
Use an atomic block for atomic access to a 16-bit `int`:
92
+
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.
82
93
83
94
[source,arduino]
84
95
----
85
96
#include <util/atomic.h> // this library includes the ATOMIC_BLOCK macro.
86
97
volatile int input_from_interrupt;
87
98
88
-
void loop() {
99
+
// Somewhere in the code, e.g. inside loop()
89
100
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
90
101
// code with interrupts blocked (consecutive atomic operations will not get interrupted)
0 commit comments