0% found this document useful (0 votes)
14 views106 pages

Timer0

The document discusses timer/counter functionality in AVR microcontrollers, detailing various designs for counting and generating delays. It explains the architecture of timers, including registers like TCNT, TCCR, and OCR, as well as their roles in generating waveforms and managing interrupts. Additionally, it provides examples of programming timers for specific delays and generating square waves using assembly language.

Uploaded by

22026170
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views106 pages

Timer0

The document discusses timer/counter functionality in AVR microcontrollers, detailing various designs for counting and generating delays. It explains the architecture of timers, including registers like TCNT, TCCR, and OCR, as well as their roles in generating waveforms and managing interrupts. Additionally, it provides examples of programming timers for specific delays and generating square waves using assembly language.

Uploaded by

22026170
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 106

Timer/counter

Chapter 9
A counter register

UP Counter Register Load


COUT
A simple design (counting people)
First design

Sensor UP Counter Register Load


COUT 4

Comparator
=
A simple design (counting people)
Second design

Sensor UP Counter Register Load


COUT

$FC
A simple design (making delay)

UP Counter Register Load


COUT

$FC
A generic timer/counter
• Delay generating
• Counting
• Wave-form generating
• Capturing

Oscillator 0
Counter register
COUT
External 1
source
Flag
Counter/Timer
Timers in AVR
• 1 to 6 timers
– 3 timers in ATmega32
• 8-bit and 16-bit timers
– two 8-bit timers and one 16-bit timer in ATmega32
Timer in AVR
Oscillator
 TCNTn (Timer/Counter register) External
Counter register

source

TOVn (Timer Overflow flag) Counter/Timer
Flag


TCCRn (Timer Counter control register)

OCRn (output compare register) TCCRn

OCFn (output compare match flag)
TCNTn

TOVn
= OCFn
Comment:
Comment:
All
Allofofthe
thetimer
timerregisters
registersare
are
byte-addressable
byte-addressableI/O I/Oregisters
registers OCRn
Timer 0 (an 8-bit timer)
Timer 0
TCCR0

TCNT0

TOV0
= OCF0
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0 TIFR

OCR0
Timer Registers
 Three main registers in diagram, plus two more, to interact with this particular timer!
 TCCR controls the timer functioning, waveform generation mode (PWM, etc), and clock
prescaling!  TCNT contains the current clock value, which can be reset and changed at will.
Remember that this is incremented by the pre-scaled clock as configured by the TCCR register!
 OCR contains the target clock value at which time an interrupt should be generated or a
pin state should be changed!
 A fourth register, ASSR, which is not show on the functional diagram is used on this particular
timer to select between the internal and external clocks, as well as indicate when the timer is busy!
 TIMSK (Timer Interrupt MaSK), also not shown, is used to enable interrupts on specific timer
events!

14!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00 TCCR0

Clock
Timer Selector
Mode (WGM)
(CS)

CS02 CS01 CS00 Comment


0 0 0 No clock source (Timer/Counter stopped)
WGM00 WGM01 Comment
0 0 1 clk (No Prescaling)PSR10
0 0 Normal
0 1 0 clk / 8
0 1 CTC (Clear Timer on Compare Match)Clear
0 1 1 clk / 64 clkIO 10-bit T/C Prescaler
1 0 PWM, phase correct
1 0 0 clk / 256
1 1 Fast PWM

clk/8
clk/64
clk/256

clk/1024
1 0 1 clk / 1024
1 1 0 External clock source on T0 pin. Clock on falling edge T0
1 1 1 External clock source on T0 pin.
0 Clock on rising edge

CS00 0 1 2 3 4 5 6 7
CS01
CS02

Timer/Counter0 clock
source
II: Atmega8 – Basic features

8-bit Timer / Counter0

• 10-bit clock Prescaler


timer-clk (t0) = clk (IO) / prescaler

• External clock source T0 connected to PD4


cannot be prescaled, clk(ext) <= clk (IO) / 2.5
II: Atmega8 – Basic features

8-bit Timer / Counter0 - prescaler operation

No prescaler

MAX=0xff
BOTTOM=0

Prescaler = 8
II: Atmega8 – Basic features

8-bit Timer / Counter0 usage

Timer/Counter0 Control Register (TCCR0), Bits CS02-CS00


select Clock Source and Prescaler Value :
II: Atmega8 – Basic features

8-bit Timer / Counter0 usage

Timer/Counter0 Register (TCNT0) :


read/write, incremented per CLK cycle, overflow: 0xff

• A Reload-Value is used to fine-tune the interrupt interval

• write Reload-Value to TCNT0 in the ISR


II: Atmega8 – Basic features

8-bit Timer / Counter0 usage

Timer/Counter Interrupt Mask Register (TIMSK) :


Bit 0 : Timer 0 interrupt enable
set 1 to enable timer 0 overflow interrupt ( + I-Bit in SREG)

Timer Interrupt Flag Register (TIFR) :


TOV0 indicates a Timer0 overflow, cleared by hardware when
the ISR is executed or by writing 1 to the flag
Where does PSR10 come from?
Normal mode
TCNT0

0xFF
TOV TOV TOV
0 time

FF
FE TOV0: 0
1

2
1
0 TOV0 = 1
Example 1: Write a program that waits 14 machine
cycles in Normal mode.
UP Counter Register Load
14 = $0E COUT

$100 8

-$0E $F2
$F2

FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00 TCCR0

0 0 0 0 1
PSR10

WGM00 WGM01 Comment clkIO


Clear
10-bit T/C Prescaler

0 0 Normal

clk/8
clk/64
clk/256

clk/1024
0 1 CTC T0
0
1 0 PWM, phase correct
1 1 Fast PWM CS00 0 1 2 3 4 5 6 7
CS01
CS02

Timer/Counter0 clock
source
Example 1: write a program that waits 14 machine
cycles in Normal mode.
$100 FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00 TCCR0

-$0E OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0 TIFR

$F2
.INCLUDE "M32DEF.INC"

LDI R16,0x20 DDRB = 1<<5;


