0

Can someone explain how this type of loop works, I took it from a code that has a total delay of 1 second, I didn't understand the LOOP 2 and 3 function.

DELAY:
        MOVLW 0X44
        MOVWF C1
LOOP3:
        MOVLW 0X33
        MOVWF C2
LOOP2:  
        MOVLW 0X44
        MOVWF C3
LOOP1: 
        DECFSZ C3
        GOTO LOOP1
        DECFSZ C2
        GOTO LOOP2
        DECFSZ C1
        GOTO LOOP3
        RETURN
END
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • 3
    What do you need explained? You seem to know these are nested loops. Each loop repeats all the inner loops. In total you get 0x44*0x33*0x44 iterations. Presumably that takes 1 second on your device. – Jester Jul 30 '21 at 23:45
  • 1
    It might help to understand that for [DECFSZ](http://technology.niagarac.on.ca/staff/mboldin/18F_Instruction_Set/DECFSZ.html): *If the result is 0, the next instruction, which is already fetched, is discarded and a NOP is executed instead.* – David Wohlferd Jul 31 '21 at 00:03

1 Answers1

0

Well the assembly language is harder to read by humans. It does not consist of visible hierarchical code structures that we can read easily. But on the other hand the limits of assembly is only the skies of its architecture, I mean it powerful and flexible.

The following C implementation of that loop will help new assembly people to understand how that loop works and give them some aspect. In fact, if you write the C code below and have look at its disassembly, you will see the similar assembly code.

unsigned char C1, C2, C3;

void DELAY(void) {
  // This loop corresponds to LOOP3 label which is outermost loop entry
  for(C1 = 0x44; C1 > 0; C1--){
    // This loop corresponds to LOOP2 label which is the medium loop entry
    for(C2 = 0x33; C2 > 0; C2--) {
      // This loop corresponds to LOOP1 label which is the innermost loop entry
      for(C3 = 0x44; C3 > 0; C3--) {

      }
    }
  }
}

As others said, you will have a 0x44 * 0x33 * 0x44 iterations that is equal to 235,824 iterations unless we don't count for CALL and RETURN instructions.

Kozmotronik
  • 2,080
  • 3
  • 10
  • 25