Page 1 of 1

Time measurement in seconds

Posted: Sat Dec 26, 2015 9:56 pm
by kab
Hello!

I'm totally miss how to measure time in seconds.
Task: store time for each event and send (upon request) time in seconds for each event - how old it happen.

Code:

Code: Select all

//! time variable
static uint32_t last_time_in_seconds=0;

//! update timer function
static void UpdateTime(void)
{
   static systime_t last_time_in_ticks=0;
   systime_t ticks;

   //! Update our time
   ticks = chVTGetSystemTimeX();

   if (ticks > last_time_in_ticks)
   {
      //! no overflow, just add delta
      last_time_in_seconds += ST2S(ticks - last_time_in_ticks);
   }
   else
   {
      //! overflow happen
      last_time_in_seconds += ST2S(0xffffffff - last_time_in_ticks + ticks);
   }

   last_time_in_ticks = ticks;
}



This code is called for each happen event (to update time) and then global var last_time_in_sec stored in structure for each event.

Code: Select all

UpdateTIme();
event->time=last_time_in_seconds;


Problem - last_time_in_seconds are very large.

Code: Select all

chprintf(chp, "Time: %d\r\n", last_time_in_seconds - (event->time));


Few seconds after system start i got values more than 1000000.
What i do wrong?

Re: Time measurement in seconds

Posted: Sun Dec 27, 2015 8:53 am
by Giovanni
Not sure about that code but you could just increase a variable every second using a virtual timer or a thread.

Giovanni

Re: Time measurement in seconds

Posted: Tue Dec 29, 2015 9:48 pm
by kab
Separate thread with inc to variable and 1 second delay working fine and pretty accurate.
Thanks!