Program Timing
Microcontroller (MCU) program execution is driven by a clock signal generated by an internal oscillator, which may be controlled by an external RC circuit or crystal. This signal is divided into four internal clock phases (Q1eQ4) that run at a quarter of the oscillator frequency (Fosc/4). These
provide four separate pulses during each instruction cycle, which trigger the processor operations. These include fetching the instruction code from the program memory and copying it to the instruction register. The instruction code is then used by the decoder to set up the control lines to carry out the required process. The four clock phases are used to operate the data gates and latches within the MCU in sequence to complete the data movement and processing (see Microchip’s ‘PIC Mid-Range MCU Family Reference Manual’ and Appendix C).
The instruction timing is illustrated in Figure 6.2. Most instructions are executed within these four clock cycles, unless a jump (GOTO or CALL) occurs. These will take eight clock cycles, because the program counter contents have to be replaced, taking an extra instruction cycle. The PIC® chip operates a simple pipelining scheme which overlaps the fetch cycle of one instruction with the execution cycle of the previous one, doubling the speed in linear sequences at the expense of a delay of one instruction cycle when branching. An output instruction clock signal at Fosc/4 is available at the CLKOUT pin to operate external circuits synchronously; it can also be used in hardware testing to check that the clock is running, and to monitor its frequency.
If the clock rate is known, the execution time for a section of code can be predicted. A frequency of 4 MHz, using a crystal oscillator, is a convenient value as it gives an instruction cycle time of 1 ms. This is also the default frequency of the 8 MHz internal oscillator. The NOP (No OPeration) is useful here to adjust the sequence execution time; it can be used to insert a delay of one instruction cycle, that is, four clock cycles.
This point is illustrated in the simulation of program BIN5, Figure 6.2, which is a modification of BIN4 designed to give a binary count output with an output period of exactly 2 ms (500 Hz) at the LSB. A delay of 1 ms overall can be created using a counting loop set to 247 and a NOP in the loop to make the loop execution time 4 ms. The total loop time is then 247 x 4 ¼ 988 ms plus 12 cycles for the loop control, giving a total of exactly 1000 ms. This is displayed on the stopwatch by setting a breakpoint at the start of the loop, and zeroing the stopwatch before running.