11
\$\begingroup\$

Given a microcontroller that is running the following code:

volatile bool has_flag = false;

void interrupt(void) //called when an interrupt is received
{
    clear_interrupt_flag(); //clear interrupt flag
    has_flag = true; //signal that we have an interrupt to process
}

int main()
{
    while(1)
    {
        if(has_flag) //if we had an interrupt
        {
            has_flag = false; //clear the interrupt flag
            process(); //process the interrupt
        }
        else
            sleep(); //place the micro to sleep
    }
}

Suppose the if(has_flag) condition evaluates to false and we are about to execute the sleep instruction. Right before we execute the sleep instruction, we receive an interrupt. After we leave the interrupt, we execute the sleep instruction.

This execution sequence is not desirable because:

  • The microcontroller went to sleep instead of waking up and calling process().
  • The microcontroller may never wake up if no interrupt are thereafter received.
  • The call to process() is postponed until the next interrupt.

How can the code be written to prevent this race condition from occurring?

Edit

Some microcontrollers, such at the ATMega, have a Sleep enable bit which prevents this condition from occurring (thank you Kvegaoro for pointing this out). JRoberts offers an example implementation that exemplifies this behavior.

Other micros, such at PIC18s, do not have this bit, and the problem still occurs. However, these micros are designed such that interrupts can still wake up the core irrespective of whether the global interrupt enable bit is set (thank you supercat for pointing this out). For such architectures, the solution is to disable global interrupts right before going to sleep. If an interrupt fires right before executing the sleep instruction, the interrupt handler will not be executed, the core will wake up, and once global interrupts are re-enabled, the interrupt handler will be executed. In pseudo-code, the implementation would look like this:

int main()
{
    while(1)
    {
        //clear global interrupt enable bit.
        //if the flag tested below is not set, then we enter
        //sleep with the global interrupt bit cleared, which is
        //the intended behavior.
        disable_global_interrupts();

        if(has_flag) //if we had an interrupt
        {
            has_flag = false; //clear the interrupt flag
            enable_global_interrupts();  //set global interrupt enable bit.

            process(); //process the interrupt
        }
        else
            sleep(); //place the micro to sleep
    }
}
\$\endgroup\$
  • \$\begingroup\$ Is this practical or theoretical question? \$\endgroup\$ – AndrejaKo Mar 20 '13 at 21:06
  • \$\begingroup\$ in theory you use a timer that wakes you up once every (enter acceptable value)ms and then goes back to sleep if nothing needs doing. \$\endgroup\$ – Grady Player Mar 20 '13 at 21:10
  • 1
    \$\begingroup\$ I would do interrupt_flag as an int, and increment it every time there is interrupt. Then change the if(has_flag) to while (interrupts_count) and then sleep. Nonetheless, the interrupt could occur after you've exited the while loop. If this is a problem, then do the processing in the interrupt itself? \$\endgroup\$ – angelatlarge Mar 20 '13 at 21:30
  • 1
    \$\begingroup\$ well it depends on what micro you are running.. If it was an ATmega328 you could possibly disable the sleep mode on the interrupt, so if the race condition you describe happens then the sleep function would be overridden, loop back again and you would processes the interrupt with a small latency. But also using a timer to wake up at a interval equal or less to your maximum latency would be a great solution too \$\endgroup\$ – Kvegaoro Mar 20 '13 at 21:33
  • 1
    \$\begingroup\$ @TRISAbits: On the PIC 18x, the approach I've described in my answer works just fine (it's my normal design when using that part). \$\endgroup\$ – supercat Mar 20 '13 at 22:46
9
\$\begingroup\$

There is usually some kind of hardware support for this case. E.g., the AVRs' sei instruction to enable interrupts defers enabling until the following instruction is complete. With it one can do:

forever,
   interrupts off;
   if has_flag,
      interrupts on;
      process interrupt;
   else,
      interrupts-on-and-sleep;    # won't be interrupted
   end
end

The interrupt that would have been missed in the example would in this case be held off until the processor completes its sleep sequence.

