Hello,
I'm not sure how an Arduino Uno or Mega would react in following situation:
void setup(){
cli(); // disable interrupts
initPeriodicWDTInterrupt(); // Using the WDT as a peroidic timer with 32 ms
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_enable();
delay(40); // wait 40 ms - ensure that an interrupt has occured and is queued
sei();
sleep_mode();
}
void loop(){
// nothing to do here
}
ISR (WDT_vect){
// do stuff
}
How will the program be executed?
sei() -> jump into ISR -> go to sleep
or
sei() -> go to sleep -> jump into ISR
Thanks for your help,
Robin
Hello,
perhaps someone else got the same question.
After around one hour of searching I found this:
"Now, the AVR architecture guarantees that after interrupts are enabled, at least one instruction runs uninterrupted. In this case, this means that the sleep_cpu() function (which translates to a single sleep instruction) always runs."
Source (topic Sleeping): (...) — Interrupts, sleeping and race conditions on Arduino
and the sleep_mode() function is defined as:
#define sleep_mode() \
do { \
sleep_enable(); \
sleep_cpu(); \
sleep_disable(); \
} while (0)
So I think the correct answer is the first one:
sei() -> jump into ISR -> sleep
But if you change sleep_mode() to sleep_cpu(), which is defined as:
#define sleep_cpu() \
do { \
__asm__ __volatile__ ( "sleep" "\n\t" :: ); \
} while(0)
#endif
the first answer is correct:
sei() -> go to sleep -> jump into ISR
Am I correct?
Yes. But IIRC delay does not work with interrupts disabled so the program will hung.