Snippet:Delays

From Curuxa

Delays are functions that stop the execution of the program for a given amount of time. During that time, the processor stays in a loop doing nothing useful.

Delays are not recommended, specially in complex programs, because the microcontroller cannot execute other operations while waiting for something. The best option would be using timers with interrupts in the background while we execute other operations.

In the other hand, delays are very common because they are very simple to use.

If you need to execute something periodically, or you need precision, use timers and interrupts, not delays.

If you are building a clock or any other application that needs very precise timing, search for a Real Time Clock integrated circuit, don't use timers either.

Examples using simple loops

The following examples use loops for creating the delays. They are not very precise, but very simple to use, modify and they don't waste any timer. This way, you can use delays and timers for implementing different features in the same program.

Oscillator at 8MHz

The following examples have been setup and tested with 8MHz oscillators. If you are running your application at different speeds, you should adapt and test them.

//Delay the program for 10 microseconds
void Delay10us(){
	__asm
		GOTO $+1
		GOTO $+1
		GOTO $+1
		GOTO $+1
		GOTO $+1
		GOTO $+1
		GOTO $+1
		GOTO $+1
		GOTO $+1
	__endasm;
}
//Delay the program for a given amount of milliseconds
void Delay(unsigned long ms){
	unsigned long i;
	while(ms--){
		for (i=0; i<118; i++) {
			//do nothing
		}
	}
}
//Delay the program for a given amount of seconds
void DelaySec(unsigned long seconds){
	while(seconds--){
		Delay(950);
	}
}
//Delay the program for a given amount of minutes
void DelayMin(unsigned long minutes){
	while(minutes--){
		Delay(55);
	}
}