Linking time() to my custom UNIX time function

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Linking time() to my custom UNIX time function

Andris Igaunis
Dear Sir or Madam,
I cannot get around the problem of getting time() function in <time.h> to work properly.
I have a microcontroller with no OS (embedded system), it is a single core, single thread ARM Cortex-M4 Silicon Labs EFM32GG12B110F1024GM64 processor, and Silicon Labs IDE Simplicity Studio is using arm-gnu-gcc compiler v7.2.1 arm-none-eabi-gcc with Newlib Nano C library.
I can configure a 32-bit hardware counter to count at 1 tick/second, initialize it to current UNIX time (1579964593 at the writing of this e-mail), but how do I tell time() function to use my custom function as the underlying source of time?
I did spend a night searching for info, but documentation does not explicitly tell how, most Newlib articles just make an example that does not return anything, so I am kinda stuck. I have figured out that maybe it has something to do with _gettimeofday() or _gettimeofday_r() functions.
In Github, it says that time() function implementation is:
time_t
_DEFUN (time, (t),
        time_t * t)
{
  struct timeval now;

  if (_gettimeofday_r (_REENT, &now, NULL) >= 0)
    {
      if (t)
        *t = now.tv_sec;
      return now.tv_sec;
    }
  return -1;
}

That _gettimeofday_r() function according to Github just calls another, similarly named _gettimeofday() function. I tried the following: created _gettimeofday():

int _gettimeofday(struct timeval *p, void *z){
        printf("gettimeofday called!\r\n");
        p->tv_sec = 100;
        p->tv_usec = 50;
        return 0;
}

In main code, I call:
        while(1){
                printf("Hello!\r\n");
                printf("%d\r\n", time(NULL));
                delay(1000);
        }

The output is

Hello!
gettimeofday called!
0

So the function _gettimeofday() is called, but its data is just discarded. time() just returns 0 instead of dummy 100.
If I delete _gettimeofday() function, the time() function returns -1, so I guess I am somewhere on the right track, but all leads end here.
I could also just forget about it and use my custom time function, but now I am kinda addicted to solving this puzzle.

Your help will be highly appreciated.

Best regards,
Andris Igaunis