Know sleep time

Hi guys!

I have a question. I want to use multiple pin sleep with awake time. My Idea is sent a message every 10 minutes. If the electron wakes up by pin, is there any way to know the time the electron has been asleep? To sleep it again with the remaining time and complete 10 minutes.

Thanks!

Record the UNIX time in flash when the unit goes to sleep. Pull the UNIX time at wake and subtract. You’ll have the sleep time in seconds.

Particle exposes this as Time.now().

1 Like

Something like this should get you started:

int SLEEP_PERIOD =   600   ;     // (seconds) Sleep time.   3600 = 1 hour .  See  goIntoLowPowerMode()
static unsigned long lastSleep =    0 ;

void setup() {
}  // End Setup

void loop() {
  // Do your Normal Stuff
  goIntoLowPowerMode();   // Go To Sleep
} // End Loop

void goIntoLowPowerMode() { // Go To SLEEP
  int sleepLeft = SLEEP_PERIOD;
  int startSleep = Time.now();
  while (sleepLeft > 0) { // Need to Sleep
    System.sleep(D2, RISING, sleepLeft, SLEEP_NETWORK_STANDBY );   // Will wake from D2, or SLEEP_PERIOD (seconds)
    // WILL Always Wake Up here, If Sleep Period has ellapsed, or if woken-up by PIN 
    sleepLeft = SLEEP_PERIOD - (Time.now() - startSleep);  // Check if it was asleep long eneough, or woke by pin.
  
    if (sleepLeft > 1) {  
      unsigned long timeout = millis();
      while ( millis() - timeout < 10) delay(1);
    }
  }
  lastSleep = millis();
}  // End Low Power Mode Function


1 Like