SparkFun Forums 

Where electronics enthusiasts find answers.

Your source for all things Atmel.
By dmcole
#62084
Thanks for your tutorials (or lectures) on the AVR products. I've been fiddling with an ATMega8 and your guides and been having a fun time.

I have been using AVRDude as is installed by MacPack and it too has a blinking LED routine. That routine uses a function called _delay_ms() as opposed to your delay_ms(). That function is included from a file called util/delay.h .

I have tried both your delay function and the delay.h function and, interestingly, they are apparently 10 times different. For example, with the default 8MHz internal oscillator running on the Mega8, this:
Code: Select all
_delay_ms(5);
blinks just as fast as this:
Code: Select all
delay_ms(50);
Neither appear to be related to the half-second I would be expecting (it seems to be about one second on, one second off).

I'm just curious and have two questions:

*Why is there a difference between the two functions? Which one is more accurate?

*Why are neither close to the half-second that they should be? Is it an oscillator issue? A fuse issue in setting up the Mega8?

Thanks for this wonderful playground.

\dmc
User avatar
By leon_heller
#62085
They might be intended for different oscillator frequencies, or the code might be wrong. Use a crystal and a timer if you need accurate delays.

Leon
By n1ist
#62094
util/delay.h uses the F_CPU define to determine CPU speed. This can be set in your makefile (preferred) or by #define F_CPU 8000000 before #including delay.h

I am not sure where delay_ms() is defined and how it sets the CPU frequency, but there's probably a #define somewhere else that has one too few 0's in it.

_delay_ms() works by running loops of a known length. It may be off if the processor is busy handling interrupts. It also depends on specific compiler optimizer settings and the delay amount being a compile-time constant. I'm not sure if that's good enough for DMX...

If you want a more accurate delay, you will need to use a hardware timer.

/mike
By signal7
#62110
I'm not directly familiar with these functions, but I would expect ms to mean milliseconds. So 50mS would be 1/10th of one half of a second. If delay_ms(50) is delaying half a second, it would be off by a factor of 10, imho.
By stevech
#62162
one milisecond (mSec) = 0.001 second.
50 mSec = 0.050 second
500 mSec = 0.5 second

1000 msec = 1.0 second
By koolatron
#63381
_delay_ms() and delay_ms() also have maximum allowable delays, based on the constraints of the loops used to build them. I'm pretty certain this is explained in delay.h, but it's in the neighborhood of 100ms.

--edit--

aha, it is explained in delay.h. _delay_ms() is a reduced-resolution version of delay_ms() that allows longer delays, up to about 6.5 seconds. You're limited to short (<100ms) delays with vanilla delay_ms().