Skip to content

Update volatile.adoc: Add explanation to examples #712

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 23, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions Language/Variables/Variable Scope & Qualifiers/volatile.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -55,34 +55,48 @@ There are several ways to do this:
=== Example Code
// Describe what the example code is all about and add relevant code ►►►►► THIS SECTION IS MANDATORY ◄◄◄◄◄

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.

[source,arduino]
----
// toggles LED when interrupt pin changes state
// Flashes the LED for 1 s if the input has changed
// in the previous second.

int pin = 13;
volatile byte state = LOW;

void setup() {
pinMode(pin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(2), blink, CHANGE);
pinMode(LED_BUILTIN, OUTPUT);
attachInterrupt(digitalPinToInterrupt(2), toggle, CHANGE);
}

void loop() {
digitalWrite(pin, state);
bool changedInTheMeantime = false;

byte originalState = state;
delay(1000);
byte newState = state;

if (newState != originalState) {
// toggle() has been called during delay(1000)
changedInTheMeantime = true;
}

digitalWrite(LED_BUILTIN, changedInTheMeantime ? HIGH : LOW);
}

void blink() {
void toggle() {
state = !state;
}
----

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.

[source,arduino]
----
#include <util/atomic.h> // this library includes the ATOMIC_BLOCK macro.
volatile int input_from_interrupt;

// Somewhere in the code, e.g. inside loop()
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
// code with interrupts blocked (consecutive atomic operations will not get interrupted)
int result = input_from_interrupt;
Expand Down