Power down sleep with watchdog wakeup

I’ll share a code I made to put your arduino into a sleep mode and wake up after x minutes.

I tested the time elapsed with a cronometer and works well.

For arduino mega2560, the current change was from 32 mA to 12 mA

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

int count = 0;
int led = 13;

ISR (WDT_vect) {
  wdt_reset();
}

void setup() {
  wdt_disable();
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
  Serial.begin(19200);
  Serial.println("Starting...");
}

void loop() {
  Serial.print("Awake for ");
  Serial.print(count);
  Serial.println(" sec");
  count++;
  delay(1000);
  
  if (count >= 5) {
    int sleep_time = 1; // Minutes
    Serial.println("Entering Sleep mode");
    delay(100)
    count = 0;
    digitalWrite(led, LOW);
    sleep_fun(sleep_time); // sleep function called here
    digitalWrite(led, HIGH);
    
  }
}

void sleep_fun (unsigned long sleep_time) {
  sleep_time = 60 * sleep_time; // minutes to sec
  unsigned long counter = 0;
  wdt_enable_8s();
  unsigned long prevtime = millis();
  for (int i = 0; i < round((float)sleep_time / 8); i++) {
    //set_sleep_mode(SLEEP_MODE_IDLE); //the least power savings
    //set_sleep_mode(SLEEP_MODE_ADC);
    //set_sleep_mode(SLEEP_MODE_PWR_SAVE);
    //set_sleep_mode(SLEEP_MODE_STANDBY);
    set_sleep_mode(SLEEP_MODE_PWR_DOWN); //the most power savings
    sleep_enable();
    sleep_mode();
    sleep_disable();
    counter += 8;
    // Fix new watchdog time if sleep_time is not a multiple of 8
    if (sleep_time - counter == 4){
      wdt_disable();
      wdt_enable_4s();      
    }
  }
  Serial.print("Time elapsed: ");
  Serial.println(millis() - prevtime);
  wdt_disable();
}

void wdt_enable_8s() {
  // sleep bit patterns:
  //  1 second:  0b000110
  //  2 seconds: 0b000111
  //  4 seconds: 0b100000
  //  8 seconds: 0b100001
  cli();    //disabled ints
  MCUSR = 0;   //clear reset status
  WDTCSR |= 0b00011000;    //WDCE y WDE = 1 --> config mode
  WDTCSR = 0b01000000 | 0b100001;    //set WDIE (interrupt mode enabled), clear WDE (reset mode disabled) and set interval to 8 seconds
  sei();   //enable ints
}

void wdt_enable_4s() {
  cli();    //disabled ints
  MCUSR = 0;   //clear reset status
  WDTCSR |= 0b00011000;    //WDCE y WDE = 1 --> config mode
  WDTCSR = 0b01000000 | 0b100000;    //set WDIE (interrupt mode enabled), clear WDE (reset mode disabled) and set interval to 4 seconds
  sei();   //enable ints
}