C2 - Timers
C2 - Timers
C2 - Timers
Objectives
• Upon completion of this chapter, you will be
able to:
– List the timers of the PIC18 and their associated
registers
– Describe the various modes of the PIC18 timers
– Program the PIC18 counters in C as event
counters
Introduction
D7 D0
External Source
Internal Source
EX1
• What is the value of T0CON if the Timer0
settings are as below ?
– 16-bit mode
– No pre-scaler
– Internal clock (from oscillator) source
– Increment on positive-edge.
Answer:
T0CON = 00001000 With 64 prescaller
EX
For TMR0H = B8 and TMR0L = 3E, calculate the time delay
Generated by assume XTAL = 10MHz with no pre-scaler
#include <p18f458.h>
void T0Delay()
{
T0CON = 0x08; //T0, 16-bit , no pre-scale
TMR0H = 0xB8;
TMR0L = 0x3E;
T0CONbits.TMR0ON = 0; //turn on T0
while(INTCONTbits.TMR0IF == 0); //wait for TF0 to roll over
T0CONbits.TMR0ON = 0; //turn off T0
INTCONbits.TMR0IF = 0; //clear TF0
}
EX
• Calculate the amount of time delay
generated by the timer.
• For TMR0H = FF and TMR0L = F2
• Assume that XTAL = 10MHz
Solution:
T = 4/10MHz = 0.4us (Each tick consume 0.4us)
How many tick? (FFFF-FFF2) + 1 = 14 Decimal
Rolls Over( from
ticks)
FFFF to 0
Time delay
1 = 14 x20.4us = 5.6us for half the
13 pulse 14
Solution:
TCY = 4/20MHz = 0.2us (Each tick consume 0.2us)
How many ticks in 50ms delay?
50ms/0.2us = 250000 ticks = 3D090H ticks! (out of range!!)
Solution:
• T = 1/2500 = 400us (HIGH: 200us; LOW: 200us)
• How many ticks in 200us delay?
– 200us/0.2us = 1000 ticks = 03E8H ticks!
• Therefore, register counts = - 03E8H = FC18H
Approx.1000 ins. cycles
#include <p18f458.h>
void main(void)
{
TRISCbits.TRISA4=1; //make RA4 an input for T0CK1
TRISB = 0x0;
TRISD = 0x0;
T0CON = 0x25; //T0,16-bit, prescale 1:64
TMR0H = 0x0; //set cnt = 0
TMR0L = 0x0; //set cnt = 0
while(1)
{
do
{
T0CONbits.TMR0ON = 1; // turn on T0
PORTD = TMR0H;
PORTB = TMR0L;
}
while(INTCONTbits.TMR0IF == 0); //wait for roll over
T0CONbits.TMR0ON = 0; // turn off T0
INTCONbits.TMR0IF = 0; // clear TF0
}
}
Timer2
• 8-bit wide
• Consists of a PR2 (Period Register 2)
• TMR2 will increment from 00 until reaches PR2
value before TMR2IF flag is set
• Consists of prescaler and postscaler
• No counter function, coz no external clock
source.
Important Registers:
i) T2CON (Timer2 Control Register)
• To start & stop Timer2 and other configurations
ii) PR2 (to set the counting value)
• If TMR2 = PR2; TMR2IF flag is set