Created
December 20, 2017 16:17
-
-
Save platisd/fc124a22011a9250d9be3f1969c180f1 to your computer and use it in GitHub Desktop.
Blinking LED with watchdog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <avr/sleep.h> | |
#include <avr/power.h> | |
#include <avr/wdt.h> | |
#include <avr/interrupt.h> | |
const int LED_PIN = PB4; | |
volatile bool pinState = false; | |
enum WatchDogTimeout { | |
WDT_16ms = 0, | |
WDT_32ms, | |
WDT_64ms, | |
WDT_128ms, | |
WDT_250ms, | |
WDT_500ms, | |
WDT_1sec, | |
WDT_2sec, | |
WDT_4sec, | |
WDT_8sec | |
}; | |
void goToSleep() { | |
set_sleep_mode(SLEEP_MODE_PWR_DOWN); | |
ADCSRA = 0; // Turn off ADC | |
power_all_disable(); // Power off ADC, Timer 0 and 1, serial interface | |
sleep_enable(); | |
sleep_cpu(); // Sleep here and wait for an interrupt or watchdog bark | |
sleep_disable(); | |
power_all_enable(); // Power everything back on | |
} | |
void triggerWatchDogIn(WatchDogTimeout wdt) { | |
// Adopted from InsideGadgets (www.insidegadgets.com) | |
byte timeoutVal = wdt & 7; | |
if (wdt > 7) { | |
timeoutVal |= (1 << 5); | |
} | |
timeoutVal |= (1 << WDCE); | |
MCUSR &= ~(1 << WDRF); | |
WDTCR |= (1 << WDCE) | (1 << WDE); // Start timed sequence | |
WDTCR = timeoutVal; | |
WDTCR |= _BV(WDIE); | |
wdt_reset(); // Pat the dog | |
} | |
ISR(WDT_vect) { | |
pinState = !pinState; | |
//wdt_disable(); // Disable watchdog so it does not get automatically retriggered | |
} | |
void setup() { | |
pinMode(LED_PIN, OUTPUT); | |
digitalWrite(LED_PIN, pinState); | |
triggerWatchDogIn(WDT_250ms); | |
} | |
void loop() { | |
digitalWrite(LED_PIN, pinState); | |
goToSleep(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment