Bird
Raised Fist0
Embedded Cprogramming~10 mins

Volatile variables in ISR context in Embedded C - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Volatile variables in ISR context
Main program starts
↓
Variable declared volatile
↓
Main program reads variable
↓
Interrupt occurs
↓
ISR modifies volatile variable
↓
Main program reads updated variable
↓
Program continues with updated value
The main program and ISR share a volatile variable; the volatile keyword ensures the main program always reads the latest value changed by the ISR.
Execution Sample
Embedded C
volatile int flag = 0;

void ISR() {
  flag = 1;
}

int main() {
  while(flag == 0) {}
  // proceed after ISR sets flag
  return 0;
}
This code shows a volatile flag set by an ISR and checked by the main program to proceed.
Execution Table
StepContextVariable 'flag' ValueActionEffect
1Main0Initialize flag to 0flag is 0, main waits
2Main0Check flag == 0Condition true, loop continues
3Interrupt0ISR runs, sets flag = 1flag updated to 1
4Main1Check flag == 0Condition false, exit loop
5Main1Proceed after ISRMain continues with updated flag
💡 flag becomes 1 in ISR, main loop condition flag==0 becomes false, loop exits
Variable Tracker
VariableStartAfter Step 3Final
flag011
Key Moments - 2 Insights
Why must 'flag' be declared volatile?
Because the ISR changes 'flag' asynchronously, volatile tells the compiler not to optimize away repeated reads, ensuring main sees the updated value (see execution_table step 3 and 4).
What happens if 'flag' is not volatile?
The compiler might cache 'flag' in a register in main, never seeing the ISR update, causing an infinite loop (execution_table step 2 and 4 show the importance).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'flag' right after the ISR runs?
A1
BUndefined
C0
D-1
💡 Hint
Check execution_table row 3 where ISR sets flag to 1
At which step does the main program exit the loop checking 'flag == 0'?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at execution_table step 4 where flag is 1 and condition becomes false
If 'flag' was not declared volatile, what likely happens in the main loop?
AMain sees updated flag and exits loop
BMain never sees update and loops forever
CISR never runs
DProgram crashes
💡 Hint
Refer to key_moments about compiler caching and optimization
Concept Snapshot
volatile keyword tells compiler variable can change anytime
Used for variables shared with ISR or hardware
Prevents compiler optimizations caching variable
Ensures main program reads latest value
Critical for synchronization between ISR and main code
Full Transcript
This example shows a volatile variable 'flag' shared between main program and an interrupt service routine (ISR). The main program waits in a loop checking if 'flag' is zero. When the ISR runs, it sets 'flag' to 1. Because 'flag' is declared volatile, the main program always reads the updated value and exits the loop. Without volatile, the compiler might optimize the loop to never see the change, causing an infinite wait. The execution table traces each step: initialization, main loop checks, ISR update, and main loop exit. The variable tracker shows 'flag' changes from 0 to 1 after ISR. Key moments clarify why volatile is needed and what happens if omitted. The quiz tests understanding of variable values and program flow. This teaches how volatile ensures correct communication between ISR and main code.

Practice

(1/5)
1. Why should a variable shared between an ISR (Interrupt Service Routine) and the main program be declared volatile?
easy
A. To allocate extra memory for the variable.
B. To tell the compiler the variable can change unexpectedly and prevent optimization errors.
C. To make the variable constant and unchangeable.
D. To speed up the program by caching the variable.

Solution

  1. Step 1: Understand the role of volatile

    The volatile keyword tells the compiler that the variable's value can change at any time, outside the normal program flow.
  2. Step 2: Apply to ISR context

    Since ISRs can change variables asynchronously, the compiler must always read the variable fresh, not use cached values.
  3. Final Answer:

    To tell the compiler the variable can change unexpectedly and prevent optimization errors. -> Option B
  4. Quick Check:

    Volatile prevents optimization errors in ISR variables = C [OK]
