UVIC Beye
5.2 Timers & Counters
Microcontroladors (3r curs)
Grau en Enginyeria Mecatronica
Brahim Achaoui
Ramon Reig Bolafio2 Timers in ATmega16
m= Many computer applications require accurate timing.
m Examples include
QO recording the time when an event occurs,
Q calculating the time difference between events,
O performing tasks at specific or periodic time instants,
Q creating accurate time delays,
UO generating waveforms of certain shape, period or duty cycle.
m Lecture 9 and Lecture 10 focus on the use of timers to perform the
above time-related processing.
UVIC 2Timer terminology
m Input Capture:
An input signal is connected to a pin, designated as input capture
pin, of the timer.
J When a preset event (rising edge, falling edge, change) occurs on
the input capture pin, the current value of the timer is stored in a
register.
m Output Compare:
1A timer usually has a pin designated as output compare pin.
When the timer reaches a preset value, the output compare pin can
be automatically changed to logic 0 or logic 1.
UVIC 3Overview of Timers in ATmega16
m ATmega’‘6 has three timers: Timer 0, Timer 1 and Timer 2.
m Each timer is associated with a counter and a clock signal.
m The counter is incremented by 1 in every period of the timer’s clock
signal.
@ The clock signal of a timer can come from
the internal system clock or
an external clock source.
UVICOverview of Timers in ATmega16
= When the internal system clock is used, a prescaler can be used make
the timer count at a slower rate.
m Example:
Ol Suppose the system clock rate = 1Mhz (‘ps per cycle).
Suppose a timer prescaler of 64 is used.
Then, timer will increment every 64us.
UVIC 5Overview of Timers in ATmega16
Overall | - 8-bit counter -16-bit counter - &-bit counter
~ 10-bit prescaler ~ 10-bit prescaler - 10-bit prescaler
Functions | - PWM. -PWM -PWM
Frequency generation | - Frequency generation _| - Frequency generation.
- Event counter ~ Event counter - Event counter
- Output compare - Output compare: 2 - Output compare
channeis,
-Input capture
Operation | - Normal mode - Normal mode - Normal mode
modes - Clear timer on - Clear timer on - Clear timer on
compare match compare match compare match
- Fast PWM - Fast PWM - Fast PWM
- Phase correct PWM. - Phase correct PWM - Phase correct PWM
= Timer 1 has the most capability among the three timers.
UVIC 8Timer 1: An overview
m 16-bit counter.
m 10-bit prescaler: 8, 64, 256, 1024
= can trigger a timer overflow interrupt when counter reaches MAX.
@ can trigger an input capture interrupt when an event occurs on the
input capture pin.
i timer value is stored automatically in a register.
input capture pin for Timer 1 is ICP1 (D.6).
m can trigger an output compare match interrupt when timer reaches a
preset value.
O There are two independent output compare channels A and B.
UVICTimer 1: Block diagram
praises)
pire
ee
bie RT
Not shown here: TIMSK and TIFR registers
UVIC 8Timer 1 — Relevant pins
(XCK/TO) PBO (| 4
Ti
(NTZAIND) PB2 |
COoMANNY) Pes:
SB) Pr
(MOsI) ee
(Miso) PB6
(SCK) PB? a
32
vec 31
GND 30
XTAL2 20
XTALt 287
(RXD) PDO 27
(TxD) PD1 266
(INTO) PD2 C} 16 25
(INT) PDS C] 17 245
[1
a a pi
used in this 5
lecture
UVIC
AvCC
POT (TOSC2)
PC6 (TOSC1)
PCS (TDI)
PCd (TDC)
PC3 (TMS)
PC2 (TCK)
PCi (SDA)
PCO (SCL)
PD7 (0C2)Timer 1 — Five groups of registers
4) Timer/Counter 4
OTCNT1
3 16-bit register that stores the current value of the timer.
2) Timer/Counter 1 Control Registers
O TCCRIA and TCCRIB
To configure the operations of Timer 1.
3) Input Capture Register
GIcR1
Q to store timer value when an event occurs on input capture pin.
4) Interrupt registers
I TIMSK to enable timer interrupts
OTIFR to monitor status of timer interrupts.
UVIC 102 1 Timer/Counter 1 Control Register A (TCCR1A)
7 6 5 4 3 2 1 0
[comaqeomtadcomteipowred roca FOC1B | WGM11] WGM10
Y
EU Ne ued
Pee Run comic Er
WGM13.. WGM10 = 0000 for normal mode.
channel B
{ouipui compare mode for channel A
UVIC 12 2 Timer/Counter 1 Control Register B (TCCR1B)
T 6 5 4 3 2 1 0
reer | icest 7 [eursfwowrz] cst2 | cst l cs10
eee)
Puke thn cool
Pmt emu has
input capture edge select: 1 will select rising edge, 0 will select falling edge
Proc ui a aicd
UVIC 2Clock select
esiz [csi | cs
3s
Description
No clock source (Timer/Counter stopped).
Cikyo/1 (No prescaling)
Cikyo/8 (From prescaler)
Clk,o/64 (From prescalen
Cikyo/256 (From prescaler)
cikyo/1024 (From prescalet)
External clock source on Tt pin, Clock on falling edge.
External clock source on T1 pin, Glock on rising edge.
u For ATmega'‘6, the internal clock is set by default at clk, = 1MHz.
@ Timer 1 can run using the internal or external clock.
= If using the internal clock, we can set Timer 1 to run at a speed that is
8, 64, 256 or 1024 times slower than the internal clock.
UVIC 182 3 Timer/Counter Interrupt Mask Register (TIMSK)
7 6 5.4 3 az 1 0
ocie2 | ToIe2 | TICIE1 ecierafociete] totes ocieo | ToIEo
slFor Timer
0
Se eueeud at sacs
fj Timer 1 input Capture Interrupt Enable: 1 to enable
142 4Timer/Counter Interrupt Flag Register (TIFR)
7 6 54 3 2 1 0
ocr2 | Tova | Icr1 [ocrafocrts] Tovt | ocro | Tovo
< 7 a
Lveortimer 0}
Ret ae kee
|_____.ijimer 1 Output Compare A Maten Fiag: set to 1 when maten
Homi eae ee eeu ead
@ This register has flags that indicate when a timer interrupt occurs.
UVIC 153 Timer applications
g In this section, we consider three applications of Timer 1.
.3.1 Creating an accurate delay using timer overflow interrupt.
.3.2 Measuring elapsed time between two events.
.3.3 Measuring the period of a square signal using input capture
interrupt.
UVIC 163 1 Creating an accurate delay
Ani eed lero le Tn Com ME eC WR melee Me) aie sarees
It should use timer 1 overflow interrupt to create delays of 2s each.
= Analysis
Q Internal system clock: 1MHz.
Q With no prescaler, Timer 1 will increment every 1 ps.
O Because Timer 1 is 16-bit counter, it will overflow every 2" pis.
O To have a 2s delay, we need Timer 1 to overflow for 2s/2" us = 31
times.
m Coding
1 Write code to enable & intercept Timer 1 overflow interrupt.
4 Use interrupt handler to count the number of overflows.
4 When number of overflows = 31, toggle port B.
UVIC 17Creating an accurate delay: timer_delay.c
#include
finclude al
volatile int overflow count;
IsR(TIMERL_OVF_vect)( // handler for Timerl overflow interrupt
overflow count++; /] increment overflow count 2
4£ (overflow count >= 31){ // when 2s has passed
overflow count = 0; // start new count
PORTE = ~PORTS; /1 toagle port B
}
int main(void) {
DORE = OxFF; // set port B for output
PORTB = Ox00; // initial value of PORTS
overflow count = 0; // initialise overflow count
TecRia = 000000000; // normal mode g
TecRID = 000000001; // no prescaler, internal clock
TIMsK = Oh00000100; // enable Timer 1 overflow interrupt
sei(): // enable interrupt subsystem globally
while (1) (+ // infinite Loop
return 0;
1
UVIC 183 2 Measuring elapsed time
ug To measure a time interval using Timer 1, we must keep track of both
the number of times that Timer 1 has overflowed: n
Othe current counter value: TCNT1
u If we reset n and TCNT( at the beginning of the interval, then the
time elapse is (assuming no prescaler, 1MHz clock)
t=nx65536+TCNT1 (us)
Time
n=0
TONTI=0
time interval t
stop at time t,
start at time t,
UVIC 19Measuring elapsed time
EM mee ORC a UL < CUR ee me ue emer
m Approach:
Clear Timer 1 when the code starts.
Cl Record Timer 1 when the code finishes.
Also, use Timer 1 Overflow Interrupt to keep track of how many
times it has overflowed.
UVIC 20Measuring elapsed time: measure_time.c
#include
include
Sinditde
volatile uint32_t n;
ISR(TIMER1 OVF yect){ // handler for Timerl overflow interrupt
nt; // increment overflow count
+
int main(void) {
ant i, 3:
uint32_t elapse_time;
TecR1A = 000000000; // noxmal mode
TCCRIB = 0b00000001; // no prescaler, internal clock
TIMSK = 0b00000100; // enable Timer 1 overflow interrupt
enable
terrupt subsystem globally
elapse time = n * 66536 + (uint32 t) TCNT1;
eli; // disable interrupt subsystem globally
return 0;
}
UVIC a3 3 Measuring period of a square signal
interrupt to measure the pe
Stee a
@ Analysi
O The period of a square wave = the time difference between
two consecutive rising edges.
O Connect the square wave to input capture pin of Timer 1.
O Configure input capture module to trigger on a rising edge.
square waveform
k— period ——l
UVIC 22Measuring period of a square signal
= Assumption: the input signal has a high frequency, hence timer
overflow can be ignored.
= Implementation:
J Select timer operations: normal, no prescaler, internal clock 1MHz,
noise canceller enabled, input capture for rising edges.
TCCRIA = 0b00000000;
TCCRIB = 0600000001;
O Enable input capture interrupt:
TIMSK = 0600100000;
UVIC
23measure_period.c
#include
#include
#include
uint16_t period;
ISR(TIMER1 CAPT vect){ // handler for Timerl input capture interrupt
+
int main(void) {
DDRB = OxFE; // set port B for output
TCCRIA = 0b00000000; // normal mode
TCCRIB = 0b11000001; // no prescaler, rising edge, noise canceller
TIMSK = 0b00100000; // enable Timer 1 input capture interrupt
selQ; // enable interrupt subsystem globally
while (1){;} // infinite loop
return 0;
UVIC 24Extending measure_period.c
m@ The code given here assumes that there is no timer overflow between
two rising edges of the square signal.
@ In Lab 9, you are required to extend the code so that a correct period is
measured for low-frequency signals.
m It is necessary to intercept timer overflow (as in Examples 9.3.1 and
9.3.2).
@ The measure period should also be sent through the serial port to PC
for testing.
UVIC 25references
mu J. Pardue, C Programming for Microcontrollers, 2005, SmileyMicros,
[Chapter 7: Interrupts...].
m@ Atmel Corp., 8-bit AVR microcontroller with 16K Bytes In-System
Programmable Flash ATmega16/ATmega16L, 2007,
[Interrupts], [External Interrupts] and [Timers]. Manual
S.F. Barrett and D. J. Pack, Atmel AVR Microcontroller Primer:
Programming and Interfacing, 2008, Morgan & Claypool Publishers,
[Chapter 5: Timing Subsystem].
UVIC 26