Programming, Uncategorized

Uptime and ESP8266

Any time meassurement in ESP8266 is done through millis() function. A nice article about this topic is here. The article emphasis duration meassuremnt instead of timestamps. The modular arithmetic is going to bypass any rollover of unsigned long type used for millis() function. The rollover happens approximately each 47 days. If we need longer time we can increae it by using 64 bits:

uint64_t millis64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

If we do not need to measure seconds for uptime we can use unsigned long even for thousand years, by simplification to minutes. It is just necessary to use millis one time per minute (it is 60 000 ticks). The code could look like this:

unsigned long TT,upM=0,upH=0,upD=0;

if (millis()-TT >60000)
    {
      upM++;
      if (upM == 60) 
      {
        upM=0;
        upH++;
      }
      if (upH == 24)
      {
        upH=0;
        upD++;
      }
    }
phone