display time since boot

jensvanhoof
Posts: 3
Joined: Thu Sep 23, 2021 6:52 pm

display time since boot

Postby jensvanhoof » Wed Oct 27, 2021 4:27 pm

Hi all,

I'm trying to diplay the total time my Esp32 has been running, on a LCD display.
I'm using the esp_timer_get_time() function which gives back the running time in microseconds.

I'm reading that value into a variable called microSecondsSinceBoot, and the data type is a long, which should be 64 bit, and shouldn't overflow for something like 290 million years.

Yet, something strange happens consistently at 35 minutes, 48 seconds. (35:47 is still correct), instead of displaying 00:35:48 it goes to something like 00:35:-4000 (don't remember the exact number, but anyway a negative number in the thousands).

This is my code:

Code: Select all

void upTime(void *parameter)
{
  for (;;)
  {

    microSecondsSinceBoot = esp_timer_get_time();
    previousSecondsSinceBoot = secondsSinceBoot;
    secondsSinceBoot = microSecondsSinceBoot / 1000000;
    timeSeconds += (secondsSinceBoot - previousSecondsSinceBoot);
    if (timeSeconds > 59)
    {
      timeSeconds = 0;
      timeMinutes += 1;
    }

    if (timeMinutes > 59)
    {
      timeMinutes = 0;
      timeHours += 1;
    }

    if (timeHours > 23)
    {
      timeHours = 0;
    }

    sprintf(uptimeBuffer, "   %02i:%02i:%02i         ", timeHours, timeMinutes, timeSeconds);
    bootTimePrinted = false;

    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }
}
I'd like to understand why this happens, as it must be something super logical, but I don't see it (yet).

Thanks!
Jens

mgsecord62
Posts: 20
Joined: Thu Nov 02, 2017 12:40 am

Re: display time since boot

Postby mgsecord62 » Thu Oct 28, 2021 8:26 pm

It looks like you assigned the variable microSecondsSinceBoot to an signed 32 bit variable and it rolls over to a negative value at 2^31 microseconds or ~36 minutes. I believe that the esp_timer_get_time() function returns a signed 64 bit value (int64_t) so I would declare the microSecondsSinceBoot variable the same. Then the counter should not roll over until 2^63 microseconds or many many years. The other option is to handle the roll overs in your code.

jensvanhoof
Posts: 3
Joined: Thu Sep 23, 2021 6:52 pm

Re: display time since boot

Postby jensvanhoof » Fri Oct 29, 2021 7:18 am

Indeed that seems to have fixed it! I was wrongfully trying to figure it out with 2^32 instead of 2^31 that's why I didn't get to that exact number.

I also was under the impression that declaring a variable as long would automatically initialise it at 64-bit. int64_t fixed it!
I'll let you know in 292 million years when it'll be confirmed that now indeed it's 64 bit! :-)

Who is online

Users browsing this forum: No registered users and 26 guests