RAYMOND WILLCOX wrote: > I am new to PIC and have a limited understanding > of timing loops. > I have toiled over several PIC books and Microchip > Docs to find a simple explaination for timing > loops(to no avail). If you have a simple format or > "rule of thumb" technique for determining machine > cycles and code length please send it to me. (-- SNIP --) > movlw .10 > movwf loopx > movlw .10 > movwf loopy > movlw .10 > movwf loopz >Dlay > decfsz loopz,f ?? X+(X*LOOPZ)?? > goto Dlay ?? X+(X*Y*LOOPY.....?? > decfsz loopy,f etc...^ > goto Dlay / \ > decfsz loopx,f / | \ > goto Dlay | > return /*This is the part I don't understand*/ > /* How do derive this part?? */ Count the instruction cycles (1/4 of the oscillator frequency). It is very easy to compute the timing for PIC code because every instruction takes exactly one instruction cycle except for instructions which write to the program counter (which take two cycles). Any 'skip' instruction takes one cycle for the 'skip' instruction itself and, if the following instruction is skipped, you need to count one cycle as if a 'NOP' had been substituted for the instruction that was skipped. I find it easiest to keep track of timing if I place comments after each line indicating the number of CPU cycles that have elapsed up to the start of that instruction ... i.e.: Dlay decfsz loopz,f ;(0 + 3*(loopz-1)) goto Dlay ;(1 + 3*(loopz-1)) ;(2 + 3*(loopz-1)) This loop takes 3 cycles per non-final iteration because the 'decfsz' takes one cycle and the 'goto' takes 2 cycles. The final iteration only takes 2 cycles because the 'goto' is skipped and a NOP is executed in its place. If the loop were followed up with a NOP to burn up one more cycle, the total timing would simply be 3*loopz. I hope this helps. It would take me awhile to calculate the timing for your complete example (and thus I will have to leave it as "an excersize for the reader") but it can be done by simply adding up the clock cycles for each nested loop and multipying by the number of iterations. The following sumarizes what you need to keep in mind to calculate timing for PIC code: 1). CPU cycle is 1/4 of oscillator frequency 2). Most instructions execute in one CPU cycle 3). The only instructions that take 2 cycles to execute are the ones that write to the program counter (GOTO, RETURN, RETLW, RETFIE, and any instruction that writes to PCL) 4). The instruction following a conditional skip instruction should be treated as a NOP (1 CPU cycle) for timing purposes if it is skipped. The conditional skip instruction itself simply takes one CPU cycle. Thus a BTFSC followed by a BSF will always take 2 cycles to execute regardless of whether the conditional was true or false. A BTFSC followed by a GOTO, however, will take 3 cycles to execute if the GOTO is not skipped but only 2 cycles if the GOTO is skipped. Ken