How to count how long an arduino slept ?

I'm sending my arduino to sleep, and trying to count how long it slept :

    lastTime = millis();
    set_sleep_mode (SLEEP_MODE_STANDBY);  
    byte old_ADCSRA = ADCSRA;
    // disable ADC to save power
    ADCSRA = 0;  
    power_all_disable ();  // turn off various modules
    interrupts ();
    sleep_cpu (); 
    totalSleepTime += millis() - lastTime;

the totalSleeptime is alwayes zero, although it sleeps for a while.
Maybe the arduino is not counting while sleeping ?

Maybe the arduino is not counting while sleeping ?

Not counting what? Depending on the sleep mode, the clock may not be ticking, so there is nothing to count.

imagine you are counting sheep in your head to put you to sleep and let's say it works.

When you wake up, do you think your count will have progressed while you were sleeping?

So while the Arduino is sleeping, he doesn't count anything ? I assumed that the main 16mhz clock works while sleeping.

Is there a way to figure out for how long he slept ?

Is there a way to figure out for how long he slept ?

Use an RTC. Read what time it is before going to sleep. Read what time it is when you wake up.

Is there a way to figure out for how long he slept ?

So you need basically a clock to still run while your arduino sleeps.

it could be your arduino :

  • use a "light sleep" mode - in SLEEP_MODE_IDLE for example the clocks are running. This means that the normal Timer0 which is used by millis() will be running, so counting will work but you will wake up approximately every millisecond

  • you could use the WatchDog timer to wake up every x (say 8 ) seconds - and update a variable to count to number of intervals and go back to sleep. for example and you would get a multiple of 8 seconds estimates of how long you "kinda slept" (but it is not so accurate)

  • it could be an external device that would stay powered. a RTC would give you a precision up to 1 second roughly, some RTC would go even to 100th of a second

  • Nick G. has all the details you want on power-saving techniques for the Atmega328P

Many RTCs can provide a square wave output from their 32 kHz clock that you can use to clock Timer2 while the microcontroller is in POWER_SAVE mode.