C - How to create delay function according to program need?

By: IncludeHelp, on 22 JAN 2017

Simple way to create delay function by running a loop certain time, let suppose while (1) is running 333333333 times in a second.

Based on this count we can create our own delay function, Here is the function

void delay(int seconds){
	unsigned long int count=333333333,i,j;
	
	for(i=0;i<seconds;i++)
	    for(j=0;j<count;j++);
}

Consider the following program, which is printing text with current time after 1 and then 2 seconds delay:

#include <stdio.h>
#include <time.h>

//time related//////////
time_t rawtime;
struct tm * timeinfo;
////////////////////////
	
void delay(int seconds){
	unsigned long int count=333333333,i,j;
	
	for(i=0;i<seconds;i++)
	    for(j=0;j<count;j++);
}

void printTime(void){	
	time ( &rawtime );
	timeinfo = localtime ( &rawtime );
	printf ( "Current local time and date: %s\n", asctime (timeinfo) );		
}

int main()
{    
	printf("Text1\n");
	printTime();    
	delay(1);	//delay for 1 second

	printf("Text2\n");
	printTime();    
	delay(2);	//delay for 2 seconds

	printTime();
	printf("Text3\n");
	return 0;
}

Output

    Text1 
    Current local time and date: Sun Jan 22 20:41:12 2017 

    Text2 
    Current local time and date: Sun Jan 22 20:41:13 2017 

    Current local time and date: Sun Jan 22 20:41:15 2017 

    Text3 



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.