5.1.1 The global interrupt enable flag

It is sometimes important to disable interrupt. We'll explain this later. In order not to listen for any request from any device, most processors have a flag that enables interrupt for all devices.

On the ATMega128 (as well as all AVR variants), this is a boolean flag called the I flag. It is a bit in the status register (SREG).

To clear the I flag, you can use the macro _CLI(). This disables all interrupts. To set the I flag (to enable global interrupt), you use the macro _SEI(). These two macros typically translate to assembly code.

It is not always the case that you want to disable or enable interrupts. For example, sometimes you need to disable interrupts, then restore the system to what it used to be. In other words, if interrupt was disabled originally, you don't want to enable it.

To accomplish this, you can use a local variable to remember whether interrupt was enabled to begin with. This is done by the following code template:

{
  unsigned char oldSREG = SREG;

  _CLI(); // disable interrupt
  ...  // do whatever
  if (oldSREG & (1 << SREG_I)) _SEI();
}

Copyright © 2006-02-15 by Tak Auyeung