You are on page 1of 2

An easy timer in C language http://dev.emcelettronica.


Your Electronics Open Source

Home > Blog > arag61's blog > Content

An easy timer in C language

By arag61
Created 15/03/2008 - 10:48


A good exercise for a beginner is to implement a module that pretends a timer.

To do this we have used the following functions that already exist in C library:

delay() – suspends execution for interval [ milliseconds ] ( defined in DOS.H )

kbhit() – checks for currently available keystrokes ( defined in CONIO.H )
printf() - outputs a formattes message to video. (STDIO.H)
clrscr() – clears text mode window ( defined in CONIO.H )

Below there is the module code :

#include <stdio.h>
#include <dos.h>
#include <conio.h>
void timer(float cycle)
float count=0.0;
int goLoop=1;

// Keypressed, exit
if(count> cycle)
// Time expired, exit
printf(“ The timer is %06.1f seconds\n”, cycle);
} // end for
} // end module

As we can see there is one “while” loop using the (blocking) library function delay(), (e.g. delay(1000) = 1second ;
delay(10) = 0,01 second), we here use a 1 tenth of second delay (delay(100)).
For each loop the variable count is increment by 1 tenth then an end of interval control is done (if(count> cycle)).
We used as well function kbhit() to stop the timer on demand ( with just a keypress).
Variable “cycle” is obviously a float type to get a 1 tenth of second resolution.
Morover timer value is output to video using printf with a format specifier %06,1f (e.g. 0014.5).

To use this timer every time we want, we have to :

Create an header file where the TIMER prototype must be declared.
Include this header file in the main program.
In the main program code we must call this module using the same type variable ( float in this case ).
Compile this module and see if any errors occur.

A possible header file code could be :

#ifndef __TIMER_H__
#define __TIMER_H__

1 di 2 23/04/2008 12.13
An easy timer in C language

void timer(float cycle);


In the main program #include “timer.h” must be included among the other header files and the module could be called
with the following instruction : timer (x); where x has been declared as float type.


Source URL:

2 di 2 23/04/2008 12.13