Saturday, March 19, 2011

Digital clock implementation in C using time.h header

This sample application is the implementation of the clock() function available in time.h header. The time function is very useful and necessary. Some of the examples of usage of time function are:
  • Security applications might need to update the security keys every one minute or more. 
  • You may need to write a function to send files to the remote server every one minute or extract files from the server every 15 minutes. 
and many more.

I have created a simple digital clock to show you the implementation of clock() function. The sample code given below is written in C using codeblocks IDE on windows.

#include <stdio.h>
#include <time.h>         //this is header file for time
#include <windows.h>

COORD coord = {0, 0};
void gotoxy (int x, int y)
{
    coord.X = x;
    coord.Y = y; // X and Y coordinates
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

int main()
{

    long i = 0;                      /* Loop counter              */
    clock_t now = 0;                 /* Holds initial clock time  */
    int interval = 1;                /* Seconds interval for o/p  */
    int elapsed = 0;
    int min=0,MIN=0,hrs=0,sec=0;
    int d=0,f=0;
    now = clock(); /* Get current clock time    */
    
    for(i = 0L ;  ; i++)
    {
        elapsed = (clock()-now)/CLOCKS_PER_SEC;

        if(elapsed>=interval)
        {
            interval += 1;
            if(elapsed%60==0)
            {
                min=elapsed/60;
                d=60*min;
                if(min%60==0)
                {
                    hrs=min/60;
                    f=60*hrs;
                }
            }
            sec=elapsed-d;
            MIN=min-f;
            if(hrs<10)
            {
                gotoxy(2,4);
                printf("0%d",hrs);
            }
            else
            {
                gotoxy(2,4);
                printf(":%d",hrs);
            }
            if(min<10)
            {
                gotoxy(4,4);
                printf(":0%d",MIN);
            }
            else
            {
                gotoxy(4,4);
                printf(":%2d",MIN);
            }

            if(sec<10)
            {
                gotoxy(7,4);
                printf(":0%d",sec);
            }
            else
            {
                gotoxy(7,4);
                printf(":%2d",sec);
            }
            gotoxy(7,7);
            printf("%dhrs:%dmin:%dsec",hrs,MIN,sec);
        }
    }

    return 0;
}

4 comments:

  1. great job dude..keep it up...thanks

    ReplyDelete
  2. A superb content on digital source code. Through digital time zone clocks we are able to recognize the time of different zones at a time.

    ReplyDelete
  3. How to stop the stopwatch????

    ReplyDelete