SBI DDRB,5 ;PB5 as an output
LDI R17,0 PORTB &= ~(1<<5); //PB5=0
OUT PORTB,R17 while (1)
BEGIN: LDI R20,0xF2
OUT TCNT0,R20 ;load timer0 {
LDI R20,0x01 TCNT0 = 0xF2;
OUT TCCR0,R20 ;Timer0,Normal mode,int clk
AGAIN: IN R20,TIFR Question:
Question: How
Howto
;read TIFR tocalculate
calculatethe= delay
the
TCCR0 delaygenerated
0x01; generated
SBRS by the
R20,TOVO ;if TOV0 is timer?
set skip next
by the timer? while((TIFR&(1<<TOV0))==0);
inst.
RJMP AGAIN TCCR0 = 0;
LDI R20,0x0 Answer:
Answer: TIFR = (1<<TOV0);
OUT TCCR0,R20 1) ;stop Timer0
LDI R20,(1<<TOV0) 1)Calculate
Calculate
;R20
how much a machine
= 0x01how much aPORTB
machine clock
clocklasts.
lasts.
= PORTB^(1<<5);
OUT TIFR,R20 T=
T= 1/f
1/f TOV0 flag
;clear
}
2) Calculate
2) ;toggle
Calculate how many
manymachine
machineclocks
clocksititwaits.
EOR R17,R16 D5 how
of R17 waits.
OUT PORTB,R17 3)
3)Delay
Delay==PB5
;toggle TT**number
numberof
ofmachine
machinecycles
cycles
RJMP BEGIN
In example 1 calculate the delay. Imagine XTAL = 10
MHz.

.INCLUDE "M32DEF.INC"
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,0x01
OUT TCCR0,R20 ;Timer0,Normal mode,int clk
$100 AGAIN: IN R20,TIFR ;read TIFR
SBRS R20,0 ;if TOV0 is set skip next inst.
-$F2 RJMP AGAIN
LDI R20,0x0
$0E = 14 OUT TCCR0,R20 ;stop Timer0
LDI R20,0x01
3) Calculating delay OUT TIFR,R20 ;clear TOV0 flag

14 * 0.1µs = 1.4 0µs EOR R17,R16 ;toggle D5 of R17


OUT PORTB,R17 ;toggle PB5
RJMP BEGIN
Accurate calculating
Other than timer, executing the instructions consumes time; so if we
want to calculate the accurate delay a program causes we should add
the delay caused by instructions to the delay caused by the timer
LDI R16,0x20
SBI DDRB,5
LDI R17,0
OUT PORTB,R17
BEGIN: LDI R20,0xF2 1
OUT TCNT0,R20 1
LDI R20,0x01 1
OUT TCCR0,R20 1
AGAIN: IN R20,TIFR 1
SBRS R20,0 1/2
RJMP AGAIN 2
LDI R20,0x0 1
OUT TCCR0,R20 1
LDI R20,0x01 1
OUT TIFR,R20 1
EOR R17,R16 1
OUT PORTB,R17 1
RJMP BEGIN 2
18
Delay caused by timer = 14 * 0.1µs = 1.4 µs Delay caused by instructions = 18 * 0.1µs = 1.8
Total delay = 3.2 µs  wave period = 2*3.2 µs = 6.4 µs  wave frequency = 156.25 KHz
Finding values to be loaded into the timer
1. Calculate the period of clock source.
– Period = 1 / Frequency
• E.g. For XTAL = 8 MHz  T = 1/8MHz
2. Divide the desired time delay by period of
clock.
3. Perform 256 - n, where n is the decimal value
we got in Step 2.
4. Set TCNT0 = 256 - n
Example 2: Assuming that XTAL = 10 MHz, write a program to generate a
square wave with a period of 10 us on pin PORTB.3.
• For a square wave with T = 10 µs we must have a time delay of 5 µs. Because XTAL = 10
MHz, the counter counts up every 0.1 µs. This means that we need 5 µs / 0.1 µs = 50
clocks. 256 - 50 = 206.
.INCLUDE "M32DEF.INC"
DDRB = 1<<3;
LDI R16,0x08
PORTB &= ~ (1<<3);
SBI DDRB,3 ;PB3 as an output
LDI R17,0 while (1)
OUT PORTB,R17
{
BEGIN: LDI R20,206
OUT TCNT0,R20 ;load timer0 TCNT0 = 206;
LDI R20,0x01
TCCR0 = 0x01;
OUT TCCR0,R20 ;Timer0,Normal mode,int clk
AGAIN: IN R20,TIFR ;read TIFR while((TIFR&0x01) == 0);
SBRS R20,TOV0 ;if TOV0 is set skip next
RJMP AGAIN TCCR0 = 0;
LDI R20,0x0 TIFR = 1<<TOV0;
OUT TCCR0,R20 ;stop Timer0
LDI R20,0x01 PORTB = PORTB ^ (1<<3);
OUT TIFR,R20 ;clear TOV0 flag }
EOR R17,R16 ;toggle D3 of R17
OUT PORTB,R17 ;toggle PB3
RJMP BEGIN
Example 3: Modify TCNT0 in Example 2 to get the largest time delay possible with no prescaler.
Find the delay in µs. In your calculation, do not include the overhead due to instructions.
• To get the largest delay we make TCNT0 zero. This will count up
from 00 to 0xFF and then roll over to zero.
.INCLUDE "M32DEF.INC"
DDRB = 1 << 3;
LDI R16,1<<3
SBI DDRB,3 ;PB3 as an output PORTB &= ~(1<<3);
LDI R17,0
OUT PORTB,R17 while (1)
BEGIN: LDI R20,0x0 {
OUT TCNT0,R20 ;load Timer0
LDI R20,0x01 TCNT0 = 0x0;
OUT TCCR0,R20 ;Timer0,Normal mode,int clk TCCR0 = 0x01;
AGAIN: IN R20,TIFR ;read TIFR
SBRS R20,TOV0 ;if TOV0 is set skip next
RJMP AGAIN Solution while((TIFR&(1<<TOV0))==0);
LDI R20,0x0 TCCR0 = 0;
OUT TCCR0,R201) Calculating T:
;stop Timer0
LDI R20,0x01 TIFR = 0x01;
OUT TIFR,R20 T = 1/f = ;clear
1/10MHzTOV0= 0.1µs
flag PORTB = PORTB^(1<<3);
EOR R17,R16 ;toggle D3 of R17
OUT PORTB,R17 2) Calculating
;toggle delay
PB3 }
RJMP BEGIN
256 * 0.1µs = 25.6µs
Generating Large Delays
• Using loop
• Prescaler
• Bigger counters
Prescaler and generating a large time delay

PSR10

Clear
clkIO 10-bit T/C Prescaler

clk/8

clk/256
clk/64

clk/1024
T0
0

CS00 0 1 2 3 4 5 6 7
CS01
CS02

Timer/Counter0 clock
source
CTC (Clear Timer on Compare match) mode
TCNT0
0xFF
OCR0

