About mbed
mbed is a tool for Rapid Prototyping with microcontrollers.
Take the tour...
Back to blog

Library Update: Real-Time Clock

We thought it was about time to get time() working...

The mbed Microcontroller has a Real-Time Clock (RTC) on it, which is a built in hardware clock that can keep track of the time and date. We've now done the plumbing to make use of it sane, and you can now just use standard C functions to read, set and format the time. Ideal for data logging and other time related functions!

The basic function to read the time is named time(). This returns the time in seconds since January 1st 1970, often known as the UNIX timestamp. This is a fairly universal way to define time, and can be transformed in to other string forms using C functions. The function time() actually takes a pointer as an argument, but in most case you'll just want to pass NULL. Here is a most basic example to get the current time:

#include "mbed.h"

int main() {
    while(1) {
        time_t seconds = time(NULL);
        printf("Seconds since January 1, 1970: %d\n", seconds);
        wait(1);
    }
}

Of course, that isn't much use until the time has been set somehow, as the RTC won't have been setup. Here is the minimal way to set the time, in this case providing the UNIX timestamp:

#include "mbed.h"

int main() {
    set_time(1256729737);  // Set RTC time to Wed, 28 Oct 2009 11:35:37
}

A natural thing to want to do is display the time and/or date in a human readable way, either on a screen, in a file, or over a terminal. For that, C provides a number of functions to help do this. This example shows these functions in use:

#include "mbed.h"

int main() {
    while(1) {
        time_t seconds = time(NULL);

        printf("Time as seconds since January 1, 1970 = %d\n", seconds);

        printf("Time as a basic string = %s", ctime(&seconds));

        char buffer[32];
        strftime(buffer, 32, "%I:%M %p\n", localtime(&seconds));
        printf("Time as a custom formatted string = %s", buffer);

        wait(1);
    }
}

The results of this are shown below:

For all the string formatting options, see the list of format specifiers in the strftime function api documentation.

While we were testing, Rolf said he thought it'd be nice to be able to set the time from the terminal, so here is the final example for this post that does just that:

// Example to setup the Real-Time Clock from a terminal, sford

#include "mbed.h"

int main() {

    // get the current time from the terminal
    struct tm t;
    printf("Enter current date and time:\n");
    printf("YYYY MM DD HH MM SS[enter]\n");    
    scanf("%d %d %d %d %d %d", &t.tm_year, &t.tm_mon, &t.tm_mday
                             , &t.tm_hour, &t.tm_min, &t.tm_sec);

    // adjust for tm structure required values
    t.tm_year = t.tm_year - 1900;
    t.tm_mon = t.tm_mon - 1;
    
    // set the time
    set_time(mktime(&t));
        
    // display the time
    while(1) {    
        time_t seconds = time(NULL);
        printf("Time as a basic string = %s", ctime(&seconds));
        wait(1);
    }
}

Hopefully this gives you a good insight in to how to use the RTC from software, but of course one of the nice features of the RTC is that it is designed to support a battery backup. This means just like your PC or various equipment around the house, the mbed can keep time even when the power is disconnected.

It obviously needs some source of power to keep the clock running, but it is very tiny and this is where the VB pin comes in. By connecting a 3V battery to this pin, the clock can be kept running for a long time with only a single coin cell (watch battery). Wire a 3v coin cell battery between VB and GND, and when you disconnect the main power (e.g. USB cable) the clock will continue to run:

For full details of the time related functions, see the time API page:

To update to this new library version, as ever just start a new project or select the existing mbed library in an existing one and hit "Update". Please feedback any problems/questions to the forum.

Have Fun!

Comments

29 Oct 2009

All,

 

A handy website from BJ Sintay for current/converting unix time is at ...

http://www.unixtimestamp.com/index.php

 

-Ken

29 Oct 2009 . Edited: 30 Oct 2009

I $60 digital clock :)

30 Oct 2009

From a C++ point of view, shouldn't this be wrapped in a class?

12 Nov 2009

Vlad Cazan wrote:

I $60 digital clock :)

Could I see your code?

12 Nov 2009

Can I invoke ctime(&seconds), ctime(&minutes), ctime(&hours), etc as integers?

26 Feb 2011

Is there any reasonable way to get the 12-hour format without the leading 0? I was going to do some post-processing on the output of strftime(), but doing this in the general case becomes tricky: it's easy to detect if the input uses %I, but not all of the format specifiers result in equal-length output. That is, the position of the hours value in the output string may change, since there may be something like %A or %B in front of it.

I'll probably end up hacking something together, but it would be useful if this was added as an option in strftime(). Just a note :)

26 Feb 2011

Hi Phil,

strftime() is an implementation of a standard C library function ([[http://www.cplusplus.com/reference/clibrary/ctime/strftime/|strftime]]), so it is unlikely this would be added, so I think you are right to try and write a solution.

It is an interesting one; if you just want to turn the 0 in to a space, i can see some easy ways (e.g. generate a second verison with XX instead of the hour, but everything else the same, then use [[http://www.cplusplus.com/reference/clibrary/cstring/strchr/|strchr]] on the second to word out which byte to change in the first. I'm sure there are lots of other approaches, so sounds like a nice little challenge :)

If you do come up with a useful code sequence, perhaps you could post it here so someone searching for the same thing can re-use your handywork.

Simon

Please log in to post a comment.