Using Volatile keyword in embedded code

Volatile is probably the least documented keyword in most tutorials and books. This is the primary cause of most misuses and bugs related to it. If you already are programming microcontrollers, you probably know that volatile is always used on global variables that are accessed from interrupt service routines. Otherwise, code won’t work. After few requests, I decided to drop few lines about volatile keywords. This keyword is commonly used to tag memory type. We hear “volatile memory” and “non-volatile memory” when discussing computer hardware. As a quick reminder – “non-volatile memory” is a type of memory that stores its contents even when power is off. Such type of memory is EEPROM, Flash, and FRAM. This is easy from a hardware perspective. But what volatile keyword means in C or C++ code? This is an indicator (called qualifier) to the compiler that tells that this variable may be changed during program flow even if it doesn’t look like it be. This means that compiler must treat this value seriously and keep optimizer away from it.

Continue reading