OCF0 OCF0 OCF0


0 time

OCR0 0
xx TOV0:

2 0
1
OCF0:
1
TOV0 = no change
0
OCF0 = 1
Example 4: Rewrite example 2 using CTC
Rewrite example 2 using CTC
FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00 TCCR0

OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0 TIFR

• For a square wave with T = 10 µs we must have a time delay of 5 µs. Because XTAL = 10
MHz, the counter counts up every 0.1 µs. This means that we need 5 µs / 0.1 µs = 50
clocks. Therefore, we have OCR0= 49.
.INCLUDE "M32DEF.INC" DDRB |= 1<<3;
LDI R16,0x08
PORTB &= ~(1<<3);
SBI DDRB,3 ;PB3 as an output
LDI R17,0 while (1)
OUT PORTB,R17
{
LDI R20,49
OUT OCR0,R20 ;load timer0 OCR0 = 49;
BEGIN: LDI R20,0x09
OUT TCCR0,R20 ;Timer0,CTC mode,int clk TCCR0 = 0x09;
AGAIN: IN R20,TIFR ;read TIFR
SBRS R20,OCF0 ;if OCF0 is set skip next while((TIFR&(1<<OCF0))==0);
RJMP AGAIN
LDI R20,0x0 TCCR0 = 0; //stop timer0
OUT TCCR0,R20 ;stop Timer0 TIFR = 0x02;
LDI R20,0x02
OUT TIFR,R20 ;clear OCF0 flag PORTB.3 = ~PORTB.3;
EOR R17,R16 ;toggle D3 of R17 }
OUT PORTB,R17 ;toggle PB3
RJMP BEGIN
Timer2
• Timer0 • Timer2
TCCR0 TCCR2

TCNT0 TCNT2

TOV0 TOV2
= OCF0 = OCF2

OCR0 OCR2

OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0 TIFR


The difference between Timer0 and Timer2
• Timer0 • Timer2

CS02 CS01 CS00 Comment CS22 CS21 CS20 Comment


0 0 0 Timer/Counter stopped 0 0 0 Timer/Counter stopped
0 0 1 clk (No Prescaling) 0 0 1 clk (No Prescaling)
0 1 0 clk / 8 0 1 0 clk / 8
0 1 1 clk / 64 0 1 1 clk / 32
1 0 0 clk / 256 1 0 0 clk / 64
1 0 1 clk / 1024 1 0 1 clk / 128
1 1 0 External clock (falling edge) 1 1 0 clk / 256
1 1 1 External clock (rising edge) 1 1 1 clk / 1024
Timer 1
OCR1BH OCR1BL

= OCF1B

TCCR1A TCCR1B TCNT1H TCNT1L

TOV1 = OCF1A
OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0 TIFR

OCR1AH OCR1AL
COM1A1 COM1A0 COM1B1 COM1B0 FOC1A FOC1B WGM11 WGM10 TCCR1A

ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10 TCCR1B

Clock Selector (CS)

CS12 CS11 CS10 Comment


0 0 0 No clock source (Timer/Counter stopped)
PSR10
0 0 1 clk (No Prescaling)
0 1 0 clk / 8 clkIO
Clear
10-bit T/C Prescaler
0 1 1 clk / 64
1 0 0 clk / 256

clk/8

clk/64
clk/256

clk/1024
1 0 1 clk / 1024 T1
1 1 0 External clock source on T0 pin. Clock on falling edge
1 1 1 External clock source on0T0 pin. Clock on rising edge

CS10 0 1 2 3 4 5 6 7
CS11
CS12

Timer/Counter1 clock
source
16 – bit Timer / Counter 1

● Two Independent Output Compare Units


● can be used as Pulse Width Modulator (PWM)
● Clear Timer on Compare Match (Auto Reload)
● One Input Capture Unit
● can be used as External Event Counter
● Four Independent Interrupt Sources
TOV1, OCF1A, OCF1B, and ICF1

AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
16 – bit Timer / Counter 1
● TCNT1, OCR1A,
OCR1B and ICR1
are 16-bit registers

● write high byte first


read low byte first
(automatically done in C)

● clocking via prescaler or


external clock on pin T1

● output compare register


OCR1A/B can be used
for PWM generation
(output pin: OC1A/B)
or for interrupt request

AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
16 – bit Timer / Counter 1
● Input capture Unit: timestamp external events on ICP1 pin (or on Analog comp.)
Can generate Input Capture Interrupt

AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
16 – bit Timer / Counter 1
● Output Compare Units: compare TCNT1 with OCR1A and OCR1B
Can generate Output Capture Interrupt

● 13 PWM / Waveform
generation modes

● Top and Bottom values

● Auto reload

AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
16 – bit Timer / Counter 1
● Mode configuration using TCCR1A and TCCR1B

PWM Mode, set/clear/toggle of OC1A/B, auto-reload, Noise canceller

Find Details in the ATmega8 datasheet !

AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
16 – bit Timer / Counter 1
● Clock source configuration using TCCR1B

AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Assuming XTAL = 10 MHz write a program that toggles
PB5 once per millisecond, using Normal mode.
XTALLDI = 10 MHz
.INCLUDE "M32DEF.INC"
 1/10 MHz
R16,HIGH(RAMEND) ;init=stack
0.1 pointer
µs
Num.OUT
LDI of machine
SPH,R16
cycles = 1 ms / 0.1 µs = 10,000
R16,LOW(RAMEND)
TCNT1
OUT
SBI = 65,536
DDRB,5 – 10,000 ;PB5
SPL,R16
= 55,536 = $D8F0
as an output
BEGIN:SBI PORTB,5 ;PB5 = 1
RCALL DELAY_1ms
CBI PORTB,5 ;PB5 = 0
RCALL DELAY_1ms TCNT1H TCNT1L
RJMP BEGIN

DELAY_1ms:
LDI R20,HIGH(-10000)
R20,0xD8
OUT TCNT1H,R20
TCNT1H,R20 ;TEMP = 0xD8
LDI R20,R20,0xF0
,LOW(-10000)
OUT TCNT1L,R20
TCNT1L,R20 ;Timer1 overflows
;TCNT1L after
= 0xF0, 10000
TCNT1H machine cycles
= TEMP
LDI R20,0x0
OUT TCCR1A,R20 ;WGM11:10=00
LDI R20,0x1
OUT TCCR1B,R20 ;WGM13:12=00,CS=CLK
AGAIN:IN R20,TIFR ;read TIFR
SBRS R20,TOV1 ;if OCF1A is set skip next instruction
RJMP AGAIN
LDI R20,1<<TOV1
OUT TIFR,R20 ;clear TOV1 flag
LDI R19,0
OUT TCCR1B,R19 ;stop timer
OUT TCCR1A,R19 ;
RET
TEMP register
Data bus (8-bit)

