MPS W6-L1 Programming AVR Timers I (1)
MPS W6-L1 Programming AVR Timers I (1)
Outline
• Timers
▫ Registers
▫ Timer flags
▫ Timer programming
AVR Timers
Timers
Timers: Why do we need
them?
• Provide accurately timed delays or actions
independent of code execution time
• How are Timers used?
▫ Accurate delay
Read the timer, store value as K. Loop until timer
reaches K+100.
▫ Schedule important events
Setup an Output Compare to trigger an interrupt at a
precise time
▫ Measure time between events
When event#1 happens, store timer value as K
When event#2 happens, read timer value and subtract K
The difference is the time elapsed between the two
6
AVR Timers
• Generally, we use a timer/counter to generate time
delays, waveforms, or to count events.
▫ In AVR ATmega16 / ATmega32, there are three
timers:
Timer0: 8-bit timer
Timer1: 16-bit timer
Timer2: 8-bit timer
7
AVR Timers
• We can load a count value in TCNT0 and start the
timer from a specific count.
• Another interesting feature is that a value can be
set in the Output Compare Register (OCR0), and
▫ whenever TCNT0 reaches that value, the Output
Compare Flag (OCF0) flag is Set.
8
Timer0 Programming
12
TCCR0
TIFR0
14
Timer 0 – Hardware
Organization
17
Example
• Find the value of TCCR0 if we want to program
Timer0 in:
▫ Normal Mode
▫ No prescaler
▫ Use AVR’s Crystal Oscillator for the clock source
• Sol:
Normal Mode
FF TCNT0
FE
0xFF
TOV0: 0
1
19
Timer 0 Demo
1. Load the TCNT0 LDI R20, 0xF2
OUT TCNT0, R20
2. Configure TCCR0 register
3. Monitor TOV0 LDI R20, 0x01
OUT TCCR0, R20
4. Stop the timer
5. Clear the TOV0 AGAIN: IN R20,TIFR
SBRS R20,TOV0
RJMP AGAIN
LDI R20,0x0
OUT TCCR0,R20
LDI R20,0x01
OUT TIFR, R20
In example 1 calculate the delay.
XTAL = 10 MHz.
Solution 1 (inaccurate):
LDI R16,0x20
1) Calculating T: SBI DDRB,5 ;PB5 as an output
LDI R17,0
T = 1/f = 1/10M = 0.1µs OUT PORTB,R17
BEGIN: LDI R20,0xF2
2) Calculating num of OUT TCNT0,R20 ;load timer0
machine cycles: LDI R20,0x0
OUT TCCR0A,R20
$100 LDI R20,0x01
OUT TCCR0B,R20 ;Normal mode, inter. clk
-$F2 AGAIN: SBIS TIFR0,TOV0 ;if TOV0 is set skip next
RJMP AGAIN
$0E = 14 LDI R20,0x0
OUT TCCR0B,R20 ;stop Timer0
3) Calculating delay
LDI R20,(1<<TOV0) ;R20 = 0x01
14 * 0.1µs = 1.4 0µs OUT TIFR0,R20 ;clear TOV0 flag
Conclusion
• Timers as delay
▫ Registers
▫ Timer flags
31
Reading Material
• Textbook:
▫ Chapter 9, Section 9.1
32
Questions?