Watchdog Timer Issue

Hi,

I’ve been tearing my hair out all day on this & I finally give up.
I’m trying to implement a watchdog timer on a project, to recover from the device hanging very occasionally.

I’ve tried this on a 168 & a 328p - I’m using the ICs on a breadboard, they do not have a bootloader, and I’m programming them via a TinyISP

I found this excellent guide:
http://arduino.cc/forum/index.php/topic,63651.0.html

But since I don’t have serial, I modified the code a touch to give me visual indication of what was happening.
My code is below.
What I see is my status LED blinking, slower and slower. When it gets to around 2 secs period, the wdt_reset() doesn’t occur in time, and the watchdog kicks in.
What I then see is the LED blinking very rapidly - I think the IC has gone in to a tight reset loop.

I also tried the simpler method of enabling the timer:

 wdt_reset(); // reset the WDT timer 
  wdt_enable(WDTO_2S); //and enable it

with the same results

Clearly I’ve messed up somewhere - can anyone point me in the right direction?

Thanks,

James

/* 
Watchdog Timer Basic Example
10 June 2011
Nicolas Larsen
*/
#include <avr/wdt.h>
int loop_count = 0;
void setup()
{
  pinMode(13,OUTPUT);
  digitalWrite(13,HIGH);
  delay (500);
  watchdogSetup();
}

void watchdogSetup(void)
{
cli(); // disable all interrupts
wdt_reset(); // reset the WDT timer
/*
   WDTCSR con?guration:
   WDIE  = 0: Interrupt Enable
   WDE   = 1 :Reset Enable
   WDP3 = 0 :For 2000ms Time-out
   WDP2 = 1 :For 2000ms Time-out
   WDP1 = 1 :For 2000ms Time-out
   WDP0 = 1 :For 2000ms Time-out
*/
// Enter Watchdog Con?guration mode:
WDTCSR |= (1<<WDCE) | (1<<WDE); 
// Set Watchdog settings:
 WDTCSR = (0<<WDIE) | (1<<WDE) | (0<<WDP3)  | (1<<WDP2) | (1<<WDP1)  | (1<<WDP0);
sei();
}
void loop()
{
  digitalWrite(13,HIGH);
  delay(100);
  digitalWrite(13,LOW);
  delay(100+loop_count);
  loop_count=loop_count+100;
  wdt_reset();
}

OK - spotted my own dumb mistake -

you MUST reset & then enable the WDT RIGHT at the start of the Setup() section.

Once the WDT fires, it's left enabled at restart, but the duration is set to the minimum time (20ms).

If the resest is anywhere else, it trips again and you're stuck in an endless loop.

D'Oh.