Makhlouf Gharbi Makhlouf Gharbi - 17 days ago 6
C Question

is volatile keyword really needed when variable changed in interrupt routine

I'm using nrf52 microcontroller (CORTEX 34F) processor. I have a variable check on the main loop which is modified both on the main loop and timer interrupt routine.


  1. main loop check if variable is true :


    • execute condition code

    • set variable to false


  2. timer interrupt routine set variable to true every 10 ms



without
volatile
keyword, the code seems not working, but when I set the variable to
volatile
it seems to work but I'm not convinced because :


  1. first I think cortex M4f doesn't contain data cache memory

  2. second : this case is handeld by the compiler (arm keil)



any answer please ;

if true execute body code
2. List item

Answer

You have a misunderstanding regarding the volatile keyword; specifically it is not related to caching - cache consistency is handled entirely by hardware and volatile has no effect on that.

The purpose of volatile is to prevent the compiler from generating code that assumes the value cannot have changed. The C language does not provide support to threads of execution, and the code is generated as if there were a single thread; if the compiler can observe within a single thread of execution that a variable has not been explicitly modified, it may remove the explicit read and use an already known value (stored in a register for example).

The code in your main() function is "unaware" that the interrupt may occur between reads, and can therefore optimise out the read. The volatile keyword instructs the compiler to generate code to explicitly read the memory. It does not matter one way or the other whether that read results in a cache-hit or miss or if there is no cache at all - that is a hardware issue.

You might benefit from reading Introduction to the volatile keyword on Embedded.com. It covers exactly this issue.