Volatile variables tell the compiler that their value can change anytime, especially in interrupt routines. This prevents wrong assumptions and keeps the program working correctly.
0
0
Volatile variables in ISR context in Embedded C
Introduction
When a variable is changed inside an Interrupt Service Routine (ISR) and read in the main program.
When hardware registers or memory locations can change independently of the program flow.
When sharing data between different parts of a program that run at different times, like main code and interrupts.
Syntax
Embedded C
volatile type variable_name;The keyword volatile tells the compiler not to optimize or cache the variable.
Use it for variables that can change unexpectedly, like in ISRs or hardware registers.
Examples
A volatile integer variable named
flag that might change in an ISR.Embedded C
volatile int flag;A volatile character variable initialized to 0, used to signal data readiness.
Embedded C
volatile char data_ready = 0;Sample Program
This program shows a volatile variable data_ready that is changed inside a simulated ISR function. The main program checks this variable before and after the ISR call.
Embedded C
#include <stdio.h> #include <stdbool.h> volatile bool data_ready = false; // Simulated ISR that sets data_ready void ISR_simulator() { data_ready = true; } int main() { printf("Before ISR: data_ready = %d\n", data_ready); ISR_simulator(); // Simulate interrupt if (data_ready) { printf("After ISR: Data is ready!\n"); } else { printf("After ISR: Data not ready.\n"); } return 0; }
OutputSuccess
Important Notes
Without volatile, the compiler might optimize and assume the variable does not change, causing bugs.
Always declare variables shared between ISRs and main code as volatile.
Summary
Volatile tells the compiler a variable can change anytime, so it must always read it fresh.
Use volatile for variables changed in interrupts or hardware.
This helps avoid bugs caused by compiler optimizations.