Home > Atmel AVR > Simple Delay/Pause on AVR using delay.h

Simple Delay/Pause on AVR using delay.h

How to implement a simple delay on an AVR
By 09/11/10 [Last Edited by Joseph 10/01/11]
BOOKMARK
LOGIN
REGISTER
I've seen a few google search queries that are pointing to this site about how to create a 'software delay on the avr'. I thought I would briefly explain how to do this in C.

First of all, at the top of your code, add the following:

#define F_CPU 3680000UL 
#include <util/delay.h> 

Change the value of F_CPU depending on what speed your AVR is running at. In this case, my AVR is running at 3.68Mhz. If your AVR is sitting on an STK500 development board, and you haven't adjusted any of the defaults, it's likely it is running at 3.68Mhz. The next line of code includes the delay library.

You can now use the following two functions to create delays:

_delay_ms(1000); 
_delay_us(50);

The first line delays for 1000 milliseconds (1 second), and the second delays for 50 microseconds.

Note: The data types are as follows:

_delay_ms(double delay); 
_delay_us(double delay);

Both take double precision data type as the parameter. You don't need to worry about this if you are hard coding a number into it, e.g. _delay_ms(1000); but if you are passing a variable into it, you need to ensure it is double precision. Either the variable can be dimensioned as a double, or another numeric data type can be casted to a double. Example:

double number = 5; 
_delay_ms(number); 


unsigned char number = 5; 
_delay_ms((double)number);

I hope this makes things a bit clearer.