Example 9-29 on page 364 shows code with timer 0 and XTAL = 10 M Hz that toggles
ID: 3552651 • Letter: E
Question
Example 9-29 on page 364 shows code with timer 0 and XTAL = 10 M Hz that toggles PORTB.4 bit continuously every 50 ms.
Trythis code with three other timers: timer 1, timer 2, and timer 3. Show what the best you can have (say do you get exactly 50 ms or you get 49.5 ms, 50.2 ms, or you get ?s (microseconds) at the best)? Showthe code change you need to have for each of these timers (which lines must be added, deleted, or modified?).
void T0Delay()
{
T0CON=0x01;
TMR0H=0x85;
TMR0L=0xEE;
T0CONbits.TMR0ON=1;
while(INTCONbits.TMR0IF==0);
T0CONbits.TMR0ON=0;
INTCONbits.TMR0IF=0;
}
Explanation / Answer
For timer1
T1CON = 0xA0; //so that prescaler is 4 and clock is Fosc/4 and 16 bit timer
TMR1H = 0x85; //same as prescaler and clock are not changed
TMR1L = 0xEE; //same
T1CONbits.TMR1ON = 1;
while(INTCONbits.TMR1IF==0);
T1CONbits.TMR1ON = 0;
INTCONbits.TMR1IF= 0;
this will generate a delay of (0xFFFF-0x85EE+1)*4(prescaler)*400ns(1/(Fosc/4)) = 50ms
For timer2:
8 bit timer with 1,4,16 prescaler and 1-16 postscaler
using 16 post and 16 pre scalers we get a delay of 16*16*400ns = 102400ns = 102.4us for 1 count
So for 50ms we need a to count 488.28 times. This is not possible in a 8 bit timer(maximum of 255)
to achieve 50ms delay we split it into two and manage in the code for 50 ms.
for 25ms we need 244 counts which gives -> 24.985ms
the following code will generate 50 ms delay( approx 49.971ms)
T2CON = 0x7B; //so that prescaler is 16 and post scaler is 16
PR2 = 244;//match value
TMR2L = 0;//start from 0
T2CONbits.TMR2ON = 1;
while(INTCONbits.TMR2IF==0);
TMR2L = 0;//restart after 25ms
while(INTCONbits.TMR2IF==0);
INTCONbits.TMR1IF= 0;
T2CONbits.TMR2ON = 0; // end after 50 ms delay
for timer3:
same as timer0
T3CON = 0x20; //so that prescaler is 4 and clock is Fosc/4
TMR3H = 0x85; //same as prescaler and clock are not changed
TMR3L = 0xEE; //same
T3CONbits.TMR3ON = 1;
while(INTCONbits.TMR3IF==0);
T3CONbits.TMR3ON = 0;
INTCONbits.TMR3IF= 0;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.