Skip to content

Commit 34c5c08

Browse files
committed
volatile.adoc: Add suggestions by @cmaglie
1 parent a239a51 commit 34c5c08

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

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

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -55,37 +55,36 @@ 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 would be loaded into a register when entering the function and would not be updated anymore until the function ends.
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.
5959

6060
[source,arduino]
6161
----
6262
// Flashes the LED for 1 s if the input has changed
6363
// in the previous second.
6464
65-
volatile byte state = LOW;
65+
volatile byte changed = 0;
6666
6767
void setup() {
6868
pinMode(LED_BUILTIN, OUTPUT);
6969
attachInterrupt(digitalPinToInterrupt(2), toggle, CHANGE);
7070
}
7171
7272
void loop() {
73-
bool changedInTheMeantime = false;
73+
if (changed == 1) {
74+
// toggle() has been called from interrupts!
7475
75-
byte originalState = state;
76-
delay(1000);
77-
byte newState = state;
76+
// Reset changed to 0
77+
changed = 0;
7878
79-
if (newState != originalState) {
80-
// toggle() has been called during delay(1000)
81-
changedInTheMeantime = true;
79+
// Blink LED for 200 ms
80+
digitalWrite(LED_BUILTIN, HIGH);
81+
delay(200);
82+
digitalWrite(LED_BUILTIN, LOW);
8283
}
83-
84-
digitalWrite(LED_BUILTIN, changedInTheMeantime ? HIGH : LOW);
8584
}
8685
8786
void toggle() {
88-
state = !state;
87+
changed = 1;
8988
}
9089
----
9190

0 commit comments

Comments
 (0)