TEMP (8-bit)

OCR1xH (8-bit) OCR1xL (8-bit) TCNT1H (8-bit) TCNT1L (8-bit)

OCR1x (16-bit Register) TCNT1 (16-bit Counter)

OCR1xH buf. OCR1xL buf.


Note: OCR1x is OCR1A or OCR1B
OCR1x buffer (16-bit Register)

LDI R20,0xF3
IN R20,TCNT1L
a = TCNT1L;
TCNT1H = 0xF3;
OUT TCNT1H,R20
IN R21,TCNT1H
b = TCNT1H;
TCNT1L = 0x53;
LDI R20,0x53
OUT TCNT1L,R20
Assuming XTAL = 10 MHz write a program that toggles
PB5 once per millisecond, using CTC mode.
.INCLUDE "M32DEF.INC"
LDI R16,HIGH(RAMEND)
OUT SPH,R16
LDI R16,LOW(RAMEND)
OUT SPL,R16
SBI DDRB,5 ;PB5 as an output
BEGIN:SBI PORTB,5 ;PB5 = 1
RCALL DELAY_1ms
CBI PORTB,5 ;PB5 = 0
RCALL DELAY_1ms
RJMP BEGIN

DELAY_1ms:
LDI R20,0x00
OUT TCNT1H,R20 ;TEMP = 0
OUT TCNT1L,R20 ;TCNT1L = 0, TCNT1H = TEMP

LDI R20,0x27
OUT OCR1AH,R20 ;TEMP = 0x27
LDI R20,0x0F
OUT OCR1AL,R20 ;OCR1AL = 0x0F, OCR1AH = TEMP

LDI R20,0x0
OUT TCCR1A,R20 ;WGM11:10=00
LDI R20,0x09
OUT TCCR1B,R20 ;WGM13:12=01,CS=CLK
AGAIN:
IN R20,TIFR ;read TIFR
SBRS R20,OCF1A ;if OCF1A is set skip next instruction
RJMP AGAIN
LDI R20,1<<OCF1A
OUT TIFR,R20 ;clear OCF1A flag
LDI R19,0
OUT TCCR1B,R19 ;stop timer
OUT TCCR1A,R19 ;
RET
Counting
PSR10
Counting
Clear
clkIO 10-bit T/C Prescaler

clk/8

clk/256
clk/64

clk/1024
T0
0

CS00 0 1 2 3 4 5 6 7
CS01 T0

CS02

Timer/Counter0 clock
source

7
Example Assuming that clock pulses are fed into pin T0, write a program for counter 0
in normal mode to count the pulses on falling edge and display the state of the TCNT0
count on PORTC.
PSR10

Clear
clkIO 10-bit T/C Prescaler
.INCLUDE "M32DEF.INC"

clk/8
clk/64
clk/256

clk/1024
CBI DDRB,0 ;make T0 (PB0) input
LDI R20,0xFF T0

OUT DDRC,R20 ;make PORTC output 0

LDI R20,0x06
OUT TCCR0,R20 ;counter, falling edgeCS00 0 1 2 3 4 5 6 7
CS01
AGAIN: CS02
IN R20,TCNT0
OUT PORTC,R20 ;PORTC = TCNT0 Timer/Counter0 clock
IN R16,TIFR source

SBRS R16,TOV0
RJMP AGAIN ;keep doing it
LDI R16,1<<TOV0
OUT TIFR, R16
FOC0RJMP
WGM00 AGAIN
COM01 COM00 WGM01 ;keep
CS02 doing
CS01 itCS00 TCCR0
Assuming that clock pulses are fed into pin T1. Write a program for counter 1 in CTC
mode to make PORTC.0 high every 100 pulses.

.INCLUDE "M32DEF.INC"
CBI DDRB,1 ;make T1 (PB1) input
SBI DDRC,0 ;PC0 as an output
LDI R16, 0X01
LDI R17, 0
LDI R20,0x0
OUT TCCR1A,R20
LDI R20,0x0E
OUT TCCR1B,R20 ;CTC, counter, falling edge
AGAIN:
LDI R20,0
OUT OCR1AH,R20 ;TEMP = 0
LDI R20,99
OUT OCR1AL,R20 ;ORC1L = R20, OCR1H = TEMP
L1: IN R20,TIFR
SBRS R20,OCF1A
RJMP L1 ;keep doing it
LDI R20,1<<OCF1A ;clear OCF1A flag
OUT TIFR, R20
EOR R17,R16 ;SBI PORTC,0 ;PC0 = 1
OUT PORTC, R17 ;CBI PORTC,0 ;PC0 = 0
RJMP AGAIN ;keep doing it
Interrupt
Chapter 10
Contents
• Polling Vs. interrupt
• Interrupt unit
• Steps in executing an interrupt
• Edge trigger Vs. Level trigger in external
interrupts
• Timer interrupt
• Interrupt priority
• Interrupt inside an interrupt
• Task switching and resource conflict
• C programming
Polling Vs. Interrupt
• Interrupt
• Polling – Efficient CPU use
– Ties down the CPU – Has priority
– Can be masked

main( )
{
while (true) Do your common task
{ }
if(PIND.2 == 0)
//do something; whenever PIND.2 is 0 then
} do something
Real Time
Systems
Interrupts

3!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Real Time Systems

” A real-time system is one in which the correctness of the computations


not only depends upon the logical correctness of the computation but also
upon the time at which the result is produced. If the timing constraints of
the system are not met, system failure is said to have occurred. " !
! Donald Gillies, UBC!

 POSIX 1003.1 states: “Realtime in operating systems: the ability of the


operating system to provide a required level of service in a bounded
response time”!
 There are two major classifications of Real Time:!
 Hard Real Time is when a task not being completed at the required time
causes the operation to fail!
 Example: A bottle arrives late to the filling nozzle in a bottling plant, causing the
product to be deposited on the conveyor belt and not into the bottle!

 Soft Real Time is when a task not being completed at the desired time causes, for
example, a decrease in system efficiency, but does not result in total failure!
 Example: A bottle arrives early to the filling nozzle, causing the bottle to have to wait until the
nozzle can fill it!

4!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Interrupts

 How do we stop whatever else the processor is doing at


