Help calculating cummulative uptime

Can someone help me with my logic here, I’m not getting something. I want to calculate seconds since boot. Since millis() rolls I want to catch that also. If I know it’s rolled I can track how many times it’s rolled and compensate.

int times_rolled = 0;
long last = 0;
long get_uptime() {
  long mil = micros();
  
  // If this run is less than the last the counter rolled
  if (last < mil) {
    times_rolled++; 
  }
  
  // Seconds is easy
  long seconds = mil / 1000;
  // Add one the seconds for times rolled also
  seconds += ((times_rolled * 4294967296) / 1000);
  
  last = mil;
  return seconds;
}

You talk about millis(), then call micros(). Two different function returning two different times.

Which should you be calling or asking about?

By the way, both functions return a value of type unsigned long, not long.

An easier way may be to use one of the timer libraries and simply increment a variable in the timer function…

http://www.arduino.cc/playground/Main/MsTimer2

// Uptime counter
#include <MsTimer2.h>

volatile unsigned long _Uptime =0;

void updateuptime() {
_Uptime++;
}

unsigned long getUpTime()
{
    unsigned long ret;
    // optional: disable interrupts
    cli();
    ret = _Uptime;
    // optional: enable interrupts 
    sei();
    return ret;
}

void setup() {
  MsTimer2::set(1000, updateuptime); 
  MsTimer2::start();
}

void loop() {
   // call getUpTime here.
}

Just call getUpTime once and a while to retrieve the number of seconds since boot.