More efficient alternative to this code snippet?

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi guys. I'm looking for a way to have a variable delay within a while loop that takes up a small amount of code. The example below compiles to 760 bytes of flash. If the delay is changed to a constant amount, the code is about 226 bytes. Obviously I'm not going to use this exact code in a real application, but it illustrates the point. Anyway, I will be greatful to hear any alternative ways to achieve this affect that creates smaller code size. BTW I have looked at the list file output, but I'm not good enough to really make heads or tails of it. Thanks for any suggestions!

int main(void)
{

	int d = 0;
	while(1)
	{
		d++;
		_delay_ms(d);
	}
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The _delay_ms command is a relatively new addition to the lib C library. It is designed for constant delay values, because the calculations are done with inefficient floats - the theory being is that the compiler will optimise the calculations away with a constant value on build. To do a variable delay, you'd be better off using _delay_ms(1) and then looping that the required amount of time (or do your own calculations with the cycle delay routines) but keep in mind of the cycle overhead of the loop - the longer the loop the worse the accuracy, but this shouldn't be noticable for loops that end in this millenium (1000 loops - 1sec - would have an overhead of somthing like 1000 cycles or so).

- Dean :twisted:

Make Atmel Studio better with my free extensions. Open source and feedback welcome!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Good thinking Dean. My real project (not the code above) went from 1246 bytes to 752 bytes using this. Very good solution..

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I use my own function for milliseconds delay

void ms_delay(uint16_t delay_time)
{
	while(delay_time-- != 0)
	_delay_loop_2(4000);
};

All you have to do is to incude avr/delay.h and adjust the value in _delay_loop_2 for your clock speed. You can calculate it like this 1ms/(4*clock_period). 4000 works for a 16MHz clock.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Of course, the generic solution is to use the timer hardware.

Jörg Wunsch

Please don't send me PMs, use email if you want to approach me personally.