Continue to Site

Welcome to

Welcome to our site! is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How to make a delay 1 sec in C?

Not open for further replies.


Junior Member level 1
Apr 22, 2010
Reaction score
Trophy points
Activity points
I use ATmega32 and i need to make delay 1 sec exactly. I used
_delay_ms (1000);
; however, none of them is accurate, so do I misunderstand those functions?

How much innacurate ?
Take in mind that precision is highlly dependent on hardware ( crystal ).


Have you defined the correct clock speed for your project?
The delay of _delay_ms() is based on the defined clock frequency and of course on the accuracy of the clock source.
Also note that any interrupt during the delay will pause the delay routine until the interrupt is executed and then the delay will resume.

The _delay_loop_2 function can't give you 1 sec delay unless you have a very low cpu clock frequency which I doubt
avr-libc: <util/delay_basic.h>: Basic busy-wait delay loops

you call it with the number of iterations up to 65536, the loop executes four CPU cycles per iteration so depending on the clock you can delay up to 65536*4 clock cycles

...Also note that any interrupt during the delay will pause the delay routine until the interrupt is executed and then the delay will resume...

I never attempted to that point.
Really, it is a potential candidate to be the reason of the problem.


It would help a lot if you posted your code here. Then, we could see if there are other mistakes or the more common mistakes as have been already stated above. Which compiler are you using? I'm guessing you're using avr-gcc (WinAVR IDE).

yes interrupt may be the problem, check if you are using any interrupt.
and if the delay going shorter than programmed then it may not be the interrupt.

In fact I am using avr-gcc compiler this is the code

#include <avr/io.h>
#include <avr/delay.h>

int main(void)
for(int i=0;i<8;i++)
_delay_loop_2(30000); //30 seconds delay

Did you read post #3?

_delay_loop_2(30000) is not a delay in ms, it executes 30000 iterations taking four CPU cycles each so the delay is 30000*4= 120000 * (1/clock) where clock is in Hz
for example with 8000000Hz clock the delay is 120000 * 0.000000125 = 0.015 which is 15ms

Use _delay_ms(1000) instead but define your clock frequency first in the project properties (you enter the frequency in Hz)


You can define the clock frequency by adding this to the first line:
#define F_CPU 8000000 //This currently is set for 8MHz

And use _delay_ms as stated above.

Hope this helps.

Not open for further replies.

Part and Inventory Search

Welcome to