0

My exercise: •Calculate the maximum delay possible using three loops @ 1 MHz clock frequency. (Answer 49.94 s)

delay:   ldi    r23,$FF          ;Initialise 3rd loop counter 
loop3:   ldi    r24,$FF          ;Initialise 2nd loop counter 
loop2:   ldi    r25,$FF          ;Initialise 1st loop counter 
loop1:   dec         r25              ;Decrement the 1st loop counter 
          brne   loop1            ;and continue to decrement until 1st loop counter = 0 
          dec    r24               ;Decrement the 2nd loop counter 
          brne   loop2            ;If the 2nd loop counter is not equal to zero repeat the 1st loop, else continue 
          dec    r23
          brne   loop3 
      ret                   ;Return

I'm trying to calculate the maximum delay using those 3 loops the answer apparently is 49.94 s and I'm really struggling it was much simpler with 2 nested loops.

Here is what I've tried, but the answer is way off.

33*((255*3)-1) + 17*((33*3)-1) + 11*3

ldi - 1 clock cycle, brne 1 or 2 clock cycles

Architecture: ATmega8535

Cactus
  • 25,576
  • 9
  • 60
  • 130
Higeath
  • 5
  • 3

1 Answers1

2

For starters, the longest loop would load 0 not FF to the counter, but let's stick with FF so we get the expected answer. With FF the loop runs 254 times and exits on the 255th.

The general formula is 1 for ldi, (n-1) * (body + 3) for the full iterations (1 for dec and 2 for brne) and (body + 2) for the final one (1 fordec and 1 for not taken brne). body means whatever is in the loop body, for the innermost loop that's 0 as it's empty.

Thus, for the innermost loop: 1 + 254 * (0 + 3) + (0 + 2) = 765. For the middle loop, the body is the 765 from the innermost loop, thus we have: 1 + 254 * (765 + 3) + (765 + 2) = 195840. For the outermost loop the body is the 195840 from the middle loop, thus we have: 1 + 254 * (195840 + 3) + (195840 + 2) = 49939965 which is the expected answer.

Jester
  • 52,795
  • 4
  • 67
  • 108
  • I'm a little bit confused with the (body +3) now so ldi runs once so 1 then dec and brne runs 254 times so wouldn't it be 2*254 on the final loop brne is 2 so the whole thing would look like 1 + 2*254 + 2 – Higeath Mar 02 '16 at 15:16
  • You swapped the times for the `brne`, it takes 2 clocks when it jumps back, that is in the loop, and 1 clock when it does not jump, that is the last iteration. – Jester Mar 02 '16 at 15:23
  • I got it now thanks :) I don't mean to burden you but could you tell me what would the delay be for e.g. loops r23, $06, r24, $FD, r23, $DD; It's harder to follow with all the same numbers my answer for those ones is 1174836 clock cycles I'm trying to recreate it in Excel so I don't have to calculate it every time – Higeath Mar 02 '16 at 15:38
  • I got `1011006` but might have messed up :) – Jester Mar 02 '16 at 15:44
  • you are right thanks again! I've messed up the order of loops – Higeath Mar 02 '16 at 15:50