I am having a problem in calculating delays. I want to make a delay for 1 sec
when I am using 1MHz
clock speed for my atmega128 microcontroller.
I use proteus for simulation and avr studio for coding in assembly for atmel microcontroller.
For example this code is for 8MHz
clock microcontroller
Delay_15mS: ; For CLK(CPU) = 8 MHz
LDI dly1, 120 ; One clock cycle;
Delay1:
LDI dly2, 250 ; One clock cycle
Delay2:
DEC dly2 ; One clock cycle
NOP ; One clock cycle
BRNE Delay2 ; Two clock cycles for true 1 clock for false
DEC dly1 ; One clock Cycle
BRNE Delay1 ; Two clock cycles for true 1 clock for false
RET
Can you teach me how to calculate the time this delay will take? So I could make 1 for 1 sec delay @ 1 MHz
Thank you
It is easier to use timer/counter for this. You can use timer/counter0 with
prescalar=1024
and1MHz
clock for creating250ms
delay. Each250
milliseconds one interrupt will be generated.4
interrupts mean1
second!To calculate a delay, you need to calculate the cycle time and then count how may cycles you need to reach the wanted delay.
In your case,
1MHz
clock means1000000
cycles per second. So1
cycle equals1/1000000
seconds or1us
. To get 1 second delay, you need1000000
cycles of1us
, so it means that you have to create an algorithm of1000000
cycles.Building on your example, a
1
sec delay@ 1MHz
clock would be:In this case there is the internal loop
Delay3
that is4
cycles long becauseDEC=1
,NOP=1
andBRNE=2
when jumping to Delay3. So,4
cycles repeated250
times (the value ofdly3
) are1000
cycles or1000us
=1ms
.Then the loop
Delay2
repeats theDelay3
125
times (the value ofdly2
). So the accumulated delay in this case is125ms
.And finally, the loop
Delay1
repeats theDelay2
8
times (the value ofdly1
). So the accumulated delay in this case is1000ms
or1
second.NOTE: This example delay is actually a little bit longer than
1sec
because I didn't consider the time of the instructions ofDelay2
andDelay1
. The influence is very small, but for a precise1sec
delay, these instructions must be counted and the values ofdly1
,dly2
anddly3
must be adjusted to guarantee that the algorithm is exactly1000000
cycles long.NOTE2: With this algorithm the microcontroller can't do anything else while executing the delay because you are using it to count cycles. If you want to do other things while doing a delay, take a look at timers and interrupts of the microcontroller.