\$\endgroup\$
  • \$\begingroup\$ Great answer! The algorithm you provide actually works really well on an AVR. Thanks for the suggestion. \$\endgroup\$ – TRISAbits Mar 21 '13 at 15:48
3
\$\begingroup\$

On many microcontrollers, in addition to being able to enable or disable particular interrupt causes (typically within an interrupt controller module), there is a master flag within the CPU core that determines whether interrupt requests will be accepted. Many microcontrollers will exit sleep mode if an interrupt request reaches the core, whether or not the core is willing to actually accept it.

On such a design, a simple approach to achieving reliable sleep behavior is to have the main loop check clear a flag and then check whether it knows any reason the processor should be awake. Any interrupt that occurs during that time which might affect any of those reasons should set the flag. If the main loop didn't find any cause to stay awake, and if the flag isn't set, the main loop should disable interrupts and check the flag again [perhaps after a couple NOP instructions if it's possible that an interrupt which becomes pending during a disable-interrupt instruction might be processed after the operand fetch associated with the following instruction has already been performed]. If the flag still isn't set, then go to sleep.

Under this scenario, an interrupt which occurs before the main loop disables interrupts will set the flag before the final test. An interrupt which becomes pending too late to be serviced before the sleep instruction will prevent the processor from going to sleep. Both situations are just fine.

Sleep-on-exit is sometimes a good model to use, but not all applications really "fit" it. For example, a device with an energy-efficient LCD might be most readily programmed with code that looks like:

void select_view_user(int default_user)
{
  int current_user;
  int ch;
  current_user = default_user;
  do
  {
    lcd_printf(0, "User %d");
    lcd_printf(1, ...whatever... );
    get_key();
    if (key_hit(KEY_UP)) {current_user = (current_user + 1) % MAX_USERS};
    if (key_hit(KEY_DOWN)) {current_user = (current_user + MAX_USERS-1) % MAX_USERS};
    if (key_hit(KEY_ENTER)) view_user(current_user);
  } while(!key_hit(KEY_EXIT | KEY_TIMEOUT));
}

If no buttons are pushed, and nothing else is going on, there's no reason the system shouldn't go do sleep during the execution of the get_key method. While it may be possible to have keys trigger an interrupt, and manage all user-interface interaction via state machine, code like the above is often the most logical way to handle highly-modal user-interface flows typical of small microcontrollers.

\$\endgroup\$
  • \$\begingroup\$ Thanks supercat for the great answer. Disabling interrupts and then going to sleep is a fantastic solution provided the core will awake from any interrupt sources irrespective of whether the global interrupt bit is set/clear. I took a look at the PIC18 interrupt hardware schematic, and this solution would work. \$\endgroup\$ – TRISAbits Mar 21 '13 at 15:57
1
\$\begingroup\$

Program the micro to wake on interrupt.

The specific details will vary depending on the micro you are using.

Then modify the main() routine:

int main()
{
    while(1)
    {
        sleep();
        process(); //process the interrupt
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Wake-on-interrupt architecture is assumed in the question. I don't think your answer solves the question/problem. \$\endgroup\$ – angelatlarge Mar 20 '13 at 21:32
  • \$\begingroup\$ @angelatlarge Point accepted. I've added a code example that I think helps. \$\endgroup\$ – jwygralak67 Mar 20 '13 at 21:51
  • \$\begingroup\$ @jwygralak67: Thanks for the suggestion, but the code you provide merely moves the problem into the process() routine, which now has to test whether the interrupt occurred before executing the process() body. \$\endgroup\$ – TRISAbits Mar 20 '13 at 21:58
  • 2
    \$\begingroup\$ If the interrupt hadn't occurred, why are we awake? \$\endgroup\$ – JRobert Mar 20 '13 at 22:13
  • 1
    \$\begingroup\$ @JRobert: We could be awake from a previous interrupt, complete the process() routine, and when we finish the if(has_flag) test and right before the sleep, we get another interrupt, which causes the issue I've described in the question. \$\endgroup\$ – TRISAbits Mar 20 '13 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.