delay()

Adding a delay between commands is key in a lot of programs. Replicating the delay() command on an AVR is slightly more complex because it’s not included as part of the standard commands and instead a library is needed.

Before we import the library we need to define the CPU clock speed. This because the delay is calculated from the number of clock cycles passed. For the Xplained board the clock frequency is 16 MHz and so a value of 16,000,000 is used. It is important to create the define before the library is imported. To create a reference to the clock speed the following code can be used:

#define F_CPU 16000000

Next the library can be imported with the following code:

#include <util/delay.h>

Now that the relevant packages are included in the program the delay command can be used:

_delay_ms()

Wherever this function is called the program will pause for the specified number of milliseconds. To create a delay for 250 milliseconds the following command can be used.

_delay_ms(250);

 Example

Now that we know how to implement a delay we can recreate the infamous ‘Blink’ sketch on an AVR. In a new file start by setting the pin mode to output and then in the while loop we can recreate the blink sketch.

while (1) {
  PORTB |= (1<<PORTB5);
  _delay_ms(1000);
  PORTB &= ~(1<<PORTB5);
  _delay_ms(1000);
}