Electronic – Is this a correct way to have a 1 second delay

assemblydelayfrequencypic

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:

  1. Clock frequency accuracy. 4 million clock cycles is only exactly 1 second if you have precisely a 4,000,000.00000000000000000000000000 Hz clock.
  2. Interrupts. If an interrupt occurs during your loop the loop will take longer.
  3. Unaccounted for extras. If you're working in C and your delay is in a function you have to take into account such things as the function preamble / postamble, time taken for the call instruction, etc.

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.

  1. Internal timers. These are good for short periods and are far simpler than counting cycles. Set the timer up with an interrupt, sit back, and relax. For longer periods though they do tend to involve triggering the interrupt multiple times and counting up your own variable. One common way is to have a constantly running 1ms timer that is always counting up a millisecond counter. That is then used to time your delays. Not always 100% accurate, but very simple to manage. Timers of course are still dependant on the accuracy of your clock source.
  2. Real-time clocks. For longer periods of a second or longer, where you don't need fine grained accuracy but do you need coarse grained accuracy (i.e., accuracy to the second, not the ┬ÁS, but that accuracy stable over long periods), you can't beat a real time clock module - either internal to the chip or external in a separate chip. The lower frequency clock sources (32768Hz) used in RTC modules tends to make them more accurate (50ppm in 4MHz is 200Hz; 50ppm in 32768Hz is 1.6384Hz).