Electronic – AVR Time Delay without Arduino Libraries

avrc

Trying to figure out how to do something like delay() in Arduino but just for straight AVR code. What's the typical way to do waits and such on AVR chips?

Best Answer

You have a couple options:

1) Use an interrupt. The setup is slightly complicated but frees up your device to do other things while it is waiting. Refer to your AVR datasheet for instructions on how to set an interrupt. For delays greater than the interrupt counter, you can use a pre-scaler or another variable to count interrupts until your desired wait has occurred.

2) Use a NOP in a for loop to perform your wait. According to this page - http://playground.arduino.cc/Main/AVR, a NOP operation takes 1 clock cycle - 1 clock cycle = 1/frequency. At 16MHz a NOP will take 62.5nS to execute. use an unsigned long variable when defining your loop counter so you don't roll over.

Your loop counter will look like this (volatile ensures that the compile will not optimize out the code):

void delay(unsigned long delay) {
  volatile unsigned long i = 0;
  for (i = 0; i < delay; i++) {
      __asm__ __volatile__ ("nop");
  }
}

Edit: There will be some overhead from the for loop. You can determine this experimentally (easy) or by counting the instructions (hard).