If I have a PIC24 with a 4 MHz frequency. Is it accurate to have a 1 second delay by having 4 million clock cycles?
I made a 1 second delay like this on my PIC24FJ128GA010:
MOV #244, W3
DL: REPEAT #16383
NOP
DEC W3, W3
BRA NZ, DL
REPEAT #1566
NOP
RETURN
Clearly if you calculated the cycles right you will get 3999995 cycles plus 3 for RETURN and 2 for CALL = 4000000 cycles. Can this be exact ? On a LED blink example with a comparison with a real clock, I can see (almost) a very very minor difference between them.
What factors can affect this accuracy ?
P.S: I used many delay techniques, the __delay_ms function in the XC16 C compiler, the timer interrupt in both assembly and C, and the RTCC module for accurate timing. I'm asking this just for practice and learning.
Best Answer
Repeat loops are only really any good for "rough" timing and for short periods. There are many factors that can effect just how long your loop takes:
Basically instruction cycle / clock cycle counting is a right pain in the rectum and not something you want to do very often.
The PIC, and most other microcontrollers, have better mechanisms.