16 bit interrupt shared variable access on 8 bit MCU

Discussion in 'Embedded Systems and Microcontrollers' started by aamirali, Jul 23, 2014.

  1. aamirali

    Thread Starter Member

    Feb 2, 2012
    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?
  2. THE_RB

    AAC Fanatic!

    Feb 11, 2008
    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;
    Code ( (Unknown Language)):
    2. while(TMR0 > 245) continue;  // wait here, for timer roll to be safe!
    3. foo = blah;   // read the 16bit variable now it is safe