Professional Documents
Culture Documents
Prepared by:
Eng. Ashraf Darwish
Ashraf.emad.darwish@gmail.com
Session 5
Timers /
Counters
Introduction
Introduction
Introduction
System Clock:
Microcontroller is a Sequential circuit which
need clock to operate
The clock source is the oscillator circuit,
AVR can be clocked internally or externally
ATmega 16 has internal oscillator of values
1,2,4,8,12 MHz
ATmega 16 can be clocked externally up to
16 MHz
Timer / Counter
external events
Timer / Counter
Timer / Counter
Prescaler :
It is an internal device that divides the system
Timer / Counter
Timer / Counter
prescaler of 8
therefore timer speed is 1/8 MHz (125KHz)
Which mean timer increases by 1 every 8 micro seconds
Timer / Counter
1.
2.
3.
4.
.
Modes of operation
Normal mode
Clear Timer on Compare match mode
(CTC)
Fast PWM
Phase correct PWM
In our Course we will talk about the first
two modes , Normal & CTC
Timer / Counter
Normal mode :
Timer counts from 0 (or initial value determined by
event occurred .
When timer overflow occurred the timer resets its
Timer / Counter
CTC mode :
Timer counts from 0 (or initial value determined by
event occurred
Then timer resets to its initial value again
OC0 pin can toggled on compare match
We can use compare match interrupt
Timer / Counter
Timer 0 registers :
1.
2.
3.
4.
5.
Timer / Counter
1.
Timer / Counter
2.
to it
Timer restarts when TCNT0=OCR0
When compare match occurred it can generate
toggle signal output on OC0 pin
(pin 4)
Timer / Counter
3.
Mode selection
Prescaler
Timer / Counter
Bits 0,1,2 : cs00,cs01,cs02 : choose the
prescaler value
Timer / Counter
Bit 6, Bit 3 WGM00, WGM01 : mode selection
Timer / Counter
Bits 5, Bit 4-COM00, COM01 (Compare Output
Mode)
Timer / Counter
4.
Timer Overflow
Interrupt enable
Interrupt Enable
Bit 1 OCIE0: Timer/Counter0 Output
Compare Match Interrupt Enable
Timer / Counter
5.
Timer / Counter
Timer / Counter
timer
Timer / Counter
match interrupt
Ex:
Timer / Counter
Timer / Counter
simple code :
#include <mega16.h>
int x=0, sec=0,min=0;
// Timer 0 output compare
interrupt service routine
interrupt [TIM0_COMP] void
timer0_comp_isr(void)
{
x++;
if(x==10000)
{x=0;
sec++;}
if(sec==60)
{sec=0;
min++;}
if(min==60) min=0;
}
void main(void)
{
PORTA=0x00;
DDRA=0xFF;
PORTB=0x00;
DDRB=0xFF;
TCCR0=0x09;
TCNT0=0x00;
OCR0=0x63;
TIMSK=0x02;
// Global enable interrupts
#asm("sei")
while (1)
{
PORTA=sec;
PORTB=min;
};
}
Timer / Counter
#include <mega16.h>
void main(void)
{
PORTA=0x00;
DDRA=0xFF;
// Timer/Counter 0 initialization
// Clock source: T0 pin Rising Edge
// Mode: CTC top=OCR0
// OC0 output: Disconnected
TCCR0=0x0F;
TCNT0=0x00;
OCR0=0x0A;
TIMSK=0x00;
Thank you
Contact:
http://www.facebook.com/groups/263197427113025
/
Ashraf.darwish@ymail.com
Ashraf.emad.darwish@gmail.com
+201064897791