16 bit interrupt shared variable access on 8 bit MCU

Thread Starter

aamirali

Joined Feb 2, 2012
412
I am working on Atmega1280v. It is 8 bit MCU.

I have a 16 bit variable shared across interrupt. I have defined it as volatile

I was reading the documentation & found that if I have to access that variable in main then I have to disable interrupts first & then access.


1. I thought declaring a shared variable as volatile is enough?
2. Does that apply to all MCU & compiler.
3. If I access 16 bit shared variable in main across 8 bit machine then I should disable interrupt first & reenable them after accessing them?

4. If it is common, then what we should in 32 bit machine like ARM?
 

THE_RB

Joined Feb 11, 2008
5,438
No declaring it as volatile is not enough!

An 8bit processor needs to read/write the 16bit variable as two separate 8bit operations, at different points in time. So you need to disable interrupts, OR make sure the interrupt does not occur between the two operations.

Generally I hate turning interrupts off, and instead just access the 16bit variable at a time when I know the interrupt will not occur. That is easy with timer interrupts, you just check the timer low byte to make sure it won't roll over during the next 10 instructions, and if so, just read or write the 16bit variable;
Rich (BB code):
while(TMR0 > 245) continue;  // wait here, for timer roll to be safe!
foo = blah;   // read the 16bit variable now it is safe
 
Top