Volatile and ISR

Status
Not open for further replies.

PAAUX4

Well-known member
I asked a question on Stack Overflow that mentioned using accessing volatile variables in an ISR and most said/implied that volatile was not required, which goes against everything I know. Admittedly I've only been looking at this over the last few days, but I'm still confused. I assume my question is poorly worded and has been misunderstood.

This is the question: https://stackoverflow.com/questions/57499440/using-methods-of-volatile-standard-template-objects

Can anyone explain what's going on? I've read here: https://www.pjrc.com/teensy/interrupts.html

If anybody wants to answer my actual question, that would also be very much appreciated.
 
I believe the keyword "volatile" provides some insurance. Against what? The compiler making assumptions that differ from my own.

What is an ISR? Some code that might happen - but your'e never truly sure when. Compilers often have a habit of using local registers to store things rather than take the longer road to RAM memory. If you use the insurance, then you force the longer road to memory regardless. What does it cost? Not a lot.
 
I asked a question on Stack Overflow that mentioned using accessing volatile variables in an ISR and most said/implied that volatile was not required, which goes against everything I know. Admittedly I've only been looking at this over the last few days, but I'm still confused. I assume my question is poorly worded and has been misunderstood.

This is the question: https://stackoverflow.com/questions/57499440/using-methods-of-volatile-standard-template-objects

Can anyone explain what's going on? I've read here: https://www.pjrc.com/teensy/interrupts.html

If anybody wants to answer my actual question, that would also be very much appreciated.

It may be in the case of older processors like the AVR processors without many registers, that you can get away without using volatile. But in general, I agree with TelephoneBill, that you want to use volatile for any variable that is accessed in an interrupt handle (particularly one that is set in the ISR).

However if you are doing any thing more compilicated than setting a scalar variable or looking at it (where the variable is small enough that the machine can read it with one instruction and the variable is properly aligned), you are just asking for trouble. You don't want to call functions (even inlined functions). You just want to set a status variable saying the interrupt was received or similar, and then in your loop code, check that variable, and do the more complicated stuff there (like bitset). In particular, don't use anything that can call malloc or new, don't do I/O unless you really know what you are doing, etc.
 
Status
Not open for further replies.
Back
Top