the appropriate time to “focus” on the time-critical
task?!
 Interrupts!!
 low-level CPU function!
 External stimulus to the active computations!
 Interrupt Request or IRQ!
 Causes the CPU to halt the current execution sequence and
jump the program counter to a specific address!
 Address is called the Interrupt Vector!
 Interrupt Vector points to a section of your code that
performs whatever actions are required upon that specific

IRQ!
This function is called a handler or Interrupt Service Routine (ISR)! 
Upon completion of the ISR, the CPU resumes normal
program execution from where it left off!
5!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Interrupts - Context Switch

 How does the processor switch to the ISR?!


 Move the CPU working registers and Program Counter into
RAM, !  Repeat above step in reverse to restore the CPU to
the pre-IRQ state once the ISR completes!
 This entire process takes a non-trivial amount of time,
sometimes on the order of 10s-100s of CPU cycles. See the
datasheet for more details.!  Sometimes the CPU hardware will
assist with the context switch, but often the software is
responsible!
 The AVR-GCC compiler implements the required software automatically in
its libraries.!

 IRQ Sources!
 Internal Timers (compared to a specific value or upon
overflow)!  External IRQ (a special Input pin function)!
 Other Peripherals (UART, I2C, SPI, ADC, Comparator, etc)!
6!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Interrupt Preemption
 It is possible that on a particular system there would be
multiple real-time tasks, with some tasks being more time
critical than others!

 Simple Buoy example:!


 The ADC can interrupt when its buffer is full, requiring
immediate attention to avoid data loss (hard real time)!
 The compact flash can also interrupt when it is ready for
more data to write, however this is a soft real time task.!
 If the ADC signaled while the ISR was running for the
compact flash, you would want:!
 to run the ISR for the ADC
immediately!  then return to the
compact flash ISR!  and then resume
normal operation.!

9!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Interrupt Preemption
 This is called preemption, and can get extremely complex!
 Some processors have a hierarchy of IRQ priorities, which
can specify which IRQ preempt which ISRs!
 Other processors do not have this feature, making
preemption quite difficult.!
 Some processors will automatically disable all interrupts
while one ISR is running (like the AVR Series). In this case,
you must manually re- enable global interrupts at the
beginning of the ISR for preemption to be possible at all!

 Preemption is often required for real time systems that have


both soft and hard components, as well as those with multiple
interrupt sources of non-equivalent priority!

10!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
II: Atmega8 – Basic features
II: Atmega8 – Basic features

Interrupt Processing

● several Interrupt Sources:


External Interrupts, Timer, Bus-Peripherals,
ADC, EEPROM

● individual Interrupt-Enable bits in the SFR‘s

● global interrupt enable Bit in SREG,


set with sei() and clear with cli() instruction

● flagged (remembered) and non-flagged interrupt sources

● lowest addresses in program memory reserved


for the interrupt vector table

● higher priority interrupts have lower addresses


II: Atmega8 – Basic features
II: Atmega8 – Basic features

Reset-Vector and
Interrupt-Vectors

● Word addresses
0, 1 – 19 in Flash Ram

● When a reset or
interrupt occurs,
the CPU calls
the address

● Install an Interrupt
Handler: modify
the vector table to
jump to your user-
handler

● return from interrupt:


reti
II: Atmega8 – Basic features

Reset-Vector and
Interrupt-Vectors

● example shows
full featured
vector table

● 19 handlers installed

● program execution
after reset:
jmp RESET ($013)

● Main program is
located at $013,
beyond the vectors
II: Atmega8 – Basic features

Reset- and Interrupt- Vectors

● Reset vector can be set to the Bootloader section using the


BOOTRST fuse bit

● Interrupt vectors can be set to the Bootloader


section using the IVSEL bit of the General Interrupt Contol Register
II: Atmega8 – Basic features

AVR Reset Sources:


II: Atmega8 – Basic features

Reset Sources:

• Power-on Reset: supply voltage is


below the Power-on Reset threshold

• External Reset: low level is present on

/RESET – input pin

• Watchdog Reset: Watchdog Timer


enabled and period expires

• Brown-out Reset: Brown-out Detector


enabled and supply voltage below
threshold

MCUCSR provides information on which reset source caused a CPU reset


II: Atmega8 – Basic features

Reset Voltage Thresholds


II: Atmega8 – Basic features

Reset Voltage Thresholds:

Example:
Power-on Reset

Example:
Brown Out Reset
Interrupt unit
TIFR OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0

TIMSK
SREGOCIE2 ITOIE2 T TICIE1
H OCIE1A
S OCIE1B
V TOIE1
N Z OCIE0C TOIE0

RAM EEPROM Timers


GICR INT1 INT0 INT2 - - - IVSEL IVCE
PROGRAM
ROM
40 PIN DIP
Program
(XCK/T0) PB0 1Bus 40 Bus
PA0 (ADC0)
CPU
(T1) PB1 2 39 PA1 (ADC1)
(INT2/AIN0) PB2 3 SREG 38 PA2 (ADC2)
(OC0/AIN1) PB3 4 MEGA32 37 PA3 (ADC3)
(SS) PB4 5 36 PA4 (ADC4)
(MOSI) PB5 6 35 PA5 (ADC5)TIMSK
GICR
Other
(MISO) PB6 7 OSC34 PA6 (ADC6)Interrupt Ports
Peripherals
(SCK) PB7 8 33 PA7 (ADC7)Unit
RESET 9 32 AREF
I/O
VCC 10 31 AGND
PINS
GND 11 30 AVCC
XTAL2 12 29 PC7 (TOSC2)
XTAL1 13 28 PC6 (TOSC1)
(RXD) PD0 14 27 PC5 (TDI)
(TXD) PD1 15 26 PC4 (TDO)
(INT0) PD2 16 25 PC3 (TMS)
(INT1) PD3 17 24 PC2 (TCK)
(OC1B) PD4 18 23 PC1 (SDA)
(OC1A) PD5 19 22 PC0 (SCL)
(ICP) PD6 20 21 PD7 (OC2)
Example: AtMega128 Interrupts

