Menu
CoddyTech

Sharing With volatile

Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 14 of 18.

An ISR should do one quick thing, so it usually sets a variable for the rest of the sketch to read. A variable that both use must be declared volatile:

volatile bool started = false;

void onPress() {
  started = true;
}

To save time, the compiler (the program that turns your C++ into the chip's instructions) may keep a copy of a variable inside the processor instead of reading memory. It does not know an interrupt can change the variable, so the sketch may use the old copy forever. volatile makes it read the variable fresh every time.

This sketch waits in setup() with a while loop: while (condition) { } repeats its braces as long as the condition is true, here !started. As in the Inputs section, ! means not: the loop repeats while started is false. Without volatile, it can wait forever, even after the press.

challenge icon

Challenge

Easy

This sketch should wait until the button is pressed, then blink the LED. Right now it waits forever. Fix it:

  • in onPress(), set started to true
  • declare started as volatile

Press Run, press the button, then Check. Try it once without volatile to see the board stay stuck.

Try it yourself

const int ledPin = 13;
const int buttonPin = 2;

bool started = false;   // set by the interrupt, read by the sketch

unsigned long previousMillis = 0;
int ledState = LOW;

void onPress() {
  // set started to true here
}

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPin), onPress, FALLING);

  // wait here until the button has been pressed
  while (!started) {
  }
}

void loop() {
  // blink every 250 ms
  unsigned long now = millis();
  if (now - previousMillis >= 250) {
    previousMillis = now;
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }
    digitalWrite(ledPin, ledState);
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Timing Without Delay

Practice on your own: Arduino playground