Hint: Volatile means 'may change anytime' to compiler [OK]
Common Mistakes:
  • Thinking volatile makes variable constant
  • Assuming volatile allocates more memory
  • Believing volatile speeds up code
2. Which of the following is the correct way to declare a variable flag that is modified inside an ISR?
easy
A. const int flag;
B. int flag;
C. volatile int flag;
D. static int flag;

Solution

  1. Step 1: Identify the need for volatile

    Since flag is changed inside an ISR, it must be declared volatile to prevent compiler optimizations.
  2. Step 2: Check declaration syntax

    The correct syntax is volatile int flag; which tells the compiler to always read the variable fresh.
  3. Final Answer:

    volatile int flag; -> Option C
  4. Quick Check:

    ISR-modified variable needs volatile keyword = A [OK]
Hint: Use volatile before type for ISR-shared variables [OK]
Common Mistakes:
  • Forgetting volatile keyword
  • Using const which prevents changes
  • Using static without volatile
3. Consider this code snippet:
volatile int flag = 0;

void ISR() {
    flag = 1;
}

int main() {
    while(flag == 0) {
        // wait for flag to change
    }
    return 0;
}
What will happen if flag was NOT declared volatile?
medium
A. The program will immediately exit the loop.
B. The program will crash at runtime.
C. The program will cause a compile-time error.
D. The program may loop forever because the compiler caches flag value.

Solution

  1. Step 1: Understand compiler optimization without volatile

    Without volatile, the compiler may assume flag does not change in the loop and cache its value.
  2. Step 2: Effect on the loop

    The loop condition flag == 0 may never be rechecked from memory, causing an infinite loop.
  3. Final Answer:

    The program may loop forever because the compiler caches flag value. -> Option D
  4. Quick Check:

    Missing volatile causes infinite loop due to caching = B [OK]
Hint: No volatile means compiler caches variable, causing infinite loops [OK]
Common Mistakes:
  • Thinking program crashes without volatile
  • Assuming compile error occurs
  • Believing loop exits immediately
4. Given this code, what is the main problem?
int flag = 0;

void ISR() {
    flag = 1;
}

int main() {
    while(flag == 0) {
        // wait
    }
    return 0;
}
medium
A. flag should be declared volatile to avoid optimization issues.
B. ISR function must return a value.
C. flag should be declared as const.
D. main() should not have a while loop.

Solution

  1. Step 1: Identify variable shared with ISR

    The variable flag is modified inside the ISR and read in main.
  2. Step 2: Check declaration for optimization safety

    Since flag is shared, it must be declared volatile to prevent the compiler from caching its value.
  3. Final Answer:

    flag should be declared volatile to avoid optimization issues. -> Option A
  4. Quick Check:

    Shared ISR variable needs volatile keyword = D [OK]
Hint: Always declare ISR-shared variables volatile [OK]
Common Mistakes:
  • Thinking ISR must return a value
  • Declaring shared variable const
  • Removing the loop instead of fixing volatile
5. You have a variable counter incremented inside an ISR and read in the main loop. Which of these is the best way to safely read counter in main without race conditions?
hard
A. Declare volatile int counter and disable interrupts briefly while reading it in main.
B. Declare volatile int counter and read it directly in main.
C. Declare int counter without volatile and read it directly.
D. Declare const int counter and read it in main.

Solution

  1. Step 1: Understand volatile role

    Declaring counter volatile ensures main reads fresh value, but does not prevent partial updates during read.
  2. Step 2: Prevent race conditions

    Disabling interrupts briefly while reading counter prevents ISR from changing it mid-read, avoiding inconsistent values.
  3. Final Answer:

    Declare volatile int counter and disable interrupts briefly while reading it in main. -> Option A
  4. Quick Check:

    Volatile + interrupt disable ensures safe multi-byte read = A [OK]
Hint: Disable interrupts briefly when reading multi-byte volatile variables [OK]
Common Mistakes:
  • Assuming volatile alone prevents race conditions
  • Not disabling interrupts during read
  • Using const which prevents changes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard