Skip to content

Instantly share code, notes, and snippets.

@extrasleepy
Last active January 17, 2025 18:49
Show Gist options
  • Select an option

  • Save extrasleepy/9bede0458e55cfb8ec5167869e858b52 to your computer and use it in GitHub Desktop.

Select an option

Save extrasleepy/9bede0458e55cfb8ec5167869e858b52 to your computer and use it in GitHub Desktop.
//unknown days
//AKleindolph 2025 (with ChatGPT)
#include <avr/sleep.h>
#include <avr/wdt.h>
// Define pins for the LEDs
#define LED_PIN0 0
#define LED_PIN1 1
// Sleep and wake management
volatile uint8_t sleepCounter = 0; // Count the number of 8-second cycles
const uint8_t maxSleepCycles = 4; // 4 x 8 seconds = 32 seconds
void setup() {
pinMode(LED_PIN0, OUTPUT); // Set LED_PIN0 as output
pinMode(LED_PIN1, OUTPUT); // Set LED_PIN1 as output
// Disable ADC to save power
ADCSRA &= ~(1 << ADEN);
// Set up Watchdog Timer for 8-second intervals
setupWatchdogTimer();
}
void loop() {
// Fade LED on PIN1
fadeInOut(LED_PIN1);
// Fade LED on PIN0 immediately after
fadeInOut(LED_PIN0);
// Enter deep sleep until 7.5 minutes have passed
sleepCounter = 0;
while (sleepCounter < maxSleepCycles) {
enterDeepSleep();
}
}
void fadeInOut(uint8_t pin) {
// Fade in to 60% brightness in smaller steps for slower fade
for (int brightness = 0; brightness <= 153; brightness += 2) { // 60% of 255 = 153
analogWrite(pin, brightness);
delay(12); // Slower fade-in with adjusted delay
}
// Fade out from 60% brightness in smaller steps for slower fade
for (int brightness = 153; brightness >= 0; brightness -= 2) {
analogWrite(pin, brightness);
delay(12); // Slower fade-out with adjusted delay
}
// Ensure LED is completely off at the end
analogWrite(pin, 0);
}
void setupWatchdogTimer() {
// Clear the WDRF flag in MCUSR (reset if watchdog reset occurs)
MCUSR &= ~(1 << WDRF);
// Set the Watchdog Timer for 8-second intervals
WDTCR = (1 << WDP3) | (1 << WDP0);
// Enable Watchdog Timer interrupt mode (not reset mode)
WDTCR |= (1 << WDIE);
}
void enterDeepSleep() {
// Set the sleep mode to Power Down
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
// Disable brown-out detection for lower power consumption
MCUCR |= (1 << BODS) | (1 << BODSE);
MCUCR &= ~(1 << BODSE);
// Enter sleep mode
sleep_cpu();
// Wakes up here after Watchdog Timer interrupt
sleep_disable();
}
void delayWithLowPower(unsigned long ms) {
unsigned long start = millis();
while (millis() - start < ms) {
// Idle briefly to save power
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_enable();
sleep_cpu();
sleep_disable();
}
}
// Watchdog Timer Interrupt Service Routine
ISR(WDT_vect) {
// Increment the sleep counter each time the Watchdog Timer triggers
sleepCounter++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment