Skip to content

When to use volatile

joshua255 edited this page Aug 4, 2019 · 5 revisions

here's my best attempt to explain what declaring a variable with the volatile qualifier means:

volatile is a so-called "variable qualifier," which basically means that it tells the compiler how it should treat this variable.

volatile is used primarily for variables that are involved in "interrupt service routines" (ISR). An ISR is a function that gets called when an event (attached to the function) happens (like a PIN change interrupt or a timer).

volatile is used to designate which source of memory the variable should be stored in for use. There are two types of memory that are used (as I understand it), those being RAM (Random Access Memory) and memory from a "storage register." Using volatile before a variable and its data type will designate it to be stored in RAM, while not typing it before will result in the variable being stored in the storage register. If a variable is stored in a storage register and is called by an interrupt service routine, it may not read the variable correctly. When volatile is used, the variable can be read correctly because it has been stored in RAM.

TL;DR volatile should be used to declare a variable if it will be used in an interrupt service routine or between multiple tasks.

Arduino Reference for volatile: https://www.arduino.cc/reference/en/language/variables/variable-scope--qualifiers/volatile/

Clone this wiki locally