Working of a timer in pic microcontroller


I am new completely new to microcontrollers and right now I am working in a project that requires 1 mS timing delays. In my project, I use a pic16f877a microcontroller. I am unable to understand the timer concept in general. In some tutorial, I have read that the timer depends on CPU clock but independent on ALU. Can anybody explain to me how a timer is linked to clock frequency and independent from the CPU?

Thanks in advance.

The CPU and the timer are entirely independent block. They both operate independently but both depend on the same clock frequency for operations. Although, the internal bus connects both timer and CPU, which enables the CPU to access the internal registers of a timer. See the image,


Thanks for the replay. But how exactly does a timer operrates from the generated clock signals? How the timing of the generated clock signals affect the timekeeping of a timer?

You have to understand that the timer is a separate block from the CPU. Both depend on the same clock source but operates independently. Imagine you have a (Fosc) 4 Mhz oscillator which generates the clock signal. The pic microcontrollers need 4 clock cycles to execute one instruction i.e the instruction executes at,

Fcyc = 4Mhz/4 = 1 Mhz

which is 1000000 instruction/sec. From this we can find the time required to execute one instruction (Time period)

Tcyc = 1/Fcyc = 1/1 Mhz = 1 uSec

i.e if enabled, the timer also ticks every 1 uSec ( 1 tick = Tcyc = 1uSec ).

The Timer1 module in pic16f877a has the following features:

  • 16-bit timer/counter
  • Readable and writable
  • 8-bit software programmable prescaler
  • Internal or external clock select
  • Interrupt on overflow from FFh to 00h
  • rising or falling edge selection for external clock

The timer1 has a 16 bit TMR1 register which takes in values from 0 to 65535. This register gets incremented on every tick. In our previous case, in order to generate a 1 mSec delay we need 1000 ticks.
So we have to set value 65535 - 1000 = 64535 in the TMR1 register. The register gets incremented every 1uSec and when it reaches 65535 the timer overflows and hence enables the TMRIF interrupt register. At this point, we have successfully completed the 1 mSec delay.

In this case, the CPU can be used to continuously check the TMRIF register, to see if the 1 mSec is completed.


Well explained. You deserve an applause :clap:

Thank you so much @Mr.Tesla. Brilliantly explained.

Refer Useful guides on Timers in PIC microcontrollers working codes example : Timers in PIC Microcontrollers