AVR_Interrupts
AVR_Interrupts
com
AVR Interrupts
By
D.BALAKRISHNA,
Research Assistant, IIIT-H
A single microcontroller can serve several devices. There are two methods
m
by which devices receive service from the microcontroller: interrupts or polling.
co
Interrupts Vs Polling:
In the interrupt method, whenever any device needs the microcontroller’s
n.
service, the device notifies it by sending an interrupt signal. Upon receiving an
io
interrupt signal, the microcontroller stops whatever it is doing and serves the
device.
at
The program associated with the interrupt is called the interrupt service
uc
routine (ISR) or interrupt handler.
device; when the status condition is met, it performs the service. After that, it
moves on to monitor the next device until each one is serviced. Although polling
hi
can monitor the status of several devices and serve each of them as certain
ks
devices (not all at the same time, of course); each device can get the
.s
round-robin fashion.
w
1
www.sakshieducation.com
www.sakshieducation.com
m
vector table, as shown in Table below
co
n.
io
at
uc
ed
hi
a ks
.s
2
www.sakshieducation.com
www.sakshieducation.com
m
o Then it starts to execute from that address.
co
Notice from Step 4 the critical role of the stack. For this reason, we must be careful
in manipulating the stack contents in the ISR. Specifically, in the ISR, just as in
n.
any CALL subroutine, the number of pushes and pops must be equal.
io
Sources of interrupts in the AVR:
at
There are many sources of interrupts in the AVR, depending on which
peripheral is incorporated into the chip.
uc
The following are some of the most widely used sources of interrupts in the
ed
AVR:
• There are at least two interrupts set aside for each of the timers, one for over
hi
o Pins PD2 (PORTD.2), PD3 (PORTD.3), and PB2 (PORTB.2) are for
a
3
www.sakshieducation.com
www.sakshieducation.com
The D7 bit of the SREG (Status Register) register is responsible for enabling
and disabling the interrupts globally. The I-bit makes the job of disabling all the
interrupts easy. With a single instruction “CLI” (Clear Interrupt), we can make I =
0 during the operation of a critical task.
m
co
n.
io
Fig: Status Register of ATmega 32
at
• Bit D7 (1) of the SREG register must be set to HIGH to allow the interrupts
uc
to happen.
o This is done with the “SEI” (Set Interrupt) instruction.
ed
• If I =1, each interrupt is enabled by setting to HIGH the interrupt enable (IE)
flag bit for that interrupt.
hi
o There are some I/O registers holding the interrupt enable bits.
o It must be noted that if I =0, no interrupt will be responded to, even if
ks
External Interrupts
.s
• PB2 (PORTB.2)
w
These are for the external hardware interrupts INT0, INT1, and INT2,
respectively
4
www.sakshieducation.com
www.sakshieducation.com
They are located on pins PD2, PD3, and PB2, respectively. As shown in
Table below, the interrupt vector table locations $2, $4, and $6 are set aside for
m
INTO, INT1, and LNT2, respectively.
co
n.
io
at
uc
ed
hi
ks
The hardware interrupts must be enabled before they can take effect. These
interrupts are controlled by the following registers.
w
• GICR
w
• GIFR
• MCUCR
w
• MCUCSR
5
www.sakshieducation.com
www.sakshieducation.com
GICR:
m
INT0:
co
When this bit is ‘1’ and global interrupt bit in SREG is ‘1’ (i.e. I bit) the
External Interrupt 0 is enabled
enabled.. The ISC01 and ISC00 of MCUCR register
n.
control the interrupt when to be activated (i.e. on rising edg
edgee or falling edge or
level sensed).
io
The INTO is a low-level-triggered interrupt by default, which means,
when a low signal is applied to pin PD2 (PORTD.2), the controller will be
at
interrupted and jump to location $0002 in the vector table to service the TSR.
uc
INT1: When this bit is ‘1’ and global interrupt bit in SREG is ‘1’ (i.e. I bit)
the External Interrupt 1 is enabled. The ISC11 and ISC10 of MCUCR register
ed
control the interrupt when to be activated (i.e. on rising edge or falling edge or
level sensed).
hi
INT2: When this bit is ‘1’ and global interrupt bit in SREG is ‘1’ (i.e. I bit)
ks
the External Interrupt 2 is enabled. ISC2 bit of MCUCSR register control the
interrupt when to be activated (i.e. on rising edge or falling edge).
a
• Level triggered
w
• Edge triggered
w
INT0 & INT1 can be edge or level triggered, but INT2 can be edge
w
triggered only.
The MCUCR & MCUCSR registers decides the triggering options of the external
hardware interrupts INT0, INT1, and INT2.
6
www.sakshieducation.com
www.sakshieducation.com
MCUCR:
This register decides the triggering options of the external hardware interrupts
INT0 and INT1.
m
co
ISC01 & ISC00 (Interrupt Sense Control Bits):
These bits define the level or edge on the external INT0 pin that activate the
n.
interrupt as shown in table below.
io
at
uc
ed
ISC11 &ISC10:
hi
These bits define the level or edge on the external INT1 pin that activate the
ks
MCUSCR:
This register decides the triggering options of the external hardware interrupt
INT2.
7
www.sakshieducation.com
www.sakshieducation.com
m
co
n.
io
GIFR:
at
When an external interrupt is in an edge-triggered mode (falling edge, rising
uc
edge, or change level), upon triggering an interrupt request, the related INTFx flag
becomes set.
ed
hi
ks
If the interrupt is active (the INTx bit is set and the I-bit in SREG is one), the
a
AVR will jump to the corresponding interrupt vector location and the INTFx flag
.s
will be cleared automatically, otherwise, the flag remains set. The flag can be
cleared by writing a one to it.
w
In other words
w
• INTF1: When ‘1’ on this bit trigger INT1 Interrupt when INT1 bit of GICR
w
8
www.sakshieducation.com
www.sakshieducation.com
Interrupt Priority:
If two interrupts are activated at the same time, the interrupt with the higher
priority is served first. The priority of each interrupt is related to the address of that
interrupt in the interrupt vector.
m
The interrupt that has a lower address, has a higher priority.
co
For example, the address of external interrupt 0 is 2, while the address of
external interrupt 2 is 6; thus, external interrupt 0 has a higher priority, and if both
n.
of these interrupts are activated at the same time, extern al interrupt 0 is served
first.
io
Interrupt inside an interrupt:
at
What happens if the AVR is executing an ISR belonging to an interrupt and
uc
another interrupt is activated?
ed
When the AVR begins to execute an ISR, it disables the I-bit of the SREG
register, causing all the interrupts to be disabled, and no other interrupt occurs
while serving the current interrupt.
hi
When the RETI instruction is execute d, the AVR enables the I-bit, causing
ks
If you want another interrupt (with any priority) to be served while the
.s
current interrupt is being served you can set the I-bit using the SEI instruction. But
do it with care.
w
while the pin is still active will cause the ISR to be reentered infinitely, causing the
w
Interrupt latency:
The time from the moment an interrupt is activated to the moment the CPU
starts to execute the task is called the interrupt latency. This latency is 4 machine
cycle times.
9
www.sakshieducation.com
www.sakshieducation.com
During this time the PC register is pushed on the stack and the I-bit of the
SREG register clears, causing all the interrupts to be disabled. The duration of the
interrupt latency can be affected by the type of instruction that the CPU is
executing when the interrupt comes in, since the CPU finishes the execution of the
current instruction before it serves the interrupt. It takes slightly longer in cases
where the instruction being executed lasts for two (or more) machine cycles (e.g.,
MUL) compared to the instructions that last for only one instruction cycle (e.g.,
m
ADD).
co
INTERRUPT PROGRAMMING IN C:
n.
In C language there is no instruction to manage the interrupts. So, in
WinAVR the following have been added to manage the interrupts:
io
at
Interrupt include file: We should include the interrupt header file if we
want to use interrupts in our program. Use the following instruction:
uc
#include <avr\ interrupt .h>
ed
cli ( ) and sei ( ): In Assembly, the CLI and SEI Instructions clear and set
the I-bit of the SREG register, respectively. In WinAVR, the cli () and sei ()
hi
//our program
w
}
For the interrupt vector namewe must use the ISR names in Table shown below.
w
For example, the following TSR serves the Timer0 compare match interrupt:
ISR (TIMER0_COMP_vect)
{
}
10
www.sakshieducation.com
www.sakshieducation.com
m
Time/Counter1 Compare Match A TIMER1_ COMPA_vect
co
Time/Counter1 Compare Match B TIMER1_ COMPB_vect
Time/Counter1 Overflow TIMER1_OVF_vect
n.
Time/Counter0 Compare Match TIMER0_COMP_vect
Time/Counter0 Overflow TIMER0_OVF_vect
io
SPI Transfer complete SPI_STC_vect
at
USART, Receive complete USART0_RX_vect
USART, Data Register Empty USART0_UDRE_vect
uc
USART, Transmit Complete USART0_TX_vect
ADC Conversion complete ADC_vect
ed
Example 1:
w
Assume that the INT0 pin is connected to a switch that is normally high.
w
Write a program that toggles PORTC.3, whenever INT0 pin goes low. Use the
external interrupt in level-triggered mode.
w
Solution:
#include <avr/io.h>
#include <avr/irtterrupt.h>
int main ()
11
www.sakshieducation.com
www.sakshieducation.com
{
DDRC = 1<<3; //PC3 as an output
PORTD = 1<<2; //pull-up activated
GICR = (1<<INTO); //enable external interrupt 0
sei (); //enable interrupts
while (1); //wait here
}
m
ISR (INT0_vect) //ISR for external interrupt 0
co
{
PORTC ^= (l<<3); //toggle PORTC.3
}
n.
Example 2:
io
Rewrite Example 1, so that whenever INT0 goes low, it toggles PORTC.3 only
at
once. uc
Solution:
#include <avr/io.h>
ed
#include <avr/irtterrupt.h>
int main ()
hi
{
DDRC = 1<<3; //PC3 as an output
ks
{
PORTC ^= (1<<3); //toggle PORTC.3
}
12
www.sakshieducation.com
www.sakshieducation.com
TIMER Interrupts
AVR Timers:
AVR timers have a lot of complex uses, but their essential purpose is to measure
time.
m
microcontroller’s core code. This is possible only because the timers have a
co
separate circuit for their function.
The smallest amount of time that a timer can measure is determined by the
n.
frequency of the clock source which the microcontroller uses. For example if the
microcontroller uses a 4MHz crystal as the clock source, then the smallest time it
io
can measure is 1/4000000th of a second.
at
Timers as registers:
uc
So basically, a timer is a register, but not a normal one. The value of this
register increases/decreases automatically.
ed
from 0 to 255
.s
w
w
w
13
www.sakshieducation.com
www.sakshieducation.com
m
• TIMER0 - 8-bit timer
co
• TIMER1 – 16-bit timer
• TIMER2 – 8-bit timer
n.
The timer is totally independent of the CPU. Thus, it runs parallel to the
io
CPU and there is no CPU’s intervention.
at
Apart from normal operation, these three timers can be either operated in
• Normal mode
uc
• CTC mode
• PWM mode
ed
hi
Timer Concepts:
ks
Now let’s assume that we have an external crystal XTAL of 4 MHz, Hence,
the CPU clock frequency is 4 MHz
w
14
www.sakshieducation.com
www.sakshieducation.com
For F_CPU = 4 MHz, time period T = 1/4M = 0.00025 ms. Thus for every
transition (0 to 1, 1 to 2, etc), it takes only 0.00025 ms
m
Let us assume we need a delay of 10 ms. This maybe a very short delay, but
for the microcontroller which has a resolution of 0.00025 ms, it’s quite a long
co
delay.
n.
To get an idea of how long it takes, let’s calculate the timer count from the
following formula:
io
at
uc
Substitute Required Delay = 10 ms and Clock Time Period = 0.00025 ms,
and we will getTimer Count = 39999
ed
Now, to achieve this, we definitely cannot use an 8-bit timer (as it has an
upper limit of 255, after which it overflows). Hence, we use a 16-bit timer (which
hi
To achieve this, we cannot use an 8-bit timer (as it has an upper limit of
255). Hence, we use a 16-bit timer (which is capable of counting up to 65535) to
a
The Prescaler:
w
substituting in the above formula, we can get a maximum delay of 16.384 ms.
w
Suppose if we decrease the F_CPU from 4 MHz to 0.5 MHz (i.e. 500
kHz), then the clock time period increases to 1/500k = 0.002 ms.Now if we
substitute Required Delay = 20 ms and Clock Time Period = 0.002 ms, we get
15
www.sakshieducation.com
www.sakshieducation.com
Timer Count = 9999. As we can see, this can easily be achieved using a 16-bit
timer. At this frequency, a maximum delay of 131.072 ms can be achieved.
m
some bits which we will discuss later.
co
We cannot use prescaler freely.There is a trade-off between resolution
and duration.The resolution has also increased from 0.00025 ms to 0.002 ms. this
n.
means each tick will take 0.002 ms that causes reduction of accuracy.
Choosing Prescalers:
io
The AVR offers us the following prescaler values to choose from: 8, 64, 256
at
and 1024. A prescaler of 8 means the effective clock frequency will be F_CPU/8.
uc
Now substituting each of these values into the above formula, we get
different values of timer value.
ed
Now out of these four prescalers, 8 cannot be used as the timer value
exceeds the limit of 65535. Also, since the timer always takes up integer values,
we cannot choose 1024 as the timer count is a decimal digit. Hence, we see that
prescaler values of 64 and 256 are feasible. But out of these two, we choose 64 as
it provides us with greater resolution. We can choose 256 if we need the timer for a
greater duration elsewhere.
16
www.sakshieducation.com
www.sakshieducation.com
Thus, we always choose prescalar which gives the counter value within
the feasible limit (255 or 65535) and the counter value should always be an
integer.
m
co
n.
io
at
uc
Fig: Timer0 Prescalar/ Selector
ed
some registers.
ks
TCNT0 Register:
a
17
www.sakshieducation.com
www.sakshieducation.com
Now we know where the counter value lies. But this register won’t be
activated unless we activate the timer! Thus we need to set the timer up by
using Timer Counter Control Register.
TCCR0 Register:
m
co
n.
Fig: TCCR0 Register
io
• Clock Select Bits (CS 02: 00): Used toset the timer up by
at
choosing proper prescaler. The possible combinations are
shown below.
uc
CS02 CS01 CS00 Description
ed
falling edge.
.s
o Example code:
w
18
www.sakshieducation.com
www.sakshieducation.com
m
operation on
0 0 0 Normal 0xFF Immediate MAX
co
1 0 1 PWM, Phase 0xFF TOP BOTTOM
correct
n.
2 1 0 CTC OCR0 Immediate MAX
3 1 1 Fast PWM 0xFF TOP MAX
io
Fig: Wave Generation Mode Bit Description
at
• Bit 5:4 – COM01:00 – Compare Match Output Mode –
o Controls the behavior of the OC0 (PB3) pin depending
uc
upon the WGM mode –
non-PWM,
ed
19
www.sakshieducation.com
www.sakshieducation.com
OCR0 Register:
m
co
n.
io
Fig: OCR0 Register
at
The value to be compared (max 255) is stored in this register.
uc
TIMSK Register:
ed
Bits (1:0):
w
• Correspond to TIMER0
• Bit0:
o Setting the bitTOIE0 to ’1′ enables the TIMER0 overflow interrupt.
• Bit 1:
20
www.sakshieducation.com
www.sakshieducation.com
Bits (5:2):
• Correspond to TIMER1.
• Bit 2 – TOIE1 – Timer/Counter1 Overflow Interrupt
m
Enable bit
co
o Enables the overflow interrupt of TIMER1.
• Other bits are related to CTC mode
n.
o Bit 4:3 –OCIE1A: B – Timer/Counter1, Output
Compare A/B Match Interrupt Enable bits.
io
Enabling it ensures that an interrupt is fired
whenever a match occurs.
at
Since there are two CTC channels, we have two
uc
different bits OCIE1A and OCIE1B for them.
Enable
TICIE1= 0 Disables Timerl input capture
hi
interrupt
TICIE1= I Enables Timer 1 input capture
ks
interrupt
Bits (7:6):
a
.s
• Correspond to TIMER2
• Setting the bit TOIE2 to ’1′ enables the TIMER0 overflow
w
interrupt.
w
Interrupt Enable
o Enables the firing of interrupt whenever a compare
match occurs.
TIFR Register:
21
www.sakshieducation.com
www.sakshieducation.com
m
co
Fig: TIFR Register
n.
Bits (1:0):
io
• Correspond to TIMER0
at
• Bit 0: uc
o TOV0(Timer/Counter1 Overflow Flag) bit is set (one) whenever TIMER0
overflows.
This bit is reset (zero) whenever the Interrupt Service Routine (ISR) is
ed
executed.
If there is no ISR to execute, we can clear it manually by writing one to it.
hi
• Bit 1:
ks
Bits (5:2):
w
• Correspond to TIMER1.
• Bit 2 – TOV1 – Timer/Counter1 Overflow Flag bit is set to 1 whenever
w
22
www.sakshieducation.com
www.sakshieducation.com
m
Bits (7:6):
co
• Correspond to TIMER2
• TOV2 bit is set (one) whenever TIMER2 overflows.
n.
o This bit is reset (zero) whenever the Interrupt Service Routine (ISR) is
io
executed.
o If there is no ISR to execute, we can clear it manually by writing one to it.
at
uc
Example: (Without Using interrupts)
ed
TCCR0 register.
ks
Code:
a
#include <avr/io.h>
.s
void timer0_init()
{
w
TCNT0 = 0;
}
int main(void)
{
// connect led to pin PC0
DDRC |= (1 << 0);
// initialize timer
23
www.sakshieducation.com
www.sakshieducation.com
timer0_init();
// loop forever
while(1)
{
// check if the timer count reaches 124
if (TCNT0 >= 124)
{
PORTC ^= (1 << 0); // toggles the led
m
TCNT0 = 0; // reset counter
}
co
}
}
n.
Example: (Using Interrupts)
io
To flash the LED every 50 ms. With CPU frequency 16 MHz,
at
Even a maximum delay of 16.384 ms can be achieved using a 1024
uc
prescaler.The concept here is that the hardware generates an interrupt every time
the timer overflows. Since the required delay is greater than the maximum possible
delay, obviously the timer will overflow. And whenever the timer overflows, an
ed
interrupt is fired. Now the question is how many times should the interrupt be
fired?
hi
For this, let’s do some calculation. Let’s choose a prescaler, say 256. Thus,
as per the calculations, it should take 4.096 ms for the timer to overflow. Now as
ks
soon as the timer overflows, an interrupt is fired and an Interrupt Service Routine
(ISR) is executed. Now,
a
.s
50 ms ÷ 4.096 ms = 12.207
Thus, in simple terms, by the time the timer has overflown 12 times, 49.152
w
ms would have passed. After that, when the timer undergoes 13th iteration, it
w
would achieve a delay of 50 ms. Thus, in the 13th iteration, we need a delay of 50
– 49.152 = 0.848 ms. At a frequency of 62.5 kHz (prescaler = 256), each tick takes
w
0.016 ms. Thus to achieve a delay of 0.848 ms, it would require 53 ticks. Thus, in
the 13th iteration, we only allow the timer to count up to 53, and then reset it. All
this can be achieved in the ISR as follows:
Code:
#include <avr/io.h>
24
www.sakshieducation.com
www.sakshieducation.com
#include <avr/interrupt.h>
// global variable to count the number of overflows
volatile uint8_t tot_overflow;
// initialize timer, interrupt and variable
void timer0_init()
{
TCCR0 |= (1 << CS02);// set up timer with prescaler = 256
TCNT0 = 0;// initialize counter
m
TIMSK |= (1 << TOIE0);// enable overflow interrupt
sei();// enable global interrupts
co
tot_overflow = 0;// initialize overflow counter variable
}
n.
// TIMER0 overflow interrupt service routine called whenever TCNT0
overflows
io
ISR(TIMER0_OVF_vect)
{
at
// keep a track of number of overflows
tot_overflow++;
uc
}
int main(void)
ed
{
// connect led to pin PC0
DDRC |= (1 << 0);
hi
// initialize timer
ks
timer0_init();
// loop forever
while(1)
a
{
.s
{
w
{
PORTC ^= (1 << 0); // toggles the led
TCNT0 = 0; // reset counter
tot_overflow = 0; // reset overflow counter
}
}
}
25
www.sakshieducation.com
www.sakshieducation.com
m
The input capture register is used for measuring pulse widths or
capturingtimes. The output compare registers are used for producing frequencies or
co
pulses from thetimer/counter to an output pin on the microcontroller.
TCNT1 Register:
n.
The Timer/Counter1 Register, shown in figure below.
io
at
uc
ed
the HIGH byte whereas TCNT1L represents the LOW byte. The timer/counter
value is stored in these bytes.
a
TCCR1B.
w
TCCR1A controls the compare modes and the pulse width modulation
modes of Timer1.
w
TCCR1B controls the prescaler and input multiplexer for Timer 1, as well
asthe input capture modes.
TCCR1A Register:
26
www.sakshieducation.com
www.sakshieducation.com
m
• The behavior changes depending upon the following modes:
co
o Non-PWM mode (normal / CTC mode)
o Fast PWM mode
n.
o Phase Correct / Phase & Frequency Correct PWM mode
• Bit 7:6 – COM1A1:0 and Bit 5:4 – COM1B1:0
io
o Compare Output Mode for Compare Unit A/B.
at
o These bits control the behavior of the Output Compare (OC)
pins.
uc
ed
COM1B1 COM1B0
0 0 Normal port operation, OC1A/OC1B disconnected.
ks
low level)
.s
A/B.
o These bits are write only bits.
o They are active only in non-PWM mode.
o For ensuring compatibility with future devices, these bits must
be set to zero (which they already are by default).
27
www.sakshieducation.com
www.sakshieducation.com
TCCR1B Register:
m
The Timer/Counter1 Control Register Bshown in figure below.
co
n.
io
at
uc
Fig: TCCR1B Register
ed
The bit 2:0 – CS12:10 are the Clock Select Bits of TIMER1. Their
selection is as follows.
hi
28
www.sakshieducation.com
www.sakshieducation.com
m
Mode WGM1 WGM1 WGM11 WGM10 Timer/Counter Mode of operation Top Update of TOV1
3 2 (PWM1 (PWM10) OCR1x Flag Set
(CTC1) 1) on
co
0 0 0 0 0 Normal 0xFFFF Immediate MAX
1 0 0 0 1 PWM, Phase Correct, 8-bit 0x00FF TOP BOTTOM
2 0 0 1 0 PWM, Phase Correct, 9-bit 0x01FF TOP BOTTOM
n.
3 0 0 1 1 PWM, Phase Correct, 10-bit 0x03FF TOP BOTTOM
4 0 1 0 0 CTC OCR1A Immediate MAX
io
5 0 1 0 1 Fast PWM, 8-bit 0x00FF TOP TOP
6 0 1 1 0 Fast PWM, 9-bit 0x01FF TOP TOP
at
7 0 1 1 1 Fast PWM, 10-bit 0x03FF TOP TOP
8 1 0 0 0 PWM, Phase & Frequency correct ICR1 BOTTOM BOTTOM
9 1 0 0 1
uc
PWM, Phase & Frequency correct OCR1A BOTTOM BOTTOM
10 1 0 1 0 PWM, Phase Correct ICR1 TOP BOTTOM
11 1 0 1 1 PWM, Phase Correct OCR1A TOP BOTTOM
ed
12 1 1 0 0 CTC ICR1 Immediate MAX
13 1 1 0 1 Reserved - - -
14 1 1 1 0 Fast PWM ICR1 TOP TOP
15 1 1 1 1 Fast PWM OCR1A TOP TOP
hi
In pin configuration of ATMEGA16/32, we can see the pins PB3, PD4, PD5
and PD7. Their special functions are mentioned in the brackets (OC0, OC1A,
a
OC1B and OC2). These are the Output Compare pins of TIMER0, TIMER1 and
.s
29
www.sakshieducation.com
www.sakshieducation.com
m
co
n.
io
at
uc
Fig: ATmega 16/ 32 Pin description
ed
We must tell the AVR to reset the timer as soon as its value reaches such
ks
and such value. So, the question is, how do we set such and such values? The
Output Compare Register 1A – OCR1A and the Output Compare Register 1B
a
30
www.sakshieducation.com
www.sakshieducation.com
m
Since the compare value will be a 16-bit value (in between 0 and 65535),
OCR1A and OCR1B are 16-bit registers. In ATMEGA16/32, there are two CTC
co
channels – A and B. We can use any one of them or both. Let’s use OCR1A.
Example:
n.
OCR1A = 24999; // timer compare value
io
Example:
at
To flash an LED every 2 seconds, i.e. at a frequency of 0.5 Hz. We have an XTAL
uc
of 16 MHz.
Code:
#include <avr/io.h>
ed
#include <avr/interrupt.h>
// global variable to count the number of overflows
hi
void timer1_init()
{
a
TCNT1 = 0;
// enable overflow interrupt
w
31
www.sakshieducation.com
www.sakshieducation.com
{
// keep a track of number of overflows
tot_overflow++;
// check for number of overflows here itself
// 61 overflows = 2 seconds delay (approx.)
if (tot_overflow >= 61) // NOTE: '>=' used instead of '=='
{
PORTC ^= (1 << 0); // toggles the led
m
// no timer reset required here as the timer is reset every
time it overflows
co
tot_overflow = 0; // reset overflow counter
}
n.
}
int main(void)
io
{
// connect led to pin PC0
at
DDRC |= (1 << 0);
timer1_init();// initialize timer
uc
while(1)// loop forever
{
ed
// do nothing
// comparison is done in the ISR itself
}
hi
}
ks
TIMER2 is an 8-bit timer (like TIMER0); most of the registers are similar to
a
that of TIMER0 registers. Apart from that, TIMER2 offers a special feature which
.s
TCNT2 Register:
w
TCCR2 Register:
m
co
Fig: TCCR2 Register
In TIMER0/1 the prescalers available are 8, 64, 256 and 1024, whereas in
n.
TIMER2, we have 8, 32, 64, 128, 256 and 1024.
io
The bit 2:0 – CS22:20 are the Clock Select Bits of TIMER2. Their
selection is as follows.
Example:
w
Code:
w
#include <avr/io.h>
#include <avr/interrupt.h>
// global variable to count the number of overflows
volatile uint8_t tot_overflow;
// initialize timer, interrupt and variable
void timer2_init()
{
33
www.sakshieducation.com
www.sakshieducation.com
m
}
// TIMER0 overflow interrupt service routine called whenever TCNT0
co
overflows
ISR(TIMER2_OVF_vect)
n.
{
tot_overflow++;// keep a track of number of overflows
io
}
int main(void)
at
{
DDRC |= (1 << 0); // connect led to pin PC0
uc
timer2_init();// initialize timer
while(1) // loop forever
ed
{
// check if no. of overflows = 12
if (tot_overflow >= 12) // NOTE: '>=' is used
hi
{
ks
}
w
}
}
w
34
www.sakshieducation.com
www.sakshieducation.com
We had two timer values with us – Set Point (SP) and Process Value (PV).
In everytime, we used to compare the process value with the set point. Once
the process value becomes equal (or exceeds) the set point, the process value is
reset.
Example:
m
max = 39999; // max timer value set <--- set point
co
// some code here
// ...
n.
// ...
io
// TCNT1 <--- process value
at
if (TCNT1 >= max) // process value compared with the set point
uc
{
ed
}
hi
// ...
ks
Here, what we desire is that the timer (process value) should reset as soon as its
.s
value becomes equal to (or greater than) the set point (Maximum Value) of 39999.
w
So basically, the CTC Mode implements the same thing, but unlike the
above example, it implements it in hardware. Which means that we no longer need
w
to worry about comparing the process value with the set point every time! This will
w
not only avoid unnecessary wastage of cycles, but also ensure greater accuracy (i.e.
no missed compares, no double increment, etc).
Hence, this comparison takes place in the hardware itself, inside the AVR
CPU! Once the process value becomes equal to the set point, a flag in the
status register is set and the timer is reset automatically! Thus goes the name –
35
www.sakshieducation.com
www.sakshieducation.com
CTC – Clear Timer on Compare! Thus, all we need to do is to take care of the
flag, which is much faster to execute.
m
Let’s take up a problem to understand this concept. We need to flash an LED
co
every 100 ms. we have a crystal of XTAL 16 MHz.
n.
io
at
Now, given XTAL = 16 MHz, with a prescaler of 64, the frequency of the
clock pulse reduces to 250 kHz. With a Required Delay = 100 ms, we get the
uc
Timer Count to be equal to 24999. Up until now, we would have let the value of
the timer increment, and check its value every iteration, whether it’s equal to
ed
24999 or not, and then reset the timer. Now, the same will be done in hardware!
We won’t check its value every time in software! We will simply check whether
hi
WGM13:10. These bits are spread across both the TCCR1 registers (A and B).
w
Thus we need to be a bit careful while using them. Their selection is as follows:
w
Mode WGM1 WGM1 WGM11 WGM10 Timer/Counter Mode of operation Top Update of TOV1
3 2 (PWM1 (PWM1 OCR1x Flag Set
(CTC1) 1) 0) on
0 0 0 0 0 Normal 0xFFFF Immediate MAX
1 0 0 0 1 PWM, Phase Correct, 8-bit 0x00FF TOP BOTTOM
2 0 0 1 0 PWM, Phase Correct, 9-bit 0x01FF TOP BOTTOM
3 0 0 1 1 PWM, Phase Correct, 10-bit 0x03FF TOP BOTTOM
4 0 1 0 0 CTC OCR1A Immediate MAX
5 0 1 0 1 Fast PWM, 8-bit 0x00FF TOP TOP
36
www.sakshieducation.com
www.sakshieducation.com
m
13 1 1 0 1 Reserved - - -
14 1 1 1 0 Fast PWM ICR1 TOP TOP
15 1 1 1 1 Fast PWM OCR1A TOP TOP
co
Fig: Wave Generation Mode Bit Description
We can see that there are two possible selections for CTC Mode. Practically,
n.
both are the same, except the fact that we store the timer compare value in different
io
registers. Right now, let’s move on with the first option (0100). Thus, the
initialization of TCCR1A and TCCR1B is as follows.
at
TCCR1A |= 0; // not required since WGM11:0, both are zero (0)
uc
TCCR1B |= (1 << WGM12)|(1 << CS11)|(1 << CS10); // Mode = CTC,
ed
Prescaler = 64
We must tell the AVR to reset the timer as soon as its value reaches such
ks
and such value. So, the question is, how do we set such and such values? The
Output Compare Register 1A – OCR1A and the Output Compare Register 1B
a
Since the compare value will be a 16-bit value (in between 0 and 65535),
w
OCR1A and OCR1B are 16-bit registers. In ATMEGA16/32, there are two CTC
channels – A and B. We can use any one of them or both. Let’s use OCR1A.
w
w
Example:
TIFR Register:
37
www.sakshieducation.com
www.sakshieducation.com
m
match occurs i.e. TCNT1 becomes equal to OCR1A (or OCR1B). It is cleared
co
automatically whenever the corresponding Interrupt Service Routine (ISR) is
executed. Alternatively, it can be cleared by writing ’1′ to it!
n.
Code:
io
#include <avr/io.h>
// initialize timer, interrupt and variable
at
void timer1_init()
{
uc
// set up timer with prescaler = 64 and CTC mode
TCCR1B |= (1 << WGM12)|(1 << CS11)|(1 << CS10);
ed
// initialize counter
TCNT1 = 0;
hi
}
a
int main(void)
{
.s
// initialize timer
w
timer1_init();
// loop forever
w
while(1)
{
// check whether the flag bit is set if set, it means that there has been a
compare match and the timer has been cleared use this opportunity to toggle
the led
if (TIFR & (1 << OCF1A)) // NOTE: '>=' used instead of '=='
{
38
www.sakshieducation.com
www.sakshieducation.com
m
}
co
Using Interrupts with CTC Mode:
n.
In the previous methodology, we simply used the CTC Mode of operation.
io
We used to check every time for the flag bit (OCF1A). Now let’s shift this
responsibility to the AVR itself! Yes, now we do not need to check for the flag bit
at
at all! The AVR will compa
compare
re TCNT1 with OCR1A. Whenever a match occurs, it
sets the flag bit OCF1A, and also fires an interrupt! We just need to attend to that
uc
interrupt, that’s it.
ed
• Overflow,
hi
• Compare
ks
• Capture.
TIMSK Register:
w
w
w
39
www.sakshieducation.com
www.sakshieducation.com
Code:
m
#include <avr/io.h>
#include <avr/interrupt.h>
co
// initialize timer, interrupt and variable
void timer1_init()
{
n.
// set up timer with prescaler = 64 and CTC mode
TCCR1B |= (1 << WGM12)|(1 << CS11)|(1 << CS10);
io
TCNT1 = 0; // initialize counter
at
OCR1A = 24999;// initialize compare value
TIMSK |= (1 << OCIE1A);// enable compare interrupt
uc
sei();// enable global interrupts
}
// this ISR is fired whenever a match occurs hence, toggle led here
ed
itself..
ISR (TIMER1_COMPA_vect)
hi
{
PORTC ^= (1 << 0);// toggle led here
ks
}
int main(void)
a
{
DDRC |= (1 << 0);// connect led to pin PC0
.s
// do nothing
// whenever a match occurs, ISR is fired
w
40
www.sakshieducation.com
www.sakshieducation.com
In the pin configuration of ATMEGA16/32,we can see the pins PB3, PD4,
PD5 and PD7. Their special functions are mentioned in the brackets (OC0, OC1A,
OC1B and OC2). These are the Output Compare pins of TIMER0, TIMER1 and
TIMER2 respectively.
m
co
n.
io
Now time for us to concentrate on Bit 7:6 – COM1A1:0 and Bit 5:4 –
at
COM1B1:0 – Compare Output Mode for Compare Unit A/B. These bits
control the behavior of the Output Compare (OC) pins. The behavior changes
uc
depending upon the following modes:
COM1B1 COM1B0
.s
high level)
41
www.sakshieducation.com
www.sakshieducation.com
Code:
#include <avr/io.h>
#include <avr/interrupt.h>
m
// initialize timer, interrupt and variable
co
void timer1_init()
{
n.
// set up timer with prescaler = 64 and CTC mode
TCCR1B |= (1 << WGM12)|(1 << CS11)|(1 << CS10);
io
// set up timer OC1A pin in toggle mode
TCCR1A |= (1 << COM1A0);
at
// initialize counter
TCNT1 = 0;
uc
// initialize compare value
OCR1A = 24999;
ed
int main(void)
hi
{
DDRD |= (1 << 5); // connect led to pin PD5
ks
{
.s
// do nothing
// whenever a match occurs
w
}
w
42
www.sakshieducation.com
www.sakshieducation.com
m
co
• These bits are write only bits.
• They are active only in non-PWM mode.
n.
• For ensuring compatibility with future devices, these bits must be set
to zero (which they already are by default).
io
• Setting them to ‘1’ will result in an immediate forced compare match
at
and the effect will be reflected in the OC1A/OC1B pins.
• The thing to be noted is that FOC1A/FOC1B will not generate any
uc
interrupt, nor will it clear the timer in CTC mode.
ed
now.
TCCR0 Register:
a
.s
43
www.sakshieducation.com
www.sakshieducation.com
m
2 1 0 CTC OCR0 Immediate MAX
3 1 1 Fast PWM 0xFF TOP MAX
co
Table: Wave Generation Mode Bit Description
n.
• Bit 5:4 – COM01:00 – Compare Match Output Mode – They
control the behavior of the OC0 (PB3) pin
io
o depending upon the WGM mode –
at
non-PWM,
uc
Phase Correct PWM mode
ed
44
www.sakshieducation.com
www.sakshieducation.com
o For en
ensuring
suring compatibility with future devices, this bit must
be set to ‘0’.
OCR0 Register:
m
co
n.
Fig: OCR0 Register
io
The value to be compared (max 255) is stored in this register.
TIMSK Register:
at
uc
The Timer/Counter Interrupt Mask– TIMSK Register is as follows:
ed
hi
a ks
TIFR Register:
w
45
www.sakshieducation.com
www.sakshieducation.com
m
The Bit 1 – OCF0 – Output Compare Flag 0 is set whenever a compare
co
match occurs. It is cleared automatically whenever the corresponding ISR is
executed. Alternatively it is cleared by writing ‘1’ to it.
n.
AVR Timers – PWM Mode:
io
PWM is the technique used to generate analogue signals from a digital
at
device like a MCU. Almost all modern MCUs have dedicated hardware for PWM
signal generation.
uc
PWM can be used to control servo motors, perform DAC (Digital to
Analogue Conversion) etc.
ed
In PWM, we generate square waves whose duty cycle can be varied. Duty
a
cycle refers to the fraction of the time period of the wave for which the signal is in
.s
46
www.sakshieducation.com
www.sakshieducation.com
Frequency = (1/T)
m
co
n.
io
at
It has three compare output modes of operation:
uc
• Inverted Mode - In this mode, if the waveform value is greater than the
compare level, then the output is set high, or else the output is low.
ed
But it’s always not necessary that we have a fixed compare level. Those who
.s
have had exposure in the field of analog/digital communication must have come
across cases where a saw tooth carrier wave is compared with a sinusoidal
w
47
www.sakshieducation.com
www.sakshieducation.com
m
co
n.
io
at
uc
Fig: PWM Modulation
Duty Cycle:
ed
48
www.sakshieducation.com
www.sakshieducation.com
m
co
n.
io
at
uc
ed
hi
ks
We are very well aware that the AVR provides us with an option of 8 and 16
a
bit timers. 8bit timers count from 0 to 255, then back to zero and so on. 16bit
.s
timers count from 0 to 65535, then back to zero. Thus for a 8bit timer, MAX = 255
w
49
www.sakshieducation.com
www.sakshieducation.com
m
co
n.
io
at
uc
ed
compare match occurs. Due to this, the value of TOP can be reduced as shown in
w
2nd figure. The thick line shows how the timer would have gone in normal mode.
Now, the CTC Mode can be extended to introduce variable TOP as shown in
rd
3 figure.
50
www.sakshieducation.com
www.sakshieducation.com
• Fast PWM
• Phase Correct PWM
• Frequency and Phase Correct PWM
Fast PWM:
m
In simple terms, this is Fast PWM! We have a saw tooth waveform, and we
co
compare it with a fixed voltage level (say A), and thus we get a PWM output as
shown (in A).
n.
Now suppose we increase the compare voltage level (to, say B). In this case,
as we can see, the pulse width has reduced, and hence the duty cycle.
io
at
uc
ed
hi
a ks
.s
w
But, as you can see, both the pulses (A and B) end at the same time
w
In this mode, since saw tooth waveform is used, the timer counter TCNTn (n
= 0,1,2) counts from BOTTOM to TOP and then it is simply allowed to overflow
(or cleared at a compare match) to BOTTOM.
51
www.sakshieducation.com
www.sakshieducation.com
m
co
n.
io
at
uc
Here instead of a saw tooth waveform, we have used a triangular waveform.
Even here, you can see how PWM is generated. We can see that upon increasing
ed
the compare voltage level, the duty cycle reduces. But unlike Fast PWM, the phase
of the PWM is maintained. Thus it is called Phase Correct PWM.
hi
By visual inspection, we can clearly see that the frequency of Fast PWM is
ks
The datasheets say that there is no difference between 'phase correct' and
'phase and frequency correct' modes if we are not changing the value of TOP on
w
the fly. Since TOP is dictating our repeating frequency then we aren't changing it
w
So we will cover both of them with one discussion and will refer to them
both collectively as 'any phase correct' mode.
The major difference is that 'fast PWM mode' counted repeatedly from
BOTTOM to TOP to generate a saw tooth waveform whereas these 'any phase
52
www.sakshieducation.com
www.sakshieducation.com
correct modes' will count up from BOTTOM to TOP, and then from TOP to
BOTTOM so rather than a saw tooth they generate a triangular waveform:
m
co
n.
io
at
uc
Thus, for this, we need Frequency and Phase Correct PWM. Since in most
ed
cases the value of TOP remains same, it doesn’t matter which one we are choosing
– Phase Correct or Frequency and Phase Correct PWM.
hi
Making Choices:
ks
Now that we are familiar with all the PWM concepts, it’s up to you to decide
a
Choosing Timer:
w
w
53
www.sakshieducation.com
www.sakshieducation.com
Even 8bit is too much, but there is no other choice. Obviously there isn’t
much difference in speed between 123/256th and 124/256th of full speed in case of
a motor.
But if we use servo motors, you have to use 16bit timer. If we need quite
high resolution in your application, go for 16bit timer.
m
If we want to control the speed of DC motors or brightness of LEDs, go for
co
any one of them. But if we are using it for telecommunication purposes, or for
signal sampling, fast PWM would be better. For general applications, phase correct
n.
PWM would do.
io
Choosing Compare Output Modes
at
Out of the three modes, uc
• inverted,
• non-inverted
ed
• toggle mode,
the compare voltage, the duty cycle increases. However, you can choose any of
ks
them.
Analysis:
w
Given that
w
Frequency = 50 Hz
w
54
www.sakshieducation.com
www.sakshieducation.com
T (on) = 9 ms
T (off) = 11 ms
m
• Use Timer in CTC Mode
co
• Use Timer in PWM Mode
n.
Methodology – CTC Mode:
io
o For this application, we can choose any of the three timers
at
available in ATMEGA32.
• Choose a suitable prescaler.
uc
• Then set up the timer and proceed as usual.
ed
Note:The catch lies here is that you need to update the compare value of
OCRx register every time.
hi
Code:
ks
#include <avr/io.h>
#include <avr/interrupt.h>
a
// initialize counter
// initialize compare value
w
55
www.sakshieducation.com
www.sakshieducation.com
count++;
// check for the global counter
// if count == odd, delay required = 11 ms
// if count == even, delay required = 9 ms
// thus, the value of the OCRx should be constantly updated
if (count % 2 == 0)
OCRx = 9999; // calculate and substitute appropriate
value
m
else
OCRx = 10999; // calculate and substitute appropriate
co
value
}
n.
int main(void)
{
io
DDRC |= (1 << 0);// initialize the output pin, say PC0
timerX_init(); // initialize timerX
at
while(1) // loop forever
{
uc
// do nothing
}
ed
}
Methodology – PWM Mode:
hi
“everything”, is done by the AVR CPU. All we need to do is to initialize and start
the timer, and set the duty cycle.
a
TIMER0.
w
Here, we will learn how to set appropriate bits to run the timer in PWM
w
mode.
56
www.sakshieducation.com
www.sakshieducation.com
m
Mode WGM01 WGM00 Timer/Counter TOP Update of TOV0
(CTC0) (PWM0) Mode of OCR0 Flag Set-
co
operation on
0 0 0 Normal 0xFF Immediate MAX
n.
1 0 1 PWM, Phase 0xFF TOP BOTTOM
correct
io
2 1 0 CTC OCR0 Immediate MAX
3 1 1 Fast PWM 0xFF TOP MAX
at
Fig: Waveform Generation Mode Bit Description
uc
• Bit 5, 4 – COM01:0 – Compare Match Output Mode - These bits
are set in order to control the behavior of Output Compare pin (OC0)
ed
The following look up table to determine the operations of OC0 pin for Fast PWM
hi
mode.
ks
57
www.sakshieducation.com
www.sakshieducation.com
m
co
n.
io
at
Fig: Fast PWM
Now let me remind you that the AVR PWM is fully hardware controlled,
uc
which means that even the timer compare operation is done by the AVR CPU. All
we need to do is to tell the CPU what to do once a match occurs.
ed
The COM01:00 pins come into play here. We see that by setting it to “10″ or
hi
“11″, the output pin OC0 is either set or cleared (in other words, it determines
whether the PWM is in inverted mode, or in non-inverted mode).
ks
Similarly for Phase Correct PWM, the look up table and the waveforms go
a
like this.
.s
w
m
co
n.
io
at
Fig: Phase Correct PWM uc
Setting of COM01:00 to “10″ or “11″ determines the behavior of OC0 pin.
As shown in the waveforms, there are two instances – one during up-counting, and
ed
other during down-counting. The behavior is clearly described in the look up table.
Please note that OC0 is an output pin. Thus, the effects of WGM and COM
hi
won’t come into play unless the DDRx register is set properly.
ks
• Bit 2:0 – CS02:0 – Clock Select Bits - These bits are used to select
prescaler.
a
.s
We use this register to store the compare value. But when we use Timer0 in
PWM mode, the value stored in it acts as the duty cycle (obviously!). In the
w
problem statement, it’s given that the duty cycle is 45%, which means
w
Edit: Note
59
www.sakshieducation.com
www.sakshieducation.com
The following code discusses how to create a PWM signal of a desired duty
cycle. If we want to change its frequency, you need to alter the TOP value, which
can be done using the ICRx register (which is not supported by 8-bit timers). For
16-bit Timer1, it can be varied using ICR1A.
Code:
#include <avr/io.h>
m
#include <util/delay.h>
voidpwm_init()
co
{
// initialize TCCR0 as per requirement, say as follows
n.
TCCR0 |=
(1<<WGM00)|(1<<COM01)|(1<<WGM01)|(1<<CS00);
io
// make sure to make OC0 pin (pin PB3 for atmega32) as output
pin
at
DDRB |= (1<<PB3);
}
uc
void main()
{
ed
uint8_t duty;
duty = 115; // duty cycle = 45% of 255 = 114.75 = 115
// initialize timer in PWM mode
hi
pwm_init();
ks
// run forever
while(1)
{
a
OCR0 = duty;
.s
}
}
w
w
w
60
www.sakshieducation.com