Tuesday, January 13, 2015

PIC microcontroller timer0 module

PIC16F877A Microcontroller Timer0 module
Some times we need to do some thing that depends on time, for example the delay command. For example we have to make an led blinks at some frequency and we cannot hold the microcontroller using delay. In this topic we will make an led blinks without using delay command for pic16f877a, we are going to see the different timer modules of this PIC chip and how to initiate these modules.
The PIC16F877A has 3 different timers: Timer0, Timer1, and Timer2.
Timer0: The Timer0 module timer/counter has the following
features:
  • 8-bit timer/counter
  • Readable and writable
  • 8-bit software programmable prescaler
  • Internal or external clock select
  • Interrupt on overflow from FFh to 00h
  • Edge select for external clock
8-bit timer means that the maximum value is 255.
Prescaler means frequency divider of the overall system.
We can choose the clock of timer, internal or external clock. The external clock is connected to pin6 (RA4).
REGISTERS ASSOCIATED WITH TIMER0:
There are tow registers associated with timer0, the first one is OPTION_REG register, and the second is INTCON register.
The following picture describes the option_reg register:



 And the next picture shown the INTCON register:



 Timer0 calculator:
We can easily calculate the frequency of timer0 interrupt using the following equation:

Timer0_freq = MCU_freq / {4 * Prescaler * (256 - TMR0)}

Maximum time for timer0 to interrupt can be found by putting prescaler 1:256 and TMR0 = 0, and assume our mcu frequency is 12MHz, so timer0_freq = 45.7763 Hz so time = 21.8453 ms.
Timer0 Example:
Let's make a delay of 1 second for 12MHz pic16f877a. First this delay is large than the max time of the mcu, so we have to make our timer0 interrupt about 45 times to reach 1 s.
Circuit and MikroC code:




unsigned char i;
 void interrupt(){
 i++;
 if(i>45){
 i=0;
 PORTB.F1 = ~PORTB.F1;
 }
  TMR0 = 0;                      // initial value of TMRO
  INTCON.F2 = 0;                 // reset T0IF (flag bit)
}
 void main() {
 OPTION_REG = 0x07;          // Set timer TMR0 to 1:256 prescaler
 TMR0 = 0;                   //Preload timer = 256 - 12/(4*256*Hz)
 INTCON = 0xA0;              //Enabe internal interrupt
 TRISB.F1 = 0;              //Configure PORTB.F1 as output
 PORTB.F1 = 0;              //Initial value of PORTB.F1
  while(1) ;                //Endless loop
  }



Next:
 PIC16F877A Microcontroller Timer1 Module
PIC16F877A Microcontroller Timer2 Module

Most of these informations are from PIC16F877A datasheet.