power save mode on ATMEGA324P with async timer

1 post / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm using timer 2 with a 32,768kHz crystal in async mode. I'm using the overflow interrupt in my software to run once every second. To keep the CPU in sleep mode, I have used the following code:

 

while(1){
	set_sleep_mode(SLEEP_MODE_PWR_SAVE);
	cli();
	sleep_enable();
	sei();
	sleep_cpu();
	sleep_disable();
	sei();
}

When the cpu is clocked with the internal oscillator at 1MHz, everything works fine. When the cpu runs at 8Mhz, the overflow interrupt is running four times instead of once only, in ~10usec intervals. After some experimenting, I solved that by adding two lines:

 

while(1){
	set_sleep_mode(SLEEP_MODE_PWR_SAVE);
	cli();
	sleep_enable();
	sei();
	sleep_cpu();
	sleep_disable();
	TCCR2A=0;		// ADDED
	while (ASSR&7) ;	// ADDED
	sei();
}

I'd like to know if this is the right/safe way to use the sleep mode with the async timer. I'm not sure if the cli() / sei() are really necessary or if it is sufficient to call set_sleep_mode(..) and sei() once before entering the while loop.