You are on page 1of 9

Timers

Dr. M. Ramakrishnan
• Timers count internal clock frequency.
(counters in micro controller counts external
clock frequency)
• Timer has registers for storing the count.
Based on the width of this registers (8/16/32
bit), timers are called as 8 bit, 16 bit and 32
Timers bit registers
• Timers are said to be overflowed when its
register value reaches the max value and
then becomes 0 on the next clock pulse
• Typically an interrupt will be generated on
timer overflow.
Timer working Timer should overflow after 1 sec

16 bit timer
Time Period = 1/f
2^16 = 65536
T What is the initial count to be loaded to
SysClik T1 to get overflow after a sec
65536-62500 = 3036
16MHz

8 bit Timer Register


0
0 0 0 0 0 0 0 0

PRESCALER 1
Overflow
Frequency Divider
Mux 64755 Causes interrupt
16MHz/1024
= 15625Hz Timer period = 1/15625 = 0.000064s
For 1 sec, 0.064ms = 64us
number of 64us – 1 count
clock pulses = 50ms - (1/64us) *50ms
62500
• Two 8 bit Timer/Counter with separate
Prescaler (Timer0, Timer2)
• One 16 bit Timer with separate
ATMega328 Prescaler(Timer1)
p Timers • Prescaler can be configured to divide the
input frequency by 1024, 256, 128, 64, 8
• The Arduino UNO has three timers
• Timer0 - An 8 bit timer used by Arduino
Timers in functions delay(), millis() and micros().
• Timer1 - A 16 bit timer used by the Servo()
Arduino library
UNO • Timer2 - An 8 bit timer used by the Tone()
library
1. Disable Global Interrupts (nointerrupts())
2. Calculate the count to be loaded to Timer
Steps to register. (for a particular Sysclk, prescaler)

Initialize 3. Place the count in Timer register (TCNT1 =


calculated count)
Timer 4. Select the Prescalar and start timer1
(TCCR1B = (1 << CS12)) // divider as 256
5. Enable Timer 1 Overflow interrupt
(TIMSK1 |= (1 << TOIE1)
6. Enable Global interrupts (interrupts() )
For output compare
• TCCR1A – Timer Counter 1 Control Register A
• TCCR1B – Timer Counter 1 Control Register B
• TCNT1 - Timer Counter 1 Register

ATMega328
p16 Timer
Registers

Figures from ATMega328p datasheet


ATMega328 Timer1 Overflow interrupt

p16 Timer
Registers
// interrupt service routine
• void setup() ISR(TIMER1_OVF_vect)
• { {
• pinMode(ledPin, OUTPUT);
// preload timer
TCNT1 = timer1_counter;
digitalWrite(ledPin,
Timer Setup • // initialize timer1
• // disable all interrupts
digitalRead(ledPin) ^ 1);
}
to get • noInterrupts();

interrupt
• TCCR1A = 0;
• TCCR1B = 0;

every one • // preload timer 65536-16MHz/256/2Hz


• timer1_counter = 3036;

second •

TCNT1 = timer1_counter; // preload timer
TCCR1B |= (1 << CS12) ; // 256 prescaler
• TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
• interrupts(); // enable all interrupts
• }

You might also like