Page 1 of 1

C for AVR Ex 1.4 Delay Routine

Posted: Tue Jul 22, 2014 10:41 am
by ChrisBTW
I am trying to get the following code to work from the C for AVRs MATRIX course.

/* Ex 1.4 Flash one LED with delay */
/* (c) Rob Miles August 2005 */

#include <AVR\io.h>

void main(void)
{
unsigned int i;

DDRD=0x01;

while (1)
{
PORTD = 0x01;
for (i=0; i<65000; i=i+1);
PORTD = 0x00;
for (i=0; i<65000; i=i+1) ;
}
}

The 'for' delay lines do not create a delay. I have tried reducing this number and nothing seems to happen. Looking at pin 14 (PD0) the signal is not stable. This type of delay is used many time in exercises following this one so I would like to understand why it does not appear to work. The same code has been compiled for a PIC and works fine.

The hardware is the AVR EB019-00-2 ATMEL Board with the EB-004-00-2 LED on Port D. The processor is a ATMEGA324P running on internal clock 8Mhz.

Can anyone suggest a way forward?

Many thanks,
Chris

Re: C for AVR Ex 1.4 Delay Routine

Posted: Tue Jul 22, 2014 11:06 am
by Benj
Hi Chris,

Very strange it's not working. Here is something you can try.

Code: Select all

for (i=0; i<65000; i=i+1)
{
asm("NOP");
}

Re: C for AVR Ex 1.4 Delay Routine

Posted: Tue Jul 22, 2014 11:38 am
by ChrisBTW
Many thanks, I have tried this and to be honest the signal is more stable now but still not what I would expect. The signal on pin 14 does not appear to change with any number in the 'for' line.

Sorry I can't figure out how to post images form the OSC?

for (i=0; i<100; i=i+1); results in a signal around 5us

for (i=0; i<1000; i=i+1); results in the same signal, no change?

I cannot get the line of code to change the delay signal in any way?

:(

Re: C for AVR Ex 1.4 Delay Routine

Posted: Tue Jul 22, 2014 12:30 pm
by ChrisBTW
Here is an attachment jpg of the OSC image for pin 14.

Chris

Re: C for AVR Ex 1.4 Delay Routine

Posted: Tue Jul 22, 2014 1:20 pm
by ChrisBTW
Hi, OK I have figured out what it was.

Code: Select all

for (i=0; i<65000; i=i+1) 
		{
			asm("NOP");
		}    
I had the semi colon on the end of the for loop.

Just need to figure out why "NOP", fixes this delay code?

Many thanks,
Chris

Re: C for AVR Ex 1.4 Delay Routine

Posted: Tue Jul 22, 2014 4:32 pm
by SteveM
Looks like the compiler is trying to be "helpful" - i.e. it sees that the loop is empty, so "optimises" for greater speed and less memory usage by ignoring the code. Adding the assembly effectively tells the compiler that the loop is empty on purpose, and prevents the optimisation.

If you were writing C-code for a multi-threaded PC application, the optimisation would make sense, as this kind of timing loop would hardly ever be used (RTC, or making a thread 'sleep' would typically be used) - but it's most definitely not "helpful" in an embedded application like this!