An Easy Timer In C Language

2

Click here to load reader

Transcript of An Easy Timer In C Language

Page 1: An Easy Timer In C Language

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

1 di 2 23/04/2008 12.13

Your Electronics Open Source(http://dev.emcelettronica.com)

Home > Blog > arag61's blog > Content

An easy timer in C languageBy arag61Created 15/03/2008 - 10:48

BLOG

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;

while(goLoop)

{

if(kbhit())

{

// Keypressed, exit

goLoop=0;

}else{

delay(100);

count+=0.1;

if(count> cycle)

{

// Time expired, exit

goLoop=0;

}

}

clrscr();

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__

Page 2: An Easy Timer In C Language

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

2 di 2 23/04/2008 12.13

void timer(float cycle);

#endif

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

Trademarks

Source URL: http://dev.emcelettronica.com/easy-timer-c-language