This is an old revision of the document!


Delays

Simple delay

Check optimization: -O0 and frequency settings in AVRStudio: 14745600

void delay1s(int count){ // ~0,09s
	unsigned int i,j;
	for(i=0;i<count;i++){
	for(j=0;j<65530;j++){asm volatile ("nop");}}
}
 
 
//call
delay1s(10); // ~0,9 sec.

Delay with timer

Next example is not influenced by optimization.

// Delay in milliseconds
// Delay is created by timer 0
// Max delay 4500 ms
// Precision 3%
 
void aeg(unsigned int t)
{
  // Limiting max delay time
  if (t > 4500) t = 4500;
 
  // Prescaler 1024
  TCCR1B = _BV(CS12) | _BV(CS10);
 
  // Timer set up
  TCNT1 = 0xFFFF - (unsigned int)((unsigned long)t * (unsigned long)144 / (unsigned long)10);
 
  // Endless loop until timer bit is set
  while ((TIFR & _BV(TOV1)) == 0)
  {
  	asm volatile ("nop");
  }
 
  // clearing interrup bit (=1)
  TIFR |= _BV(TOV1);
}

Delay using util/delay.h header file

The problem is max value the delay functions accept. Max delay: 262.14 ms / F_CPU in MHz. Following example allows us to use much bigger values.

void delay_ms(uint16_t ms) // Set's delay duration
{
	while (ms)    // until the vaule reaches zero
	{
		_delay_ms(1); // 1ms delay
		ms--;  // decreases value
	}
}
en/examples/delay.1238583676.txt.gz · Last modified: 2020/07/20 09:00 (external edit)
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0