Skip to content

Commit a239a51

Browse files
committed
Update volatile.adoc: Add new code sample
1 parent 0650027 commit a239a51

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

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

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,42 +55,52 @@ 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-
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.
5959

6060
[source,arduino]
6161
----
62-
// toggles LED when interrupt pin changes state
62+
// Flashes the LED for 1 s if the input has changed
63+
// in the previous second.
6364
64-
int pin = 13;
6565
volatile byte state = LOW;
6666
6767
void setup() {
68-
pinMode(pin, OUTPUT);
69-
attachInterrupt(digitalPinToInterrupt(2), blink, CHANGE);
68+
pinMode(LED_BUILTIN, OUTPUT);
69+
attachInterrupt(digitalPinToInterrupt(2), toggle, CHANGE);
7070
}
7171
7272
void loop() {
73-
digitalWrite(pin, state);
73+
bool changedInTheMeantime = false;
74+
75+
byte originalState = state;
76+
delay(1000);
77+
byte newState = state;
78+
79+
if (newState != originalState) {
80+
// toggle() has been called during delay(1000)
81+
changedInTheMeantime = true;
82+
}
83+
84+
digitalWrite(LED_BUILTIN, changedInTheMeantime ? HIGH : LOW);
7485
}
7586
76-
void blink() {
87+
void toggle() {
7788
state = !state;
7889
}
7990
----
8091

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.
8293

8394
[source,arduino]
8495
----
8596
#include <util/atomic.h> // this library includes the ATOMIC_BLOCK macro.
8697
volatile int input_from_interrupt;
8798
88-
void loop() {
99+
// Somewhere in the code, e.g. inside loop()
89100
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
90101
// code with interrupts blocked (consecutive atomic operations will not get interrupted)
91102
int result = input_from_interrupt;
92103
}
93-
}
94104
----
95105

96106

0 commit comments

Comments
 (0)