atmega328 sleep and watchdog

First post :slight_smile:

I’m creating a customised atmega328 board (same chip as Pro Mini). I use 2 pins - D2 and D3 - as external interrupts to wake up from sleep. Since good reliability is required, i’ve added a watchdog for code lockup protection. The device will run on batteries and never powered down.

How does this look?

#include <avr/sleep.h>                  
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>    // Needed to use interrupts

volatile int int0_flag;
volatile int int1_flag;

#define TRUE 1
#define FALSE 0


ISR(INT0_vect)
{
    int0_flag = TRUE;    
}


ISR(INT1_vect)
{
    int1_flag = TRUE;    
}


void sleepNow()
{   
    wdt_disable();

    byte adcsra_save = ADCSRA;
    ADCSRA = 0;  // disable ADC
    power_all_disable ();   // turn off all modules
    set_sleep_mode (SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    noInterrupts();

    sleep_enable(); 

    interrupts();
    sleep_cpu ();            // now goes to Sleep and waits for the interrupt 
    sleep_disable ();      // precaution
    ADCSRA = adcsra_save;  // stop power reduction
    power_all_enable ();   // turn on all modules 

    //enable watchdog to check for code lockups
    wdt_enable(WDTO_8S);
}  // end of sleepNow


void setup()
{

   Serial.begin(9600);
   Serial.println("starting...");      

   pinMode(2, INPUT);
   pinMode(3, INPUT);

   digitalWrite(2, HIGH);
   digitalWrite(3, HIGH);

   EICRA = B00001010; // configure pin 2 and 3 for falling
   EIMSK = B00000011; // mask for INT1 and INT0

   int1_flag = FALSE;
   int0_flag = FALSE;  

   wdt_enable(WDTO_8S);

   Serial.println("ready...");  
}

void loop()
{       
       if (int0_flag == TRUE)
       {
            Serial.println("wake up from INT0");   
            int0_flag = FALSE;
       } 
       if (int1_flag == TRUE)
       {
            Serial.println("wake up from INT1");  
            int1_flag = FALSE;
       }

       Serial.println("1");
       delay(1000);
       Serial.println("2");
       delay(1000);
       Serial.println("3");
       delay(1000);
       sleepNow();
       //while (1)
}

Cheers

Does anyone have an answer?

Cheers

How does this look?

Looks good :slight_smile: I did not check every detail. Why don't you just try it on your board? Does it work?

Looks good :slight_smile: I did not check every detail. Why don't you just try it on your board? Does it work?

I tested it on a board and it appears to work fine.

As i need very high reliability, i just want to make sure there is no chance that any problems can arise when never powering it down and running on batteries.

Thanks