7!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Steps in executing an interrupt
Addres Code
PB0 1 40 VCC s .INCLUDE "M32DEF.INC"
PB1 2 39 PA0 (ADC0) .ORG 0 ;location for reset
0002 0000 JMP MAIN
(INT2) PB2 3 38 PA1 (ADC1)
.ORG 0x02 ;location for external
(OC0/AIN0) 4 37 PA2 (ADC2) INT0
PB3 JMP EX0_ISR
(SS) PB4 5 ATmega3 36 PA3 (ADC3) 0002
MAIN: LDI R20,HIGH(RAMEND)
(MOSI) PB5 PA4 (ADC4)
(MISO) PB6
6
7
2 35
34 PA5 (ADC5)
0002
OUT
LDI
SPH,R20
R20,LOW(RAMEND)
(SCK) PB7 8 PC 0016
0015
0014
0013
0012
000D
0009
000A
000B
000C
0006
0008
000F
0004
000E
0007
0005
0000 33 PA6 (ADC6) OUT SPL,R20
0004 SBI DDRC,3 ;PC.3 =
RESET 9 : 32 PA7 (ADC7) 0005 output
VCC 10 31 AGND 0006 SBI PORTD,2 ;pull-up
0007 activated
GND 11 30 AVCC LDI R20,1<<INT0 ;Enable
0008
XTAL2 12 29 PC7 (TOSC2) INT0
0009 OUT GICR,R20
XTAL1 13 28 PC6 (TOSC1) 000A SEI ;Set I (Enable
(RXD) PD0 14 27 PC5 (TDI) 000F
000B Interrupts)
(TXD) PD1 15
S 26 PC4 (TDO)
000C LDI R30, 3
000D LDI R31, 4
(INT0) PD2 16 P 25 PC3 (TMS)
000E ADD R30, R31
(INT1) PD3 17 24 PC2 (TCK) 000F HERE:JMP HERE
0010
(OC1B) PD4 18 Stac 23 PC1 (SDA)
EX0_ISR:IN R21,PORTC
(OC1A) PD5 PC0 (SCL)
19 k 22 LDI R22,0x08
(ICP) PD6 20 21 PD7 (OC2) 0012 EOR R21,R22
0013 OUT PORTC,R21
RETI
0014
0015
Interrupt Example Code
 Several steps are necessary on the ATmega to enable interrupts!
 The control register that is responsible for the interrupt you desire must be
configured to generate an IRQ upon an event!
 An ISR must be defined!
 Global Interrupts must be enabled!

Software example to interrupt on an external pin!

#include <io.h>
#include <signal.h>
#include <interrupt.h>

 SIGNAL(SIG_INTERRUPT0) /* signal handler for external interrupt int0 */


{
/* Do whatever you want to have happen during the interrupt here */
}

int main(void) {

DDRB = 0x00; /* use Port D for input*/


EIMSK = (1<<INT0); /* Enable external interrupt 0 */ sei(); /*
enable interrupts */

for (;;) { /*Your main loop here */ }


} 8!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
II: Atmega8 – Basic features

External Interrupts Int0 and Int1:

• Int0 connected to PD2


• Int1 connected to PD3
• asynchronous operation: can wake up CPU
• rising/falling edge or low level can trigger interrupt,
defined by Interrupt Sense control – bits of MCUCR SFU
II: Atmega8 – Basic features

External Interrupts Int0 and Int1:

• Int0 and Int1 have to be enabled by the GICR (+ I-bit in SREG)

• flagged interrupts: General Interrupt Flag Register (GIFR)


indicates when an interrupt request happened

• flags are cleared by executing the interrupt service routine (ISR)


or by writing 1 to the flag bit of GIFR
Edge trigger Vs. Level trigger in external interrupts
MCUCR SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00

LDI R20,0x02 ;falling


OUT MCUCR,R20
Edge trigger Vs. Level trigger (Cont.)
MCUCSR JTD ISC2 - JTRF WDRF BORF EXTRF PORF
Timers Interrupts
 Timers are counters that are incremented on a clock tick, or
after a certain number of clock ticks!
 Clock Sources, availability dependent on peripheral!
 Main Oscillator (16MHz / 8MHz)!
 Watch Crystal
(32.768KHz)!  External
Clock!
 Often Scaled internally!
 Factors of 1, 8, 64, 256, 1024 on AVR!

 Interrupts, flags, and pin state changes can be generated on


timer overflow or compare!
 High resolution timers by comparing with a target
value!  Long running timers by counting overflows! 
Pulse-Width Modulation!

12!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
II: Atmega8 – Basic features

8-bit Timer / Counter0 for AVR 8

• 10-bit clock Prescaler


timer-clk (t0) = clk (IO) / prescaler

• External clock source T0 connected to PD4


cannot be prescaled, clk(ext) <= clk (IO) / 2.5
8-bit Timer Peripheral

Sample 8-bit Timer on the ATmega128!

<- Timer control register (TCCR)!

External!
Oscillator!
Current
Timer! Value
(TCNT)!

Output Compare! Waverform Generator!


(OCR)!

13!
II: Atmega8 – Basic features

8-bit Timer / Counter0 - prescaler operation

No prescaler

MAX=0xff
BOTTOM=0

Prescaler = 8
II: Atmega8 – Basic features

8-bit Timer / Counter0 usage

Timer/Counter0 Control Register (TCCR0), Bits CS02-CS00


select Clock Source and Prescaler Value :
II: Atmega8 – Basic features

8-bit Timer / Counter0 usage

Timer/Counter0 Register (TCNT0) :


read/write, incremented per CLK cycle, overflow: 0xff

• A Reload-Value is used to fine-tune the interrupt interval

• write Reload-Value to TCNT0 in the ISR


II: Atmega8 – Basic features

8-bit Timer / Counter0 usage

Timer/Counter Interrupt Mask Register (TIMSK) :


Bit 0 : Timer 0 interrupt enable
set 1 to enable timer 0 overflow interrupt ( + I-Bit in SREG)

Timer Interrupt Flag Register (TIFR) :


TOV0 indicates a Timer0 overflow, cleared by hardware when
the ISR is executed or by writing 1 to the flag

Using Timer0 overflow interrupt
This program uses Timer0 to generate a square +5
ATmega32

PORTB.5

wave on pin PORTB.5, while at the same time


data is being transferred from PORTC to PORTD. 8
PORTD PORTC
8

1 ;Program 10-1 18 int.


Timer LDI R20,(1<<TOIE0)
2 .INCLUDE "M32DEF.INC" 19
init. OUT TIMSK,R20
3 .ORG 0x0 ;location for reset 20 SEI
4 JMP MAIN 21 LDI R20,-32 ;value for 4µs
5 .ORG 0x16 ;loc. for Timer0 over. 22 OUT TCNT0,R20
Timer
23 init.
6 JMP T0_OV_ISR LDI R20,0x01
7 ;----main program for initialization 24 OUT TCCR0,R20
8 .ORG 0x100 25 HERE: IN R20,PINC
9 MAIN: LDI R20,HIGH(RAMEND) 26 OUT PORTD,R20
10 OUT SPH,R20 27 JMP HERE
11 LDI R20,LOW(RAMEND) 28 ;--------ISR for Timer 0
12 OUT SPL,R20 29 T0_OV_ISR:
13 SBI DDRB,5 ;output 30 IN R16,PORTB
14 LDI R20,0 31 LDI R17,0x20
15 OUT DDRC, R20 32 EOR R16,R17
16 LDI R20,0xFF 33 OUT PORTB,R16
17 OUT DDRD, R20 34 RETI
Timer0 compare match interrupt

