1. Consider a C program toggles only the PORTB.4 bit continuously every 50 ms. I
ID: 1846433 • Letter: 1
Question
1. Consider a C program toggles only the PORTB.4 bit continuously every 50 ms. It uses Timer 0 16-bit mode; the 1:4 prescaler to create the delay and assume XTAL = 10MHz. This is the example you have had in both exercise 3 and exercise 4 already.
A. #include <p18f4580.h>
1. void T0Delay(void);
2. #define mybit PORTBbits.RB4
3. void main(void)
4. {
5. TRISBbits.TRISB4=0;
6. while(1)
7. {
8. mybit^=1;
9. T0Delay();
10. }
11. }
12.void T0Delay()
13. {
14. T0CON=0x01;
15. TMR0H=0x85;
16. TMR0L=0xEE;
17. T0CONbits.TMR0ON=1;
18. while(INTCONbits.TMR0IF==0);
19. T0CONbits.TMR0ON=0;
20. INTCONbits.TMR0IF=0;
21. }
(a) Explain what the while (1) loop in line 6 of the code does.
(b) Explain what the while(INTCONbits.TMR0IF==0); loop in line 18 does.
(c) In what situation will line 19 be executed? Is it possible that line 19 never gets executed with the current code? Explain!
(d) How long (in seconds) does line 18 run? Show the calculation.
(e) What does line 8 do? Explain!
(f) How many times is PORTB.4 bit flipped (toggled) every second? In other words, how often does PORTB.4 change from 0 to 1 or from 1 to 0 in every second? Show the calculation.
(g) Think of PORTB.4 as a square wave (switching between 0 and 1). What is the frequency of this square wave? Show the calculation.
Explanation / Answer
(a) while (1) creates a infinite loop where mybit is toggled between 1 and 0 after the delay
(b) this lines makes the program wait until value in timer0 reaches maximum and rolls over.
(c) when the the value in timer0 register reaches maximum i.e. 0xffff and rolls to 0x0000. INTCONbits.TMR0IF becomes 1/ at this stage program will leave the while loop in line 18 and line 19 gets executed.
TMRO = (TMR0H <<8)|TMR0L = 0x85EE = 34286 in decimal
highest value of TMR0 =0xfff =65535
TMR0 has to increase 65535-34286 = 31249 times
prescalar setting =1/4
XTAL= 10Mhz
scalled clock =1/4*10 Mhz = 2.5Mhz
now time required for TMR0 to increase 31249 = 31249 /(2.5*10^6)= 12499.6*10^-6 sec =0.0125 s or 12.5 ms
(e) mybit^=1
mybit=mybit^1
this will XOR mybit with 1. 1 XOR 1 =0 and 0 XOR 1 =1
hence if mybit is 0 it becomes 1 and if it is 1 it becomes 0
this line toggles mybit
f after each 0.0125 seconds PORTB.4 is toggled hence it is toggled 1/0.0125 times in 1 sec = 80 times
g PORTB.B4 chnages remains 0 for 0.0125 s and 1 for 0.0125 s
hence 1 cycle is 0.025s
frequency =1/0.025 =40 Hz
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.