Monday, July 28, 2014

Using the Watchdog Timer for Periodic Tasks

The more I read the datasheet on the mega1284p the more I am amazed at what I learn about chips I have been using for a long time. Forget about using timer 2 for your periodic tasks. It is nice because it can continue to run in sleep mode but it is only an 8 bit counter. Even with the max prescaling (1024) with my 8 Mhz clock you roll over about every 0.03 seconds. This forced me to keep a counter running to only update my clock every 1 second or so because the overhead of doing it every 0.03 seconds crashed the processor. Then I read the section on the Watchdog Timer. I have used it before to reset the processor when my code hung up, but I learned that the WDT can be used in interrupt mode only. This means I can use it for the periodic functions. And the great part is it has it's own clock source which will allow it to roll over from 16ms to 8 seconds. And this leaves Timer 2 for other Arduino functions or I can bring the chip down to lower shutdown levels to conserve battery power. You have to use a timing sequence to enable the WDT, so after some searching and tweaking, I found the following to work:

// Setup the watchdog timer to overflow every 8 seconds.
  MCUSR &= ~(1<<WDRF);
  WDTCSR |= (1<<WDCE) | (1<<WDE);
  WDTCSR = 1<<WDP0 | 1<<WDP3; // Set Watchdog Timer to interupt on 8 second overflow
  WDTCSR |= _BV(WDIE); // Enable Interupt but not Reset

That was it. I then used the Interrupt service routine to set my update flag ( the interrupt caused the chip to wake up from sleep)

SIGNAL(WDT_vect){
  //Add periodic operations
  if (mSelect == -1) clockUp = true; // The current mode is the clock, otherwise, don't update
}

I am currently optimizing the code to minimize battery power. I have it down to about 0.6 ma in sleep mode. The lcd should be about 0.25 ma. Unfortunately, the rest is mostly the stock IMU board. Even placing the individual components in low power mode, it is still a big draw. I am going to fix that in my next design by replacing the board with a BMP180 and a LSM9DS0 IMU. These should virtually disappear in low power mode and the 0.25 ma for the display should be just about all I see. That will give about 16 days of standby time for the 100mah battery I have. I have ordered the final parts from Mouser and will finish the PC board layout after they arrive. The new design will have the improved IMU, barometer, bluetooth, an installed speaker, and I hope, will all fit in the LunaTik ipod nano 6th gen watch case to make this project truly wearable and good looking. Stay tuned.

No comments:

Post a Comment