Society of Robots - Robot Forum

Software => Software => Topic started by: johncban on June 14, 2009, 08:36:35 PM

Title: AVR Studio 4 and Compiler optimization
Post by: johncban on June 14, 2009, 08:36:35 PM
I recently discovered the mystery why I can't have the delay_ms function work is because my compiler optimization is on and I should turn it off; however, I encounter error messages after building the whole code... What should I do, I really need the delay_ms function at the same time avoiding compromise in the other code...
Title: Re: AVR Studio 4 and Compiler optimization
Post by: sonictj on June 15, 2009, 09:12:48 AM
The likely reason that the delay function probably does not work with optimization is that whatever variable is keeping track of the milliseconds was not declared volatile.  The volatile statement tells the compiler that the variable is constantly changing.  Check the delay function and see if it resembles this.


Code: [Select]
unsigned long time = 0;

delay_ms(unsigned long delay)
{
  time = 0;
  while (time<delay)
  {}
}

The fix to this would be to declare time as "volatile unsigned long time = 0; ".  This is the most likely issue.
Title: Re: AVR Studio 4 and Compiler optimization
Post by: Webbot on June 15, 2009, 10:58:12 AM
Its probably coz your variable used for the delay is not declared as volatile - so the optimiser realises that your code is doing nothing other than wasting time so it gets rid of it (ie it optimises it).
So in the delay loop - there will be a variable that is counted down - add the keyword 'volatile'  to this variable.

See my tutorial http://www.societyofrobots.com/member_tutorials/node/207 (http://www.societyofrobots.com/member_tutorials/node/207)