I’m starting to play with the Watchdog Timer (which is pretty awesome, BTW) using the LED with my ATtiny85 to learn more how to use it.
I’ve used some web resources to put together the following sketch, but it is not working exactly as I wanted to, and was wondering if anyone would have some advice to share. So, here’s what is happening:
What I want the ATtiny85 do is:
a. sleep for 8 seconds, and do this continuously for 8 cycles (~64 sec)
b. when it reaches ~64 sec, turn on the LED
c. after 220 seconds, turn LED off
d. go back to #a
But instead, what my sketch is doing now is:
a. sleep for 8 seconds, and do this continuously for 8 cycles (~64 sec)
b. when it reaches ~64 sec, turn on the LED
c. after 220 seconds, turn LED off
d. after~1 second, it goes back to #b, and repeats the cycle b through d
My guess is that the problem is in the loop section, since it seems that it is running the led commands infinitely without calling the sleep function at the end.
Therefore, how can I tell the ATtiny to do the entire process (a. through d.) over and over again?
Thanks
#include <avr/sleep.h>
#include <avr/power.h>
int LED = 0;
#define WDTCR_REG WDTCR
volatile long watchdog_counter = 0;
void setup(void)
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
ADCSRA &= ~(1<<ADEN); //Disable ADC
ACSR = (1<<ACD); //Disable the analog comparator
DIDR0 = 0x3F; //Disable digital input buffers on all ADC0-ADC5 pins to save power
setup_watchdog(9); // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
// 6=1 sec, 7=2 sec, 8=4 sec, 9= 8sec
pinMode(LED, OUTPUT);
}
void loop()
{
sleep_mode();
if (watchdog_counter >= 8) { // # of watchdog cycles
watchdog_counter = 0;
commands_to_carry_out();
}
}
void commands_to_carry_out() {
digitalWrite(LED, HIGH);
delay(220000); // 220000 = ==> 220 sec (3.6 min)
digitalWrite(LED, LOW);
delay(1000); // wait 1 second before going to sleep
}
void setup_watchdog(int ii) {
byte bb;
int ww;
if (ii > 9 ) ii=9;
bb=ii & 7;
if (ii > 7) bb|= (1<<5);
bb|= (1<<WDCE);
ww=bb;
MCUSR &= ~(1<<WDRF);
// start timed sequence
WDTCR_REG |= (1<<WDCE) | (1<<WDE);
// set new watchdog timeout value
WDTCR_REG = bb;
WDTCR_REG |= _BV(WDIE);
}
ISR(WDT_vect) {
watchdog_counter++;
}