Difference between revisions of "ATtiny84 WDT sleep"

From wikipost
Jump to navigationJump to search
 
 
Line 5: Line 5:
 
#include <avr/wdt.h>
 
#include <avr/wdt.h>
 
#include <avr/interrupt.h>
 
#include <avr/interrupt.h>
 +
 +
// these define cbi and sbi, for as far they are not known yet
 +
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
 +
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
  
 
void setup_watchdog(int ii)  
 
void setup_watchdog(int ii)  

Latest revision as of 21:55, 4 November 2019

The following code puts the ATtiny84 into sleep mode and it is woken up by an overflow of the Watchdog Timer (WDT). It should be compatible with the ATtiny85 series. Note that disabling the ADC functions (ADC and Comparator) are probably in different registers (e.g. ADCSRA or ADCSRB).

#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>

// these define cbi and sbi, for as far they are not known yet
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

void setup_watchdog(int ii) 
{
  // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
  // 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec

  uint8_t bb;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCSR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCSR = bb;
  WDTCSR |= _BV(WDIE);
}


// system wakes up when watchdog is timed out
void system_sleep() 
{
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF
  setup_watchdog(9);                   // approximately 8 seconds sleep
 
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();
  sei();                               // Enable the Interrupts so the wdt can wake us up

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out 
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}





int main( void ) 
{

 

  while ( 1 ) 
  {

     <your code goes here>		
     <your code goes here>		
     <your code goes here>		
	
     system_sleep();  // start power down sequence
	
  }

  return 0;
}

// Watchdog Interrupt Service / is executed when watchdog timed out
ISR(WDT_vect)
{
 // nothing here
}