.INCLUDE using Timer0 and CTC mode generate a square wave on pin PORTB.5, while at the same time
"M32DEF.INC"
.ORG data is being transferred
0x0 ;location from
forPORTC to PORTD.
reset
JMP MAIN
.ORG 0x14 ;location for Timer0 compare match
JMP T0_CM_ISR
;-main program for initialization and keeping CPU busy
.ORG 0x100
MAIN: LDI R20,HIGH(RAMEND) Time (µS)
OUT SPH,R20
LDI R20,LOW(RAMEND)
OUT SPL,R20 HERE: IN R20,PINC
LDI R20,39 OUT PORTD,R20
Timer init. OUT OCR0,R20 ;OCR0 = 39 JMP HERE
LDI R20,0x09 ;--------ISR for Timer 0
OUT TCCR0,R20 ;Start Timer0 T0_CM_ISR:
SBI DDRB,5 ;PB5 as an output IN R16,PORTB
LDI R20,(1<<OCIE0) ;Timer0 compare match LDI R17,0x20
Timer int. OUT TIMSK,R20
init. EOR R16,R17
SEI ;Set I OUT PORTB,R16
LDI R20,0x00 RETI
OUT DDRC,R20 ;make PORTC input
LDI R20,0xFF
OUT DDRD,R20 ;make PORTD output
Interrupt priority
Highest
priority

Lowest
priority
Interrupt inside an interrupt
• The I flag is cleared when the AVR begins to
execute an ISR. So, interrupts are disabled.
• The I flag is set when RETI is executed.
Task switching and resource conflict
• Does the following program work?

1 .INCLUDE "M32DEF.INC" 17 LDI R20,(1<<OCIE0)


2 .ORG 0x0 ;location for reset 18 OUT TIMSK,R20
3 JMP MAIN 19 SEI
4 .ORG 0x14 ;Timer0 compare match 20 LDI R20,0xFF
5 JMP T0_CM_ISR 21 OUT DDRC,R20
6 ;---------main program------------------------------ 22 OUT DDRD,R20
7 .ORG 0x100 23 LDI R20, 0
8 MAIN: LDI R20,HIGH(RAMEND) 24 HERE: OUT PORTC,R20
9 OUT SPH,R20 25 INC R20
10 LDI R20,LOW(RAMEND) 26 JMP HERE
11 OUT SPL,R20 ;set up stack 27 ;--------------------------ISR for Timer0
12 SBI DDRB,5 ;PB5 = output 28 T0_CM_ISR:
13 LDI R20,160 29 IN R20,PIND
14 OUT OCR0,R20 30 INC R20
15 LDI R20,0x09 31 OUT PORTD,R20
16 OUT TCCR0,R20 32 RETI
Solution 1: different registers
• Use different registers for different tasks.

1 .INCLUDE "M32DEF.INC" 17 LDI R20,(1<<OCIE0)


2 .ORG 0x0 ;location for reset 18 OUT TIMSK,R20
3 JMP MAIN 19 SEI
4 .ORG 0x14 ;Timer0 compare match 20 LDI R20,0xFF
5 JMP T0_CM_ISR 21 OUT DDRC,R20
6 ;---------main program------------------------------ 22 OUT DDRD,R20
7 .ORG 0x100 23 LDI R20, 0
8 MAIN: LDI R20,HIGH(RAMEND) 24 HERE: OUT PORTC,R20
9 OUT SPH,R20 25 INC R20
10 LDI R20,LOW(RAMEND) 26 JMP HERE
11 OUT SPL,R20 ;set up stack 27 ;--------------------------ISR for Timer0
12 SBI DDRB,5 ;PB5 = output 28 T0_CM_ISR:
13 LDI R20,160 29 IN R21,PIND
14 OUT OCR0,R20 30 INC R21
15 LDI R20,0x09 31 OUT PORTD,R21
16 OUT TCCR0,R20 32 RETI

Solution 2: Context saving
Save the contents of registers on the stack before execution of
each task, and reload the registers at the end of the task.

1 .INCLUDE "M32DEF.INC" 18 OUT TIMSK,R20


2 .ORG 0x0 ;location for reset 19 SEI
3 JMP MAIN 20 LDI R20,0xFF
4 .ORG 0x14 ;Timer0 compare match 21 OUT DDRC,R20
5 JMP T0_CM_ISR 22 OUT DDRD,R20
6 ;---------main program------------------------------ 23 LDI R20, 0
7 .ORG 0x100 24 HERE: OUT PORTC,R20
8 MAIN: LDI R20,HIGH(RAMEND) 25 INC R20
9 OUT SPH,R20 26 JMP HERE
10 LDI R20,LOW(RAMEND) 27 ;--------------------------ISR for Timer0
11 OUT SPL,R20 ;set up stack 28 T0_CM_ISR:
12 SBI DDRB,5 ;PB5 = output 29 PUSH R20 ;save R20
13 LDI R20,160 30 IN R20,PIND
14 OUT OCR0,R20 31 INC R20
15 LDI R20,0x09 32 OUT PORTD,R20
16 OUT TCCR0,R20 33 POP R20 ;restore R20
17 LDI R20,(1<<OCIE0) 34 RETI
Saving SREG
• We should save SREG, when we change flags
in the ISR.
PUSH R20
IN R20,SREG
PUSH R20
...
POP R20
OUT SREG,R20
POP R20
C programming
• Using Timer0 generate a square wave on pin PORTB.5, while at the same
time transferring data from PORTC to PORTD.
#include "avr/io.h"
#include "avr/interrupt.h"
int main ()
{
DDRB |= 0x20; //DDRB.5 = output
TCNT0 = -32; //timer value for 4 µs
TCCR0 = 0x01; //Normal mode, int clk, no prescaler
TIMSK = (1<<TOIE0); //enable Timer0 overflow interrupt
sei (); sei ( );
//enable //set I
interrupts
DDRC = 0x00; cli ( );PORTC
//make //clear
inputI
DDRD = 0xFF; //make PORTD output
while (1) //wait here
PORTD = PINC;
}
ISR (TIMER0_OVF_vect) //ISR for Timer0 overflow
{
TCNT0 = -32;
PORTB ^= 0x20; //toggle PORTB.5
}
C programming Example 2
• Using Timer1 and CTC mode write a program that toggles pin PORTB.5
every second, while at the same time transferring data from PORTC to
PORTD. Assume XTAL = 8 MHz.
#include "avr/io.h"
#include "avr/interrupt.h"
int main ()
{
DDRB |= 0x20; //make DDRB.5 output
OCR0 = 40;
TCCR0 = 0x09; //CTC mode, internal clk, no prescaler
TIMSK = (1<<OCIE0); //enable Timer0 compare match int.
sei (); //enable interrupts
DDRC = 0x00; //make PORTC input
DDRD = 0xFF; //make PORTD output
while (1) //wait here
PORTD = PINC;
}
ISR (TIMER0_COMP_vect) //ISR for Timer0 compare match
{
PORTB ^= 0x20; //toggle PORTB.5
}
C programming Example 3
• Assume that the INT0 pin is connected to a switch that is normally high.
Write a program that toggles PORTC.3, whenever INT0 pin goes low. Use
the external interrupt in level-triggered mode.

