This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Set Current Time with time() and ctime()

Hi All,

I want to set the RTC time to the current time and date without hard-coding it.

I tried to use the function time() and ctime() defined in time.h, but I read that time() is a semihosted function (http://www.keil.com/support/man/docs/armlib/armlib_chr1359122861930.htm)

#include <time.h>

time_t rawtime;
char buffer[50] ={0};

time(&rawtime);
sprintf (buffer, "%s", ctime(&rawtime) );

So if I include time(&rawtime), then the program stops with BKPT 0xAB (indicating semihosting) and if I don't include it then the buffer displays 00:00 1 Jan 1970.

So my question is, how do I write the retarget.c to use the time function? I read a lot of examples on retargeting printf, but can't find anything on time().

Or what is the normal way of setting the current date/time?

Thank you.

Parents
  • Note that time() doesn't set any time. It's just intended to retrieve time.

    If you have an RTC that ticks a variable very second, and zero is the Unix epoch of 1970-01-01 00:00, then you can just write your own time:

    time_t time(time_t* t) {
        time_t tmp = my_magical_rtc_tick_value;
        if (t) *t = tmp;
        return tmp;
    }
    

    If the RTC maybe can generate an interrupt pulse every second and is interfaced using for example Maxim/Dallas one-wire protocol, then you need to write code that can write a clock value to the RTC, and that on program start can retrieve the current time. Then an interrupt handler that can increment a one-second tick variable.

    If you have an internal RTC in the processor, then you might even read out the time from the RTC on every call to time() - but you may then have to use mktime() to convert from broken-down year, month, day, hour, min, sec into the epoch tick value that time() is expected to return.

Reply
  • Note that time() doesn't set any time. It's just intended to retrieve time.

    If you have an RTC that ticks a variable very second, and zero is the Unix epoch of 1970-01-01 00:00, then you can just write your own time:

    time_t time(time_t* t) {
        time_t tmp = my_magical_rtc_tick_value;
        if (t) *t = tmp;
        return tmp;
    }
    

    If the RTC maybe can generate an interrupt pulse every second and is interfaced using for example Maxim/Dallas one-wire protocol, then you need to write code that can write a clock value to the RTC, and that on program start can retrieve the current time. Then an interrupt handler that can increment a one-second tick variable.

    If you have an internal RTC in the processor, then you might even read out the time from the RTC on every call to time() - but you may then have to use mktime() to convert from broken-down year, month, day, hour, min, sec into the epoch tick value that time() is expected to return.

Children