#include "avr/io.h"
#include "avr/interrupt.h"

int main ()
{
DDRC = 1<<3; //PC3 as an output
PORTD = 1<<2; //pull-up activated
GICR = (1<<INT0); //enable external interrupt 0
sei (); //enable interrupts

while (1); //wait here


}

ISR (INT0_vect) //ISR for external interrupt 0


{
PORTC ^= (1<<3); //toggle PORTC.3
}
Timer Overflow Example Code

Sample Timer Overflow C Code!

#include <io.h>
#include <interrupt.h>
#include <signal.h>

SIGNAL(SIG_OVERFLOW0) /* ISR for TCNT0 overflow */


{
/* DO YOUR WORK HERE */

TCNT0 = 0; /* Reset TCNT0 to get the interrupt again */


}

void main(void)
{
TCCR0 = 0x05; /* TCNT0 is clocked with cpu/1024 clock */
TIMSK = 1<<TOIE0; /* Timer Overflow Interrupt Enable on TCNT0 */
TCNT0 = 0; /* Reset TCNT0 */
sei(); /* Enable interrupts */
for (;;) {
/* Main loop */
}
}

15!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Pulse Width Modulation
 Vary the duty cycle of a fixed period “square” wave to vary output power!
 DC Motor Speed Control, LED Brightness, Servo Positioning, “Poor-manʼs DAC”!

 Waveform Generator / Output Compare module!


 Coupled with timer peripheral!

http://www.ece.utep.edu/courses/web3376/concepts/pwm.html!

16!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
PWM Example Code (1/2)

#include <io.h>!
#include <interrupt.h>!
#include <signal.h>!

void main(void)! {!

!DDRL=0x38;!
!PORTL=PORTL | 0x38; //start off with the tri-color LED off! !for (;;) {!

! !/* Main loop */!


!}!
}!

17!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
PWM Example Code (2/2)
void ColorCycle( void )!
{!
!//First, set up the timer/counter #5 for the color LED control! !TCCR5A = (1 <<
COM5A1) | (1 << COM5B1) | (1 << COM5C1) | (1 << WGM50);!
! TCCR5B = (1 << CS52) | (1 << CS50) | (1 << WGM52); // clk/1024, PWM (mode 5 in table 82 of datasheet)! !//Start with just
green!
!OCR5A = 255;!
!OCR5B =
255;! !OCR5C =
0;! !sei();!
!while ( 1 )! !{!

! !for (OCR5A = 255; OCR5A>1; OCR5A--)!


! ! !DelayMS();!
! !for (OCR5C = 0; OCR5C<255; OCR5C++)!
! ! !DelayMS();!
! !for (OCR5B = 255; OCR5B>1; OCR5B--)!
! ! !DelayMS();!
! !for (OCR5A = 0; OCR5A<255; OCR5A++)!
! ! !DelayMS();!
! !for (OCR5C = 255; OCR5C>1; OCR5C--)!
! ! !DelayMS();!
! !for (OCR5B = 0; OCR5B<255; OCR5B++)!
! ! !DelayMS();!
!}!
}!

18!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
ATmega2560 Interrupt Unit

3!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
Pulse Width Modulation
 Vary the duty cycle of a fixed period “square” wave to vary output power!
 DC Motor Speed Control, LED Brightness, Servo Positioning, “Poor-manʼs DAC”!

 Waveform Generator / Output Compare module!


 Coupled with timer peripheral!

http://www.ece.utep.edu/courses/web3376/concepts/pwm.html!

4!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
PWM Example Code (1/2)

#include <io.h>!
#include <interrupt.h>!
#include <signal.h>!

void main(void)! {!

!DDRL=0x38;!
!PORTL=PORTL | 0x38; //start off with the tri-color LED off! !for (;;) {!

! !/* Main loop */!


!}!
}!

5!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.
PWM Example Code (2/2)
void ColorCycle( void )!
{!
!//First, set up the timer/counter #5 for the color LED control! !TCCR5A = (1 <<
COM5A1) | (1 << COM5B1) | (1 << COM5C1) | (1 << WGM50);!
! TCCR5B = (1 << CS52) | (1 << CS50) | (1 << WGM52); // clk/1024, PWM (mode 5 in table 82 of datasheet)! !//Start with just
green!
!OCR5A = 255;!
!OCR5B =
255;! !OCR5C =
0;! !sei();!
!while ( 1 )! !{!

! !for (OCR5A = 255; OCR5A>1; OCR5A--)!


! ! !DelayMS();!
! !for (OCR5C = 0; OCR5C<255; OCR5C++)!
! ! !DelayMS();!
! !for (OCR5B = 255; OCR5B>1; OCR5B--)!
! ! !DelayMS();!
! !for (OCR5A = 0; OCR5A<255; OCR5A++)!
! ! !DelayMS();!
! !for (OCR5C = 255; OCR5C>1; OCR5C--)!
! ! !DelayMS();!
! !for (OCR5B = 0; OCR5B<255; OCR5B++)!
! ! !DelayMS();!
!}!
}!

6!
AVR Microcontroller and Embedded System Using Assembly and C © 2011 Pearson Higher Education,
Mazidi, Naimi, and Naimi Upper Saddle River, NJ 07458. • All Rights Reserved.

You might also like