Sie sind auf Seite 1von 240

Features

® ®
1• High-performance, Low-power Atmel AVR 8-bit Microcontroller
2• Advanced RISC Architecture
– 131 Powerful Instructions – Most Single-clock Cycle Execution
– 32 x 8 General Purpose Working Registers
– Fully Static Operation
– Up to 16 MIPS Throughput at 16 MHz
– On-chip 2-cycle Multiplier
3• High Endurance Non-volatile Memory segments
– 16 Kbytes of In-System Self-programmable Flash program memory
– 512 Bytes EEPROM
– 1 Kbyte Internal SRAM
– Write/Erase Cycles: 10,000 Flash/100,000 EEPROM –
8-bit
Data retention: 20 years at 85°C/100 years at 25°C (1)
– Optional Boot Code Section with Independent Lock Bits
Microcontroller
In-System Programming by On-chip Boot Program
True Read-While-Write Operation with 16K Bytes
– Programming Lock for Software Security
1• JTAG (IEEE std. 1149.1 Compliant) Interface In-System
– Boundary-scan Capabilities According to the JTAG Standard
– Extensive On-chip Debug Support Programmable
– Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface
2• Peripheral Features Flash
– Two 8-bit Timer/Counters with Separate Prescalers and Compare Modes
– One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture
Mode
– Real Time Counter with Separate Oscillator
– Four PWM Channels ATmega16
– 8-channel, 10-bit ADC
8 Single-ended Channels
7 Differential Channels in TQFP Package Only
ATmega16L
2 Differential Channels with Programmable Gain at 1x, 10x, or 200x
– Byte-oriented Two-wire Serial Interface
– Programmable Serial USART
– Master/Slave SPI Serial Interface
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
1• Special Microcontroller Features
– Power-on Reset and Programmable Brown-out Detection
– Internal Calibrated RC Oscillator
– External and Internal Interrupt Sources
– Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down,
Standby and Extended Standby
2• I/O and Packages
– 32 Programmable I/O Lines
– 40-pin PDIP, 44-lead TQFP, and 44-pad QFN/MLF
3• Operating Voltages
– 2.7V - 5.5V for ATmega16L
– 4.5V - 5.5V for ATmega16
4• Speed Grades
– 0 - 8 MHz for ATmega16L
– 0 - 16 MHz for ATmega16
5• Power Consumption @ 1 MHz, 3V, and 25°C for ATmega16L –
Active: 1.1 mA
– Idle Mode: 0.35 mA
– Power-down Mode: < 1 µA
Rev. 2466T–AVR–07/10
ATmega16(L)

Pin Figure 1. Pinout ATmega16


Configurations PDIP

(XCK/T0) PB0 PA0 (ADC0)


(T1) PB1 PA1 (ADC1)
(INT2/AIN0) PB2 PA2 (ADC2)
(OC0/AIN1) PB3 PA3 (ADC3)
(SS) PB4 PA4 (ADC4)
(MOSI) PB5 PA5 (ADC5)
(MISO) PB6 PA6 (ADC6)
(SCK) PB7 PA7 (ADC7)
RESET AREF
VCC GND
GND AVCC
XTAL2 PC7 (TOSC2)
XTAL1 PC6 (TOSC1)
(RXD) PD0 PC5 (TDI)
(TXD) PD1 PC4 (TDO)
(INT0) PD2 PC3 (TMS)
(INT1) PD3 PC2 (TCK)
(OC1B) PD4 PC1 (SDA)
(OC1A) PD5 PC0 (SCL)
(ICP1) PD6 PD7 (OC2)

TQFP/QFN/MLF
PB2 (AIN0/INT2)
PB3 (AIN1/OC0)

PB0 (XCK/T0)

PA0 (ADC0)

(ADC2)
PA1 (ADC1)

PA3 (ADC3)
PB4 (SS)

PB1 (T1)

GND
VCC

PA2

PA4 (ADC4)

(MOSI) PB5
PA5 (ADC5)
(MISO) PB6
PA6 (ADC6)
(SCK) PB7
RESET
AREF
VCC
GND
GND
AVCC
XTAL2
PC7 (TOSC2)
XTAL1
PC6 (TOSC1)
(RXD) PD0 PA7 (ADC7)
PC5 (TDI)
(TXD) PD1
PC4 (TDO)
(INT0) PD2

Bottom pad
should
be soldered to
ground.
NOTE:
GND
(OC1B) PD4
(OC1A) PD5
(ICP1) PD6
(OC2) PD7

(SCL) PC0
(SDA) PC1
(TCK) PC2
VCC
(INT1) PD3

(TMS) PC3
ned incha R microcontrollers manufactured on
this ract the same process technology. Min
datashe eriz and Max values will be available after
Disclaimer Typic et areatio the device is characterized.
al based n of
value on oth
s simulati er
contai ons andAV
2
2466T–AVR–07/10
ATmega16(L)
ed on the
AVR
Ov T enhanced
RISC
er h architecture.
e
vie By executing
powerful
w A instructions
T
in a single
m
clock cycle,
e
the
g
ATmega16
Blo a achieves
ck 1 throughputs
6
Dia approaching
gra i 1 MIPS per
m s MHz allowing
the system
designer to
a
optimize
power con-
l
sumption
o
versus
w
processing
-
speed.
p
o
w Figure 2.
e Block
r Diagram
PA0 - PA7
C PC7
VCC
M
O
S

8
-
b
i GND

m AVCC
i
c
r AREF

o PR
CO
c
o
n PR

t
r
INST
o RE

l
l INST

e DE

r
CO
L
b
a
s AV
PORTB DRIVERS/BUF

PB0 - PB7

2466
T–
AVR–
07/10
ATmega16(L)

The AVR core combines a rich instruction set with 32 general purpose working registers. All the
32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent
registers to be accessed in one single instruction executed in one clock cycle. The resulting
architecture is more code efficient while achieving throughputs up to ten times faster than con-
ventional CISC microcontrollers.
The ATmega16 provides the following features: 16 Kbytes of In-System Programmable Flash
Program memory with Read-While-Write capabilities, 512 bytes EEPROM, 1 Kbyte SRAM, 32
general purpose I/O lines, 32 general purpose working registers, a JTAG interface for
Boundary-scan, On-chip Debugging support and programming, three flexible Timer/Counters
with com-pare modes, Internal and External Interrupts, a serial programmable USART, a byte
oriented Two-wire Serial Interface, an 8-channel, 10-bit ADC with optional differential input
stage with programmable gain (TQFP package only), a programmable Watchdog Timer with
Internal Oscil-lator, an SPI serial port, and six software selectable power saving modes. The
Idle mode stops the CPU while allowing the USART, Two-wire interface, A/D Converter, SRAM,
Timer/Counters, SPI port, and interrupt system to continue functioning. The Power-down mode
saves the register contents but freezes the Oscillator, disabling all other chip functions until the
next External Inter-rupt or Hardware Reset. In Power-save mode, the Asynchronous Timer
continues to run, allowing the user to maintain a timer base while the rest of the device is
sleeping. The ADC Noise Reduction mode stops the CPU and all I/O modules except
Asynchronous Timer and ADC, to minimize switching noise during ADC conversions. In
Standby mode, the crystal/reso-nator Oscillator is running while the rest of the device is
sleeping. This allows very fast start-up combined with low-power consumption. In Extended
Standby mode, both the main Oscillator and the Asynchronous Timer continue to run.
The device is manufactured using Atmel’s high density nonvolatile memory technology. The On-
chip ISP Flash allows the program memory to be reprogrammed in-system through an SPI
serial interface, by a conventional nonvolatile memory programmer, or by an On-chip Boot
program running on the AVR core. The boot program can use any interface to download the
application program in the Application Flash memory. Software in the Boot Flash section will
continue to run while the Application Flash section is updated, providing true Read-While-Write
operation. By combining an 8-bit RISC CPU with In-System Self-Programmable Flash on a
monolithic chip, the Atmel ATmega16 is a powerful microcontroller that provides a highly-flexible
and cost-effec-tive solution to many embedded control applications.
The ATmega16 AVR is supported with a full suite of program and system development tools
including: C compilers, macro assemblers, program debugger/simulators, in-circuit emulators,
and evaluation kits.

Pin Descriptions

VCC Digital supply voltage.

GND Ground.

Port A (PA7..PA0) Port A serves as the analog inputs to the A/D Converter.

Port A also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used. Port pins
can provide internal pull-up resistors (selected for each bit). The Port A output buffers have sym-
metrical drive characteristics with both high sink and source capability. When pins PA0 to PA7
are used as inputs and are externally pulled low, they will source current if the internal pull-up
resistors are activated. The Port A pins are tri-stated when a reset condition becomes active,
even if the clock is not running.

4
2466T–AVR–07/10
ATmega16(L)

Port B (PB7..PB0) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port B output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port B pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port B also serves the functions of various special features of the ATmega16 as listed on page
58.

Port C (PC7..PC0) Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port C output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port C pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port C pins are tri-stated when a reset condition becomes active,
even if the clock is not running. If the JTAG interface is enabled, the pull-up resistors on pins
PC5(TDI), PC3(TMS) and PC2(TCK) will be activated even if a reset occurs.
Port C also serves the functions of the JTAG interface and other special features of the
ATmega16 as listed on page 61.

Port D (PD7..PD0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The
Port D output buffers have symmetrical drive characteristics with both high sink and source
capability. As inputs, Port D pins that are externally pulled low will source current if the pull-up
resistors are activated. The Port D pins are tri-stated when a reset condition becomes active,
even if the clock is not running.
Port D also serves the functions of various special features of the ATmega16 as listed on page
63.

RESET Reset Input. A low level on this pin for longer than the minimum pulse length will generate a
reset, even if the clock is not running. The minimum pulse length is given in Table 15 on page
38. Shorter pulses are not guaranteed to generate a reset.

XTAL1 Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.

XTAL2 Output from the inverting Oscillator amplifier.

AVCC AVCC is the supply voltage pin for Port A and the A/D Converter. It should be externally con-
nected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to V CC
through a low-pass filter.

AREF AREF is the analog reference pin for the A/D Converter.

5
2466T–AVR–
07/10
ATmega16(L)
download on
http://www.atm
el.com/avr.
Re A
so c
o
ur m
Reliability
ce pr Qualification
s eh results show
that the
e projected data
n retention
si failure rate is
Da v much less
e
ta s than 1 PPM
over 20 years
Re et at 85°C or 100
te of years at 25°C.
d
nti e
on v
el
o
p
m
e
nt
to
ol
s,
a
p
pl
ic
at
io
n
n
ot
e
s
a
n
d
d
at
a
s
h
e
et
s
ar
e
a
v
ai
la
bl
e
fo
r
6
24 66T–AVR–07/10

ATm

A This
b documentation
contains simple
o code examples
u that briefly show
t how to use
various parts of
the device.
C These code
o examples
d assume that the
part specific
e header file is
E included before
compilation. Be
x aware that not
a all C Compiler
m vendors include
bit definitions in
p the header files
l and interrupt
e handling in C is
compiler
s dependent.
Please confirm
with the C
Compiler
documen-tation
for more details.
7

2
4
ATmega16(L)
ore is to
ensure correct
AV program
execution. The
R CPU must
CP T therefore be
U hi able to access
s memories,
Co s perform
re e calculations,
ct control
io peripherals,
Intr n and handle
od di interrupts.
uct s
ion c Figure 3.
u Block Diagram
s of the AVR
s MCU
Ar e Architecture
s
chi th Data Bus 8-b

tec e
tur A
al V
P
Ov R M

erv c
or
iew e I

ar
c I
hi
te
ct Co
ur
e
in
g
e
n
er
al
.
T
h
e
m
ai In order to
n maximize
fu performance
n and
ct parallelism,
io the AVR uses
n a Harvard
of architecture –
th with separate
e memories and
C buses for
P program and
U data.
c Instructions in
the d ccess Register
pro in File contains
gra e 32 × 8-bit
m v general
me er purpose
mor y working
y cl registers with
are o a single clock
exe c cycle access
cute k time. This
d c allows single-
with y cycle
a cl Arithmetic
sing e. Logic Unit
le T (ALU)
leve h operation. In a
l e typ-ical ALU
pipe pr operation, two
linin o operands are
g. gr output from
Whil a the Register
e m File, the
one m operation is
instr e executed, and
ucti m the result is
on or stored back in
is y the Register
bein is File – in one
g In clock cycle.
exe -
Six of the 32
cute S
registers can
d, y
be used as
the st
three 16-bit
next e
indirect
instr m
address
uc- R
register
tion e
pointers for
is pr
Data Space
pre- o
addressing –
fetc gr
enabling
hed a
efficient
fro m
address
m m
calculations.
the a
One of the
pro bl
these address
gra e
pointers can
m Fl
also be used
me a
as an address
mor s
pointer for
y. h
look up tables
This m
in Flash
con e
Program
cept m
memory.
ena or
These added
bles y.
function
instr
T registers are
ucti
h the 16-bit X-
ons
e register, Y-
to
fa register, and
be
st Z-register,
exe
- described later
cute
a in this section.
n nstant and a
The
re register. Single
ALU
gi register
sup
st operations can
port
er also be
s
s executed in the
arith
or ALU. After an
meti
b arithmetic
c
et opera-tion, the
and
w Status Register
logic
e is updated to
oper
e reflect
atio
n information
ns
a about the result
bet
c of the
wee
o operation.
8

2466
T–
AVR–
07/10
ATmega16(L)
ble to directly
address the
P whole address
r space. Most
o AVR
g instructions
r have a single
a 16-bit word
m for-mat. Every
fl program
o memory
w address
is contains a 16-
p bit or 32-bit
r instruction.
o Program
vi Flash memory
d space is
e divided in two
d sections, the
b Boot program
y section and
c the Application
o Program
n section. Both
di sections have
ti dedicated
AL o Lock bits for
U–n write and
Ari al
a
read/write
th n protection.
me d The SPM
instruction that
tic u writes into the
Lo n Application
gic c Flash memory
o
Uni n section must
t di reside in the
Boot Program
ti
o section.
n During
al interrupts and
ju subroutine
Sta m calls, the
tus p return address
Re a Program
gis n Counter (PC)
d is stored on
ter c
the Stack. The
al Stack is
l effectively
in allocated in
st the general
r data SRAM,
u and
ct consequently
io the Stack size
n is only limited
s, by the total
a SRAM size
and e R architecture.
the a
The memory
usa si
spaces in the
ge ly AVR
of b architecture
the e are all linear
SR a and regular
AM. c memory
All c maps.
user e
pro s A flexible
gra s interrupt
ms e module has its
mus d control
t t registers in
initi h the I/O space
aliz r with an
e o additional
the u global
SP g interrupt
in h enable bit in
the t the Status
rese h Register. All
t e interrupts
routi fi have a
ne v separate
(bef e interrupt
ore di vector in the
subr ff interrupt
outi e vector table.
nes r The interrupts
or e have priority in
inter n accordance
rupt t with their
s a interrupt
are d vector posi-
exe d tion. The
cute r lower the
d). e interrupt
The s vector
Sta si address, the
ck n higher the
Poi g priority.
nter m The I/O
SP o memory
is d space
rea e contains 64
d/wr s addresses for
ite s CPU
acc u peripheral
essi p functions as
ble p Control Regis-
in o ters, SPI, and
the rt other I/O
I/O e functions. The
spa d I/O Memory
ce. in can be
The t accessed
data h directly, or as
SR e the Data
AM A Space
can V locations
follo p ns are divided
win u into three main
g r categories –
thos p arithmetic,
e ofo logical, and bit-
the s functions.
Reg e Some
ister r implementation
File, e s of the
$20 gi architecture
- st also provide a
$5F. e powerful
rs multiplier
The o supporting
high r both
- b signed/unsigne
perf et d multiplication
orm w and fractional
anc e format. See the
e e “Instruction
AVR n Set” section for
ALU a a detailed
oper r description.
ates e
in gi The Status
dire st Register
ct e contains
con r information
nect a about the
ion n result of the
with d most recently
all a executed
the n arithme-tic
32 i instruction.
gen m This
eral m information
purp e can be used
ose di for altering
wor at program flow
king e in order to
regi a perform
ster r conditional
s. e operations.
With e Note that the
in ax Status
singl e Register is
e c updated after
cloc ut all ALU
k e operations, as
cycl d. specified in
e, T the Instruction
arith h Set
meti e Reference.
c A This will in
oper L many cases
atio U remove the
ns o need for using
bet p the dedicated
wee e compare
n r instructions,
gen at resulting in
eral io faster and
mor w Interrupt
e a Enable bit
com r must be set for
pact e the interrupts
cod . to be enabled.
e. T The individual
inter-rupt
The h
enable control
Stat e
is then
us A
performed in
Reg V
separate
ister R
control
is S
registers. If the
not t
a Global
auto
t Interrupt
mati
u Enable
call
s Register is
y
R cleared, none
stor e
of the
ed gi
whe st interrupts are
n e enabled
ente r independent of
ring – the individual
an S interrupt
inter R enable
rupt E settings. The I-
routi G bit is cleared
ne – by hardware
and is after an
rest d interrupt has
ore e occurred, and
d fi is set by the
whe n RETI
n e instruction to
retu d enable
rnin a subsequent
g s: interrupts. The
fro Bit I-bit can also
m be set and
an Read/Write cleared by the
application with
inter Initial Value
rupt the SEI and
. • Bit 7CLI – I: Global Interrupt
This instructions, as
mus T described in
t be h the instruction
han e set reference.
dled G
by lo
soft b
al 9
2466
T–
AVR–
07/10
ATmega16(L)

• Bit 6 – T: Bit Copy Storage


The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or desti-
nation for the operated bit. A bit from a register in the Register File can be copied into T by the
BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the
BLD instruction.

• Bit 5 – H: Half Carry Flag


The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry is useful
in BCD arithmetic. See the “Instruction Set Description” for detailed information.

• Bit 4 – S: Sign Bit, S = N V


The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement
Overflow Flag V. See the “Instruction Set Description” for detailed information.

• Bit 3 – V: Two’s Complement Overflow Flag


The Two’s Complement Overflow Flag V supports two’s complement arithmetics. See the
“Instruction Set Description” for detailed information.

• Bit 2 – N: Negative Flag


The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the
“Instruction Set Description” for detailed information.

• Bit 1 – Z: Zero Flag


The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the “Instruction
Set Description” for detailed information.

• Bit 0 – C: Carry Flag


The Carry Flag C indicates a carry in an arithmetic or logic operation. See the “Instruction Set
Description” for detailed information.

10
2466T–AVR–
07/10
ATmega16(L)
o achieve the
required
Ge T performance
ner h and flexibility,
the following
al e input/output
Pur R schemes are
po e supported by
gi
se st the Register
Re e File:
gis r 1• One 8-bit
ter F output
Fil il operand and
one 8-bit
e e result input
is
o 2• Two 8-bit
p output
ti operands and
m one 8-bit
iz result input
e
d 3• Two 8-bit
f output
o operands and
r one 16-bit
result input
t
h 4• One 16-bit
e output
A operand and
V one 16-bit
R result input
E Figure 4
n shows the
h structure of
a the 32 general
n purpose
c working
e registers in
d the CPU.
R
I Figure 4. AVR CPU G
S
C
in
st
r
u
ct
io General
n Purpose
s Working

e Registers

t.
I
n
o
r
d
e
r Most of the
t instructions
ope in register is also
ratin st assigned a
g on r data memory
the u address,
Reg ct mapping them
ister io directly into
File n the first 32
hav s. locations of
e the user Data
A
dire Space.
s
ct Although not
s
acc being
h
ess physically
o
to imple-mented
all w as SRAM
regi n locations, this
ster in memory
s, F organization
and ig provides great
mos u flexibility in
t of r access of the
the e registers, as
m 4 the X-, Y-, and
are , Z-pointer
sing e Registers can
le a be set to index
cycl c any register in
e h the file.

1
1

2466
T–
AVR–
07/10
ATmega16(L)

The X-register, Y- The registers R26..R31 have some added functions to their general purpose usage. These reg-
register and Z-register isters are 16-bit address pointers for indirect addressing of the Data Space. The three indirect
address registers X, Y, and Z are defined as described in Figure 5.

Figure 5. The X-register, Y-register, and Z-register


).

X - register The Stack is mainly used for storing


temporary data, for storing local variables
and for storing return addresses after
interrupts and subroutine calls. The Stack
Y - register
Pointer Register always points to the top of
the Stack. Note that the Stack is
implemented as growing from higher memory
loca-tions to lower memory locations. This
implies that a Stack PUSH command
Z - register
decreases the Stack Pointer. If software
reads the Program Counter from the Stack
In the after a call or an interrupt, unused bits
differe (15:13) should be masked out.
nt
The Stack Pointer points to the data SRAM
addre Stack area where the Subroutine and
Stack Pointer ssing Interrupt Stacks are located. This Stack
mode space in the data SRAM must be defined by
s the program before any subroutine calls are
these executed or interrupts are enabled. The
addre Stack Pointer must be set to point above
ss $60. The Stack Pointer is decremented by
regist one when data is pushed onto the Stack with
ers the PUSH instruction, and it is decremented
have by two when the return address is pushed
functi onto the Stack with subroutine call or
ons interrupt. The Stack Pointer is incremented
as by one when data is popped from the Stack
fixed with the POP instruction, and it is
displa incremented by two when data is popped
ceme from the Stack with return from subroutine
nt, RET or return from interrupt RETI.
autom The AVR Stack Pointer is implemented as
atic two 8-bit registers in the I/O space. The
incre number of bits actually used is
ment, implementation dependent. Note that the
and data space in some implementa-tions of the
autom AVR architecture is so small that only SPL is
atic needed. In this case, the SPH Register will
decre not be present.
ment
(see
the
Instru
ction
Set
Refer
ence
for
details
Bit 15 14 13 12 11 10 9 8
SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
7 6 5 4 3 2 1 0
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1
2

2466T–AVR–07/10
ATmega16(L)
on execution.
The AVR CPU
is driven by
Ins T the CPU clock
tru hi clkCPU, directly
s
cti s generated
on e from the
selected clock
Ex cti source for the
o
ecun chip. No
tio d internal clock
n e division is
used.
Ti sc
ri Figure 6
mi b
ng e shows the
s parallel
th instruction
e fetches and
g instruction
e executions
n enabled by the
er
al Har-vard
a architecture
cc and the fast-
e access
ss Register File
ti concept. This
m is the basic
in
g pipelining
c concept to
o obtain up to 1
n MIPS per MHz
c with the
e corresponding
pt unique results
s
fo for functions
r per cost,
in functions per
st clocks, and
ru functions per
cti power-unit.
ute u s
2nd6. c
Figure t
Instr t r
uctio i u
o c
Fetc n t
i
clk2nd E o
Instr
1st x n
uctio
Instru e
ction c F
Exec
Fetch u e
ute t t
3rd e c
Instr h
uctio 4
t
Fetc h Figure 7
shows
3rd I the
Instr n internal
ti r sult is u
mi e stored t
ng g back to i
co i the
o
nc s destina-
ep t tion n
t e register.
for r T
th Figure
i
e o 7.
R p Single m
eg e Cycle e
ist r ALU
er a Operati Regi
Fil n on ster
e. d Oper
In s ands
T1 Fetc
a
h
si i
ng s
AL
le l U
cl e Op
k
oc x erat
k e ion
C
cy c Exe
cl u P cut
e t e
an e U
A d R
L , e
U a T s
op n o ul
er d t t
ati W
a
on t rit
us h l e
in e E B
g x a
tw r c
e
o e k
c
H rate e its
reset d whic
vector h
R The each i must
e AVR have n be
s provia d writte
des separ i
e n
seve ate v logic
t ral progra i
a one
diffe m d toget
n rent vector u her
d inter in thea with
I rupt progra l the
n sour m Glob
t ces. memo e al
The ry n Interr
e se space. a
r upt
inter All b Enab
r rupt interru l le bit
u s pts e in
p and are the
t the assign b Statu
sepa
ss t next isa nterr
Rt prior INT0 l upt
eT ity, – the Requ
gih and Extern I est

24
66
T–
A
V
R

07
/1
0
ATmega16(L)

0. The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the
IVSEL bit in the General Interrupt Control Register (GICR). Refer to “Interrupts” on page 45 for
more information. The Reset Vector can also be moved to the start of the boot Flash section by
pro-gramming the BOOTRST Fuse, see “Boot Loader Support – Read-While-Write Self-
Programming” on page 246.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are dis-
abled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a
Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts. The first type is triggered by an event that sets the
Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vec-tor in
order to execute the interrupt handling routine, and hardware clears the corresponding Interrupt
Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s) to be
cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the
Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by
software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is
cleared, the corresponding Interrupt Flag(s) will be set and remembered until the global interrupt
enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These
interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before
the interrupt is enabled, the interrupt will not be triggered.
When the AVR exits from an interrupt, it will always return to the main program and execute one
more instruction before any pending interrupt is served.
Note that the Status Register is not automatically stored when entering an interrupt routine, nor
restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled.
No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the
CLI instruction. The following example shows how this can be used to avoid interrupts during
the timed EEPROM write sequence.
Assembly Code Example
in r16, SREG ; store SREG value
cli ; disable interrupts during timed sequence
sbi EECR, EEMWE ; start EEPROM write
sbi EECR, EEWE
out SREG, r16 ; restore SREG value (I-bit)

C Code Example
char cSREG;
cSREG = SREG; /* store SREG value */
/* disable interrupts during timed sequence */
_CLI();
EECR |= (1<<EEMWE); /* start EEPROM write */
EECR |= (1<<EEWE);
SREG = cSREG; /* restore SREG value (I-bit) */

14
2466T–AVR–
07/10
ATmega16(L)

When using the SEI instruction to enable interrupts, the instruction following SEI will be exe-
cuted before any pending interrupts, as shown in this example.
Assembly Code Example
sei ; set global interrupt enable
sleep ; enter sleep, waiting for interrupt

1; note: will enter sleep before any pending

2; interrupt(s)

C Code Example
_SEI(); /* set global interrupt enable */ _SLEEP();
/* enter sleep, waiting for interrupt */
/* note: will enter sleep before any pending interrupt(s) */

Interrupt Response The interrupt execution response for all the enabled AVR interrupts is four clock cycles mini-
Time mum. After four clock cycles the program vector address for the actual interrupt handling routine
is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack.
The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If
an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed
before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt
execution response time is increased by four clock cycles. This increase comes in addition to the
start-up time from the selected sleep mode.
A return from an interrupt handling routine takes four clock cycles. During these four clock
cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is
incremented by two, and the I-bit in SREG is set.

15
2466T–AVR–07/10
ATmega16(L)
e Data
Memory and
AV T the Program
Memory
R hi space. In
AT sse addition, the
mecti ATmega16
features an
ga on EEPROM
16 de Memory for
sc
Me rib data storage.
All three
m es memory
ori th
e
spaces are
es dif linear and
regular.
fe
re
nt The
In- m ATmega16
Sy e contains 16
ste m Kbytes On-
chip In-System
m ori
Reprogramma
Re es ble Flash
in
pro th memory for
gra e pro-gram
m A storage. Since
ma T all AVR
ble m instructions
are 16 or 32
Fla eg bits wide, the
a1
sh 6. Flash is
Pr T organized as
ogr he 8K × 16. For
am A software
Me V security, the
Flash Program
mo R memory space
ar
ry ch is divided into
ite two sections,
ct Boot Program
ur section and
e Application
ha Program
s section.
tw The Flash
o memory has
m an endurance
ai of at least
n 10,000
m write/erase
e cycles. The
m ATmega16
or Pro-gram
y Counter (PC)
sp is 13 bits wide,
ac thus
es addressing the
, 8K program
th memory
loca ng ing the SPI
tion ” pins or the
s. on JTAG
The pa interface.
ope ge
Constant
ratio 24
tables can be
n of6.
allocated
Boo “
within the
t M
entire program
Pro e
memory
gra m
address space
m or
(see the LPM
sect y – Load
ion Pr Program
and og Memory
ass ra Instruction
ocia m Description).
ted mi
Boo ng Timing
t ” diagrams for
Loc on instruction
k pa fetch and
bits ge execution are
for 25 presented in
soft 9 “Instruction
war co Execution Tim-
e nt ing” on page
prot ai 13.
ecti ns
on a Figure 8.
are de Program
des tai Memory Map
crib le
ed d
in de
deta sc $0000
il inrip
“Bo tio
ot n
Loa on
Application
der Fl Section
Sup as
port h
– da
Rea ta
d- se
Whil ria
e- l
Writ do
e w
Self nl
- oa
Pro di
gra ng
mmi us Boot Flash
$1FFF

1
6
24 66T–AVR–07/10
S ATm
M
Figure 9
shows how the
ATmega16
SRAM Memory
is organized.
The lower
1120 Data
Memory
locations
address the
Register File,
the I/O
Memory, and
the inter-nal
data SRAM.
The first 96
locations
address the
Register File
and I/O
Memory, and
the next 1024
locations
address the
internal data
SRAM.
The five
different
addressing
modes for the
data memory
cover: Direct,
Indirect with
Displace-ment,
Indirect,
Indirect with
Pre-
decrement,
and Indirect
with Post-
increment. In
the Register
File, registers
R26 to R31
feature the
indirect
addressing
pointer
registers.
The direct
addressing
reaches the
entire data
space.
The Indirect
with
Displacement
m internal data
o SRAM in the
W ATmega16 are
h all accessible
T through all
h these
addressing
modes. The
Register File is
described in
“General
Purpose
Register File”
on page 11.
Figure 9. Data Memory Map
Register File
R0
R1
R2
...

R29
R30
R31
I/O Registers
$00
$01
$02
...

$3D
$3E
$3F

1
7

2
4
ATmega16(L)

Data Memory Access This section describes the general access timing concepts for internal memory access. The
Times internal data SRAM access is performed in two clkCPU cycles as described in Figure 10.

Figure 10. On-chip Data SRAM Access Cycles


T1 T2 T3

clkCPU
Address Compute Address Address Valid

Data

WR

Write
Data

RD
Read

description of some voltage lower than specified as


SPI, JTAG, preca minimum for the clock frequency
and Parallel utions used. See “Prevent- ing
EEPROM Data The ATmega16 data must EEPROM Corruption” on page
Memory contains 512 downloading be 22 for details on how to avoid
bytes of data to the taken. problems in these situations.
EEPROM EEPROM, see In In order to prevent
memory. It is heavil
page 273, unintentional EEPROM writes,
y
organized as a page 278, and filtere a specific write procedure
separate data page 262, must be followed. Refer to the
d
space, in which respectively. power description of the EEPROM
single bytes can suppli Control Register for details on
EEPROM Read/Write
be read and The EEPROM es, this.
Access
written. The Access
V is When the EEPROM is read,
EEPROM has Registers are CC
likely the CPU is halted for four
an endurance of accessible in
to rise clock cycles before the next
at least 100,000 the I/O space.
or fall instruction is executed. When
write/erase The writeslowly
cycles. The the EEPROM is written, the
access time foron
access between CPU is halted for two clock
the EEPROMPower
the EEPROM cycles before the next
is given in-
and the CPU is Table 1. A self-up/do
instruction is executed.
described in the timing function,wn.
following, however, letsThis
specifying the the usercause
EEPROM software detects the
Address when the nextdevic
byte can bee for
Registers, the
written. If thesome
EEPROM Data
user codeperiod
Register, and the contains of
EEPROM instructions time
Control Register. that write theto run
EEPROM, at a 18
2466T–AVR–07/10
ATmega16(L)

The
EEP
RO
M
Add
ress
Regi
ster

EEA
RH
and
EEA
RL
Bit 15 14 13
– – –
EEAR7 EEAR6 EEAR5
7 6 5
Read/Write R R R
R/W R/W R/W
Initial Value 0 0 0
X X X
d bits a
• in the n
ATme
B ga16
i and
t will
s alway
s read
1 as
5 zero.
.

T . Bits
he9 8..0 –
E
EEAR
E –
8..0:
P
R R EEPR
O e OM
Ms Addre
D : ss
at The
a R
EEPR
R e OM
e s
Addre
gi e
ss
st r
Regist
er v
– e ers –
E d EEAR
E H and
D B EEAR
R i L –
t specif
s y the
EEPR
T OM
h addre
e ss in
s
the
e
512
bytes
b
i EEPR
t OM
s space.
The
a EEPR
r OM
e data
bytes
r are
e addre
s ssed
e linearl
r y
v betwe
e en 0
Bit 7 6 5
MSB
Read/Write R/W R/W R/W
Initial Value 0 0 0

• Bits 7..0 – EEDR7.0: EEPROM


con 6
F tain
o s •
the
dat W
T
a r
h
e rea •
E d
E out T
P fro h
R m
O the
M EE 19
PR
C OM
o at
n the
tr
add
o
l
res
s
R
giv
e
g en
i by
s EE
t AR.
e
r
– Bit
E
E Read/Write
C Initial Value
R

Bit
s
7..4

Re
s:
Re
ser
ved
Bit
s
The
se
bits
are
res
erv
ed
bits
in
the
AT
me
ga1
24
66
T

A
V
R

07
/1
0
ATmega16(L)

• Bit 1 – EEWE: EEPROM Write Enable


The EEPROM Write Enable Signal EEWE is the write strobe to the EEPROM. When address
and data are correctly set up, the EEWE bit must be written to one to write the value into the
EEPROM. The EEMWE bit must be written to one before a logical one is written to EEWE, oth-
erwise no EEPROM write takes place. The following procedure should be followed when writing
the EEPROM (the order of steps 3 and 4 is not essential):
1. Wait until EEWE becomes zero.
2. Wait until SPMEN in SPMCR becomes zero.
3. Write new EEPROM address to EEAR (optional).
4. Write new EEPROM data to EEDR (optional).
5. Write a logical one to the EEMWE bit while writing a zero to EEWE in EECR.
6. Within four clock cycles after setting EEMWE, write a logical one to EEWE.
The EEPROM can not be programmed during a CPU write to the Flash memory. The software
must check that the Flash programming is completed before initiating a new EEPROM write.
Step 2 is only relevant if the software contains a Boot Loader allowing the CPU to program the
Flash. If the Flash is never being updated by the CPU, step 2 can be omitted. See “Boot
Loader Support – Read-While-Write Self-Programming” on page 246 for details about boot
programming.
Caution: An interrupt between step 5 and step 6 will make the write cycle fail, since the
EEPROM Master Write Enable will time-out. If an interrupt routine accessing the EEPROM is
interrupting another EEPROM Access, the EEAR or EEDR reGister will be modified, causing
the interrupted EEPROM Access to fail. It is recommended to have the Global Interrupt Flag
cleared during all the steps to avoid these problems.
When the write access time has elapsed, the EEWE bit is cleared by hardware. The user soft-
ware can poll this bit and wait for a zero before writing the next byte. When EEWE has been
set, the CPU is halted for two cycles before the next instruction is executed.

• Bit 0 – EERE: EEPROM Read Enable


The EEPROM Read Enable Signal – EERE – is the read strobe to the EEPROM. When the
cor-rect address is set up in the EEAR Register, the EERE bit must be written to a logic one to
trigger the EEPROM read. The EEPROM read access takes one instruction, and the requested
data is available immediately. When the EEPROM is read, the CPU is halted for four cycles
before the next instruction is executed.
The user should poll the EEWE bit before starting the read operation. If a write operation is in
progress, it is neither possible to read the EEPROM, nor to change the EEAR Register.
The calibrated Oscillator is used to time the EEPROM accesses. Table 1 lists the typical pro-
gramming time for EEPROM access from the CPU.
Table 1. EEPROM Programming Time
Number of Calibrated RC
(1)
Symbol Oscillator Cycles Typ Programming Time
EEPROM write (from CPU) 8448 8.5 ms
Note: 1. Uses 1 MHz clock, independent of CKSEL Fuse setting.
The following code examples show one assembly and one C function for writing to the EEPROM.
The examples assume that interrupts are controlled (for example by disabling inter-rupts globally) so
that no interrupts will occur during execution of these functions. The examples
20
2466T–AVR–07/10
ATmega16(L)

also assume that no Flash Boot Loader is present in the software. If such code is present, the
EEPROM write function must also wait for any ongoing SPM command to finish.
Assembly Code Example
EEPROM_write:

1; Wait for completion of previous write


sbic EECR,EEWE
rjmp EEPROM_write

2; Set up address (r18:r17) in address register


out EEARH, r18
out EEARL, r17

3; Write data (r16) to data register


out EEDR,r16

1; Write logical one to EEMWE


sbi EECR,EEMWE

2; Start eeprom write by setting EEWE


sbi EECR,EEWE
ret

C Code Example
void EEPROM_write(unsigned int uiAddress, unsigned char ucData)
{
/* Wait for completion of previous write
*/ while(EECR & (1<<EEWE))
;
/* Set up address and data registers
*/ EEAR = uiAddress;
EEDR = ucData;
/* Write logical one to EEMWE */
EECR |= (1<<EEMWE);
/* Start eeprom write by setting EEWE */
EECR |= (1<<EEWE);
}
21
2466T–AVR–07/10
ATmega16(L)

The next code examples show assembly and C functions for reading the EEPROM. The exam-
ples assume that interrupts are controlled so that no interrupts will occur during execution of
these functions.
Assembly Code Example
EEPROM_read:

1; Wait for completion of previous write sbic EECR,EEWE


rjmp EEPROM_read

2; Set up address (r18:r17) in address register out EEARH, r18


out EEARL, r17

3; Start eeprom read by writing EERE


sbi EECR,EERE
; Read data from data
register in r16,EEDR
ret

C Code Example
unsigned char EEPROM_read(unsigned int uiAddress)
{
/* Wait for completion of previous write
*/ while(EECR & (1<<EEWE))
;
/* Set up address register
*/ EEAR = uiAddress;
/* Start eeprom read by writing EERE */
EECR |= (1<<EERE);
/* Return data from data register
*/ return EEDR;
}

EEPROM Write During When entering Power-down Sleep mode while an EEPROM write operation is active, the
Power-down Sleep EEPROM write operation will continue, and will complete before the Write Access time has
Mode passed. However, when the write operation is completed, the Oscillator continues running, and
as a consequence, the device does not enter Power-down entirely. It is therefore recommended
to verify that the EEPROM write operation is completed before entering Power-down.

Preventing EEPROM During periods of low VCC, the EEPROM data can be corrupted because the supply voltage is
Corruption too low for the CPU and the EEPROM to operate properly. These issues are the same as for
board level systems using EEPROM, and the same design solutions should be applied.
An EEPROM data corruption can be caused by two situations when the voltage is too low. First,
a regular write sequence to the EEPROM requires a minimum voltage to operate correctly. Sec-
ondly, the CPU itself can execute instructions incorrectly, if the supply voltage is too low.

22
2466T–AVR–
07/10
ATmega16(L)
This
can be
E done
E by
K enablin
e g the
e internal
p Brown-
t out
h Detect
or
I/O e (BOD).
Me A If the
V
mo R detecti
ry R on
E level of
S the
E internal
T BOD
a does
ct not
iv match
e the
(l needed
o detecti
w on
) level,
d an
u externa
ri l low
n VCC
g Reset
p Protec-
e tion
ri circuit
o can be
d used. If
s a reset
o occurs
f while a
in write
s operati
u on is in
ffi progres
ci s, the
e write
n operati
t on will
p be
o comple
w ted
e provide
r d that
s the
u power
p supply
pl voltage
y is
v sufficie
ol nt.
t
a
The I/O
g
space
e
. definition of
the
AT e general
meg purpose
a16 working
is regis-ters
sho and the I/O
wn space. I/O
in Registers
“Re within the
gist address
er
range $00 -
Su
$1F are
mm
ary” directly bit-
on accessible
pag using the
e SBI and
331. CBI
instructions
All . In these
AT registers,
meg the value of
a16 single bits
I/Os can be
and checked by
peri using the
phe SBIS and
rals SBIC
are instructions
plac . Refer to
ed the
in Instruction
the Set section
I/O for more
spa details.
ce. When
The using the
I/O I/O specific
loca commands
tion IN and
s OUT, the
are I/O
acc addresses
ess $00 - $3F
ed must be
by used.
the When
IN addressing
and I/O
OU Registers
T as data
instr space
ucti using LD
ons, and ST
tran instructions
sfer , $20 must
ring be added
data to these
bet addresses.
wee
n For
the compatibilit
32 y with
gen future
devices,
rese m
rved e
bits T
sho h
uld
be
writt
en
to
zero
if
acc
ess
ed.
Res
erve
d
I/O
me
mor
y
add
ress
es
sho
uld
nev
er
be
writt
en.
So

2
3
2466
T–
AVR–
07/10
ATmega16(L)
heir
distribution.
Sy All of the
clocks need
st not be active
e at a given
time. In order
m to reduce
Cl power
oc F consumption,
i the clocks to
k g modules not
an u being used
d re can be halted
by using
Cl 1 different sleep
oc 1 modes, as
k pr described in
“Power
Op e Manage-
tio s ment and
e Sleep Modes”
ns n on page 32.
t The clock
Cl s systems are
o t detailed
h Figure 11.
ck
e
S p Figure 11. Clock Dis
ys ri
Asynchronous
te n Timer/Counter
m c
i
s p
a a
n l
d c
th l
o
ei c
r k
Di s
st y
ri s
t
b e
ut m
io s
n i
n
t
h
e
A
V
R

a
n
d
t
clkI/O

clkASY

CPU Clock – clkCPU The CP


Exampl
data me
general

I/O Clock – clkI/O The I/O


The I/O
rupts ar
clock is
nously w

Flash Clock – clkFLASH The Fla


taneous

Asynchronous Timer The Asy


Clock – clkASY from an
Timer/C

24
66
T–
AV
R–
07/
10
ATmega16(L)

ADC Clock – clkADC The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks
in order to reduce noise generated by digital circuitry. This gives more accurate ADC conversion
results.

Clock Sources The device has the following clock source options, selectable by Flash Fuse bits as shown
below. The clock from the selected source is input to the AVR clock generator, and routed to the
appropriate modules.
(1)
Table 2. Device Clocking Options Select
Device Clocking Option CKSEL3..0
External Crystal/Ceramic Resonator 1111 - 1010
External Low-frequency Crystal 1001
External RC Oscillator 1000 - 0101
Calibrated Internal RC Oscillator 0100 - 0001
External Clock 0000
Note: 1. For all fuses “1” means unprogrammed while “0” means programmed.
The various choices for each clocking option is given in the following sections. When the CPU
wakes up from Power-down or Power-save, the selected clock source is used to time the start-
up, ensuring stable Oscillator operation before instruction execution starts. When the CPU
starts from Reset, there is as an additional delay allowing the power to reach a stable level
before commencing normal operation. The Watchdog Oscillator is used for timing this real-time
part of the start-up time. The number of WDT Oscillator cycles used for each time-out is shown
in Table 3. The frequency of the Watchdog Oscillator is voltage dependent as shown in
“ATmega16 Typ- ical Characteristics” on page 299.

Table 3. Number of Watchdog Oscillator Cycles


Typ Time-out (VCC = 5.0V) Typ Time-out (VCC = 3.0V) Number of Cycles
4.1 ms 4.3 ms 4K (4,096)
65 ms 69 ms 64K (65,536)
setting ensures that all users can make their
Default Clock The desired clock source setting using an In-
Source device is System or Parallel Programmer.
shipped
with XTAL1 and XTAL2 are input and output,
CKSEL = respectively, of an inverting amplifier which
Crystal Oscillator “0001” can be con-figured for use as an On-chip
and SUT Oscillator, as shown in Figure 12. Either a
= “10”. quartz crystal or a ceramic resonator may be
The used. The CKOPT Fuse selects between two
default different Oscillator amplifier modes. When
clock CKOPT is programmed, the Oscillator output
source will oscillate will a full rail-to-rail swing on the
setting is output. This mode is suitable when operating
therefore in a very noisy environment or when the output
the 1 from XTAL2 drives a second clock buffer. This
MHz mode has a wide frequency range. When
Internal CKOPT is unprogrammed, the Oscillator has a
RC smaller output swing. This reduces power
Oscillator consumption considerably. This mode has a
with limited frequency range and it can not be used
longest to drive other clock buffers.
startup
For resonators, the maximum frequency is 8
time. This
MHz with CKOPT unprogrammed and 16 MHz
default
with CKOPT programmed. C1 and C2 should
always be equal for both crystals and resonators. The electroma the environment. Some initial guidelines for
optimal value of the capacitors depends on the crystal orgnetic
resonator in use, the amount of stray capacitance, and the noise of
2
5
2466T–AVR–07/10
ATmega16(L)

choosing capacitors for use with crystals are given in Table 4. For ceramic resonators, the
capacitor values given by the manufacturer should be used.

Figure 12. Crystal Oscillator Connections

C2
XTAL2

C1
XTAL1

GND

The Oscillator can operate in three different modes, each optimized for a specific frequency
range. The operating mode is selected by the fuses CKSEL3..1 as shown in Table 4.

Table 4. Crystal Oscillator Operating Modes


Frequency Range Recommended Range for Capacitors
CKOPT CKSEL3..1 (MHz) C1 and C2 for Use with Crystals (pF)

1 101 (1) 0.4 - 0.9 –


1 110 0.9 - 3.0 12 - 22
1 111 3.0 - 8.0 12 - 22
0 101, 110, 111 1.0 ≤ 12 - 22
Note: 1. This option should not be used with crystals, only with ceramic resonators.
26
2466T–AVR–07/10
ATmega16(L)

The CKSEL0 Fuse together with the SUT1..0 Fuses select the start-up times as shown in
Table 5.

Table 5. Start-up Times for the Crystal Oscillator Clock Selection


Start-up Time from Additional Delay
Power-down and from Reset
CKSEL0 SUT1..0 Power-save (VCC = 5.0V) Recommended Usage
(1) Ceramic resonator, fast
0 00 258 CK 4.1 ms rising power

(1) Ceramic resonator, slowly


0 01 258 CK 65 ms rising power

(2) Ceramic resonator, BOD


0 10 1K CK – enabled

(2) Ceramic resonator, fast


0 11 1K CK 4.1 ms rising power

(2) Ceramic resonator, slowly


1 00 1K CK 65 ms rising power
Crystal Oscillator, BOD
1 01 16K CK –
enabled
Crystal Oscillator, fast
1 10 16K CK 4.1 ms
rising power
Crystal Oscillator, slowly
1 11 16K CK 65 ms
rising power
Notes: 1. These options should only be used when not operating close to the maximum frequency of the
device, and only if frequency stability at start-up is not important for the application. These
options are not suitable for crystals.
2. These options are intended for use with ceramic resonators and will ensure frequency stability at start-
up. They can also be used with crystals when not operating close to the maximum fre-quency of the device, and
if frequency stability at start-up is not important for the application.

27
2466T–AVR–07/10
ATmega16(L)
Crystal
Oscillator must
Lo T be selected by
setting the
w- o
CKSEL Fuses
fre u to “1001”. The
qu s crystal should
e
en a be con-nected
cy 3 as shown in
Cry 2. Figure 12. By
stal7 programming
the CKOPT
Os 6
Fuse, the user
cill 8 can enable
ato k internal
r H capacitors on
z
w XTAL1 and
at XTAL2,
c thereby
h removing the
cr need for
y external
st capacitors.
al The inter-nal
a capacitors
s have a
th nominal value
e of 36 pF.
cl When this
o Oscillator is
c selected, start-
k up times are
s determined by
o the SUT
ur Fuses as
c shown in
e Table 6.
fo
r Table 6.
th Start-up Times
e for the Low-
d frequency
e Crystal
vi Oscillator
c Clock
e, Selection
th Start-up Tim
e Power-dow
L SUT1..0 Power-s
o 00 1K CK
w
01 1K CK
-
fr 10 32K C
e 11
q
Note: 1. These
u opti
e ons
n sho
c uld
y onl
y be at imp
used st orta
if ar nt
freq t- for
uenc up the
y is app
stabi no licat
lity t ion.
onfigur m ch
EF ation o oos
xt o shown e R
in and
er
Figure C,
r 13 can refe
nt be r to
al i used. the
m
Ri The Ext
Cn freque ern
Og ncy is al
s roughl RC
y Osc
ci i estima illat
ll n ted by or
s
ate the app
on equati licat
r s on f = ion
i 1/(3RC not
t ). C e.
i should
v be at Fig
e least ure
22 pF. 13.
a By Ext
progra ern
p
mming al
p
the RC
l
CKOP Con
i
T figu
c rati
a Fuse,
the on
t
i user
o can
n enable
s an
, interna
l 36 pF
t capacit
h or
e betwe
en
e XTAL1
x and
t GND,
thereb The
e
y Osc
r
removi illat
n
ng the or
a
need can
l
for an ope
extern rate
R in
C al
capacit four
or. For diff
c
er L ting
e 3 Modes
nt .
m.
o 0
d
es a
, s
e
ac s
h h
o o
pti w
mi n
ze
d i
fo n
r
a T
sp a
ec b
ifi l
c e
fr
e 7
q .
u
e T
nc a
y b
ra l
n e
g
e. 7
T .
h
e E
o x
p t
er e
ati r
n n
g a
ml
o
d R
e C
is
se O
le s
ct c
i
e
l
d
l
by
a
th
t
e
o
fu r
se
s O
Cp
K e
S r
E a
CKSEL3..0
0101
0110
0111
1000
28
24
66
T–
AV
R–
07/
10
ATmega16(L)
e External RC
Oscillator
W Clock
he Selection
n Start-up Tim
thi Power-dow
s SUT1..0 Power-s
Os 00 18 CK
cill
at 01 18 CK
or 10 18 CK
is (1
11 6 CK
sel
Note: 1. This
ec
option should not
te be used when
d, operating close to
st the maximum
art frequency of the
Cal - device.
ibr up
ate ti The Calibrated
d m Internal RC
Oscillator
Int es
provides a fixed
ern ar 1.0 MHz, 2.0
e
al de MHz, 4.0 MHz,
RC ter or 8.0 MHz
Os mi clock. All
frequencies are
cill ne
nominal values
ato d at 5V and 25°C.
r by This clock may
th
e be selected as
S the system-
clock by
UT
programming
Fu
the CKSEL
se
Fuses as shown
s
in Table 9. If
as
selected, it will
sh
operate with no
ow
external
n components.
in The CKOPT
Ta Fuse should
bl always be
e unpro-grammed
8. when using this
clock option.
Ta During Reset,
bl hardware loads
e the calibration
8. byte into the
St OSCCAL
art Register and
- thereby
up automatically
Ti calibrates the
m RC Oscillator.
es At 5V, 25°C and
for 1.0 MHz, 2.0
th MHz, 4.0 MHz
or ur et time-out. For
8.0 ac more
MHz y information on
Osci at the pre-
llato an programmed
r y cali-bration
freq giv value, see the
uen en section
cy VC “Calibration
sele Byte” on page
cted C 261.
, an
this d Table 9. Internal Calibr
calib Te
ratio mp CKSEL3..0
n er 0001
(1)

give atu
0010
s are.
freq W 0011
uen he 0100
cy n
Note: 1. The
withi thi device is
n s
shipped with this
±3% Os option selected.
of cill
the ato When this
nom r is Oscillator is
inal us selected, start-
freq ed up times are
uen as determined by
cy. the the SUT Fuses
Usin Ch as shown in
g ip Table 10.
calib Cl XTAL1 and
ratio oc XTAL2 should
n k, be left
met the unconnected
hod W (NC).
s asatc
des hd
crib og
ed Os
in cill
appl ato
icati r
on will
note stil
s l
avail be
able us
at ed
ww for
w.at the
mel. W
com atc
/avr hd
it isog
pos Ti
sible me
to r
achi an
eve d
±1% for
acc the
res
Table 10. Start-up Times for the In
Start-up Time from
Power-down and
SUT1..0 Power-save
00 6 CK
01 6 CK

10 (1) 6 CK
11
Note: 1. The device is shipped wit
2
9
2466
T–
AVR–
07/10
ATmega16(L)
m the Internal
Oscillator to
Osc remove
illat Bit process vari-
or ations from the
Cali Read/Write Oscillator
brat frequency.
Initial Value
ion This is done
Reg automatically
iste •
during Chip
r – Bi Reset. When
OS ts OSCCAL is
CC 7. zero, the
AL .0
– lowest
C available
A frequency is
L chosen.
7. Writing non-
.0 zero values to
: this regis-ter
O will increase
s the frequency
ci of the Internal
ll Oscillator.
at Writing $FF to
or the register
C gives the
al highest
ib available
ra
frequency. The
ti
calibrated
o
Oscillator is
n
V used to time
al EEPROM and
u Flash access.
e If EEPROM or
Flash is
W written, do not
riti calibrate to
n more than
g 10% above the
th nominal fre-
e quency.
ca Otherwise, the
lib EEPROM or
ra Flash write
tio may fail. Note
n that the
by Oscillator is
te intended for
to calibration to
thi 1.0 MHz, 2.0
s MHz, 4.0 MHz,
a or 8.0 MHz.
d Tuning to other
dr values is not
es guaranteed, as
s indicated in
wi Table 11.
ll
tri Table 11. Internal RC O
OSCCAL Value

30
24 66T–AVR–07/10

E
x
t
e
r Timer/Count
n er
a Oscillator
l
C
l
o
c
k
uld be driven as
ATmega16(L)
shown in Figure
14. To run the
device on an
T external clock,
o the CKSEL
Fuses must be
d programmed to
r “0000”. By
i programming
v the CKOPT
e Fuse, the user
can enable an
t internal 36 pF
h capacitor
e between XTAL1
and GND.
d
e Figure 14.
v External Clock
i Drive
c Configuration
e

f
r
o
m
EXTERNAL
a CLOCK
n SIGNAL

e
x
t
e
r
n When this clock
a source is
l selected, start-
c up times are
l determined by
o the SUT Fuses
c as shown in
k Table 12.

s Table 12. Start-up Times


o
Start-up Ti
u Power-do
r
SUT1..0 Power-
c
e 00 6C
, 01 6C
X 10 6C
T
A 11
L When applying
1 an external
clock, it is
s required to avoid
h sudden changes
o in the applied
c ion in frequency
l of more than 2%
o from one clock
c cycle to the next
k can lead to
unpredictable
f behavior. It is
r required to
e ensure that the
- MCU is kept in
q reset during
u such changes in
e the clock
n frequency.
c
y For AVR
microcontrollers
t with
o Timer/Counter
Oscillator pins
e (TOSC1 and
n TOSC2), the
s crystal is
u connected
r directly between
e the pins. No
external
s capacitors are
t needed. The
a Oscillator is opti-
b mized for use
l with a 32.768
e kHz watch
crystal. Applying
o an external
p clock source to
e TOSC1 is not
r recommended.
a
Note: The
t Timer/Co
i unter
o Oscillator
n uses the
same
o type of
f crystal
t oscillator
h as Low-
e Frequenc
y
Oscillator
M and the
C internal
U capacitor
. s have
A the same
nominal
v value of
a 36 pF.
r
i
a
t
31
2
4
6
6
T

A
V
R

0
7
/
1
0
ATmega16(L)
modes
allowing the
user to tailor
Po Sl the power
we ee consump-tion
p
r m to the
application’s
Ma od requirements.
na es
en To enter any of
ge ab the six sleep
m le modes, the SE
en th
e
bit in MCUCR
must be written
t ap to logic one
an pli and a SLEEP
ca instruction
d tio must be
Sl n executed. The
ee to
sh
SM2, SM1,
and SM0 bits
p ut in the MCUCR
M do Register select
w which sleep
od n mode (Idle,
es un ADC Noise
us Reduction,
ed Power-down,
m Power-save,
od Standby, or
ul Extended
es Standby) will
in be activated by
th the SLEEP
e instruction.
M See Table 13
C for a summary.
MC U, If an enabled
U th
interrupt
Con er
occurs while
trol eb
the MCU is in a
Reg y
iste sa sleep mode,
r the MCU
vi
– ng wakes up. The
MC po MCU is then
UC w halted for four
R er. cycles in
addition to the
Th
start-up time, it
e
executes the
AV
interrupt
R
pr routine, and
ov resumes
id execution from
es the instruction
va following
rio SLEEP. The
us contents of the
sl Register File
ee and SRAM are
p unaltered when
the ib
Bit 7
devi u- SM2
ce tio Read/Write R/W R
wak n. Initial Value 0
es Th
up e • Bits 7, 5, 4 – SM2..0:
fro fig
m ur These bits
slee e select between
p. Ifis the six
a he available sleep
Res lpf modes as
et ul shown in
occ in Table 13.
urs se
Table 13. Sleep Mode S
duri le
ng cti SM2 SM1
slee ng 0 0
p an
0 0
mod ap
e, pr 0 1
the op 0 1
MC ria
1 0
U te
wak sl 1 0
es ee 1 1
up p
and m 1 1
exe od Note: 1. Standby mod
cute e. resonators.
s
fro Th • Bit 6 – SE:
e Sleep Enable
m
M
the The SE bit
C
Res U must be written
et C to logic one to
Vect on make the MCU
or. tro enter the sleep
l mode when the
Figu R SLEEP
re eg instruction is
11 ist executed. To
er avoid the MCU
on
co entering the
pag
nt sleep mode
e 24
ai unless it is the
pres ns
ents co programmers
the ntr purpose, it is
diffe ol recommended
rent bit to write the
cloc s Sleep Enable
k for (SE) bit to one
syst po just before the
ems w execution of
in er the SLEEP
the m instruction and
AT an to clear it
meg ag immediately
a16, e after waking
and m up.
their en
distr t.
32
2466
T–
AVR–
07/10
ATmega16(L)

Idl P When the


e o SM2..0 bits are
Mo w written to 000,
the SLEEP
de er instruction
- makes the
s MCU enter Idle
a mode, stopping
v the CPU but
allowing SPI,
e USART, Analog
M Comparator,
o ADC, Two-wire
d Serial
e Interface,
Timer/Counters
AD , Watchdog,
and the
C
interrupt
Noi system to
se continue
Re operating. This
du sleep mode
basically halts
cti
clkCPU and
on
clkFLASH, while
Mo
allowing the
de other clocks to
run.
Idle mode
enables the
MCU to wake
up from
external
triggered
interrupts as
well as internal
ones like the
Po Timer Overflow
wer and USART
- Transmit
do Complete
wn interrupts. If
wake-up from
Mo
the Analog
de Comparator
interrupt is not
required, the
Analog
Comparator
can be
powered down
by setting the
ACD bit in the
Analog
Comparator
Control and
Status Register
– ACSR. This
will e operat-
red Re ing (if
uce du enabled). This
sleep mode
pow cti basically halts
er on
clkI/O, clkCPU,
con mo
sum de, and clkFLASH,
while allowing
ptio sto the other
n inppi clocks to run.
Idle ng
mod the This improves
e. IfCP the noise
the U environment
AD but for the ADC,
C isall enabling higher
ena ow resolution
ing measurements
bled
the . If the ADC is
, a
AD enabled, a
con
C, conversion
vers
the starts
ion
Ex automatically
start ter
s nal when this
auto Int mode is
mati err entered. Apart
- form the ADC
upt
call s, Conversion
y the Complete
whe Tw interrupt, only
n o- an External
this wir Reset, a
mod e Watchdog
e isSe Reset, a
ente rial Brown-out
red. Int Reset, a Two-
erf wire Serial
Interface
Whe ac
e Address Match
n
Interrupt, a
the ad
Timer/Counter
SM2 dr
2 interrupt, an
..0 es
bits s
SPM/EEPROM
are wa ready interrupt,
writt tch an External
en , level interrupt
to Ti on INT0 or
001, me INT1, or an
the r/C external inter-
SLE ou rupt on INT2
EP nte can wake up
instr r2 the MCU from
ucti an ADC Noise
on d Reduction
mak the mode.
es W
the atc When the
MC hd SM2..0 bits are
U og written to 010,
ente to the SLEEP
r co
instruction
AD nti makes the
C nu MCU enter
Nois e
Pow og upt on INT2
er- Re can wake up
dow se the MCU. This
n t, sleep mode
mod a basically halts
e. InBr all generated
this ow clocks,
mod n- allowing oper-
e, ou ation of
the t asynchronous
Ext Re modules only.
ern se
Note that if a
al t,
level triggered
Osc a
interrupt is
illat Tw
used for wake-
or iso-
up from Power-
stop wir
down mode,
ped, e
the changed
whil Se
level must be
e ria held for some
the l time to wake
Ext Int up the MCU.
ern erf Refer to
al ac “External
inter e Interrupts” on
rupt ad page 68 for
s, dr details.
the es
Two s When waking
- m up from Power-
wire at down mode,
Seri ch there is a delay
al int from the wake-
Inte err up condition
rfac up occurs until the
e t, wake-up
add an becomes
ress Ex effective. This
wat ter allows the
ch, na clock to restart
and l and become
the lev stable after
Wat el having been
chd int stopped. The
og err wake-up period
cont up is defined by
inue t the same
ope on CKSEL Fuses
ratin IN that define the
g (ifT0 reset time-out
ena or period, as
bled IN described in
). T1 “Clock
Onl , Sources” on
y anor page 25.
Ext an
ern Ex When the
al ter SM2..0 bits are
Res na written to 011,
et, al the SLEEP
Wat int instruction
chd err makes the
MC er/ t from
U Co Timer/Counter
ente un 2 if the
r ter corresponding
Pow 2 Timer/Counter
er- wil 2 interrupt
sav l enable bits are
e ru set in TIMSK,
mod n and the Global
e. du Interrupt
This rin Enable bit in
mod g SREG is set.
e is sle
iden ep If the
tical . Asynchronous
to Th Timer is NOT
Pow e clocked
er- de asynchronously,
dow vic Power-down
n, e mode is
with ca recommended
one n instead of
exc wa Power-save
epti ke mode because
on: up the contents of
the registers in
If fro
the
Tim m
Asynchronous
er/C eit
Timer should be
ount he
er2 r considered
is Ti undefined after
cloc m wake-up in
ked er Power-save
asy Ov mode if AS2 is
nchr erf 0.
ono lo This sleep
usly,w mode basically
that or halts all clocks
is, O except clkASY,
the ut allowing
AS2 pu operation only
bit t of
in Co asynchronous
modules,
AS m
including
SR pa Timer/Counter
is re 2 if clocked
set, ev asynchronously
Tim en .
3
3
2466
T–
AVR–
07/10
ATmega16(L)
, the SLEEP
instruction
Sta W makes the
MCU enter
nd he
Standby mode.
by n This mode is
Mo th identical to
e
de S Power-down
M with the
2.. exception that
0 the Oscillator is
bit kept running.
Ext s From Standby
en ar mode, the
de e device wakes
up in six clock
d 11
cycles.
Sta 0
nd an
d When the
by SM2..0 bits are
an
Mo ex 111 and an
de ter external
na crystal/resonat
l or clock option
cr is selected, the
ys SLEEP
tal instruction
/re makes the
so MCU enter
na Extended
tor Standby mode.
cl This mode is
oc identical to
k Power-save
op mode with the
tio exception that
n the Oscillator is
is kept running.
se From Extended
le Standby mode,
ct the device
ed wakes up in six
clock cycles..
a s in the Power
T n Differe
a d nt
Down
bl Sleep
e W Modes
1 a Power
4. k
A e Save
cti Sleep
ve U Mode Standby (1)
Cl p
Idle Exten-
oc
ADC ded
k S (1)
Do Noise Standby
o u Notes: 1.
mr Redu- External
ai c ction Crystal or
resonator
ns e selected as
cl s evel
oc e interrupt
k t INT1
so . and
3.ur INT0.
ce
Onl
. y
2.
If AS2I
bit N
in T
A 2
S
S o
R r
is l 34

24
66
T–
AV
R–
07/
10
ATmega16(L)

Minimizing Power There are several issues to consider when trying to minimize the power consumption in an AVR
Consumption controlled system. In general, sleep modes should be used as much as possible, and the sleep
mode should be selected so that as few as possible of the device’s functions are operating. All
functions not needed should be disabled. In particular, the following modules may need special
consideration when trying to achieve the lowest possible power consumption.

Analog to Digital If enabled, the ADC will be enabled in all sleep modes. To save power, the ADC should be dis-
Converter abled before entering any sleep mode. When the ADC is turned off and on again, the next
conversion will be an extended conversion. Refer to “Analog to Digital Converter” on page 204
for details on ADC operation.

Analog Comparator When entering Idle mode, the Analog Comparator should be disabled if not used. When entering
ADC Noise Reduction mode, the Analog Comparator should be disabled. In the other sleep
modes, the Analog Comparator is automatically disabled. However, if the Analog Comparator is
set up to use the Internal Voltage Reference as input, the Analog Comparator should be dis-
abled in all sleep modes. Otherwise, the Internal Voltage Reference will be enabled,
independent of sleep mode. Refer to “Analog Comparator” on page 201 for details on how to
configure the Analog Comparator.

Brown-out Detector If the Brown-out Detector is not needed in the application, this module should be turned off. If the
Brown-out Detector is enabled by the BODEN Fuse, it will be enabled in all sleep modes, and
hence, always consume power. In the deeper sleep modes, this will contribute significantly to
the total current consumption. Refer to “Brown-out Detection” on page 40 for details on how to
configure the Brown-out Detector.

Internal Voltage The Internal Voltage Reference will be enabled when needed by the Brown-out Detector, the
Reference Analog Comparator or the ADC. If these modules are disabled as described in the sections
above, the internal voltage reference will be disabled and it will not be consuming power. When
turned on again, the user must allow the reference to start up before the output is used. If the
reference is kept on in sleep mode, the output can be used immediately. Refer to “Internal Volt-
age Reference” on page 42 for details on the start-up time.

Watchdog Timer If the Watchdog Timer is not needed in the application, this module should be turned off. If the
Watchdog Timer is enabled, it will be enabled in all sleep modes, and hence, always consume
power. In the deeper sleep modes, this will contribute significantly to the total current consump-
tion. Refer to “Watchdog Timer” on page 42 for details on how to configure the Watchdog Timer.

Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. The
most important thing is then to ensure that no pins drive resistive loads. In sleep modes where
the both the I/O clock (clkI/O) and the ADC clock (clkADC) are stopped, the input buffers of the
device will be disabled. This ensures that no power is consumed by the input logic when not
needed. In some cases, the input logic is needed for detecting wake-up conditions, and it will
then be enabled. Refer to the section “Digital Input Enable and Sleep Modes” on page 54 for
details on which pins are enabled. If the input buffer is enabled and the input signal is left floating
or have an analog signal level close to VCC/2, the input buffer will use excessive power.

35
2466T–AVR–
07/10
ATmega16(L)

JTAG Interface and If the On-chip debug system is enabled by the OCDEN Fuse and the chip enter Power down or
On-chip Debug Power save sleep mode, the main clock source remains enabled. In these sleep modes, this will
System contribute significantly to the total current consumption. There are three alternative ways to
avoid this:
• Disable OCDEN Fuse.
• Disable JTAGEN Fuse.
• Write one to the JTD bit in MCUCSR.
The TDO pin is left floating when the JTAG interface is enabled while the JTAG TAP controller is
not shifting data. If the hardware connected to the TDO pin does not pull up the logic level,
power consumption will increase. Note that the TDI pin for the next device in the scan chain con-
tains a pull-up that avoids this problem. Writing the JTD bit in the MCUCSR register to one or
leaving the JTAG fuse unprogrammed disables the JTAG interface.

36
2466T–AVR–
07/10
ATmega16(L)

System Control
and Reset
Resetting the AVR During Reset, all I/O Registers are set to their initial values, and the program starts execution from the
Reset Vector. The instruction placed at the Reset Vector must be a JMP – absolute jump –
instruction to the reset handling routine. If the program never enables an interrupt source, the
Interrupt Vectors are not used, and regular program code can be placed at these locations. This
is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in
the Boot section or vice versa. The circuit diagram in Figure 15 shows the reset logic. Table 15
defines the electrical parameters of the reset circuitry.
The I/O ports of the AVR are immediately reset to their initial state when a reset source goes
active. This does not require any clock source to be running.
After all reset sources have gone inactive, a delay counter is invoked, stretching the Internal
Reset. This allows the power to reach a stable level before normal operation starts. The time-
out period of the delay counter is defined by the user through the CKSEL Fuses. The different
selec-tions for the delay period are presented in “Clock Sources” on page 25.

Reset Sources The ATmega16 has five sources of reset:


1• Power-on Reset.
The MCU is reset when the supply voltage is below the Power-on Reset threshold (V POT).
2• External Reset.
The MCU is reset when a low level is present on the RESET pin for longer than the
minimum pulse length.
3• Watchdog Reset.
The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled.
4• Brown-out Reset.
The MCU is reset when the supply voltage V CC is below the Brown-out Reset
threshold (VBOT) and the Brown-out Detector is enabled.
5• JTAG AVR Reset.
The MCU is reset as long as there is a logic one in the Reset Register, one of the scan
chains of the JTAG system. Refer to the section “IEEE 1149.1 (JTAG) Boundary-scan”
on page 228 for details.
37
2466T–AVR–07/10
ATmega16(L)

Figur
e 15.
Reset DATA BUS
Logic

MCU Control and


Status
Register
(MCUCSR)

JTRF
EXTRF
PORF

WDRF
BORF
COUNTER RESET
CK Delay Counters
INTERNAL RESET
Gen TIMEOUT
erat
or

CKSEL[
3:0]
SUT[
1:0]
belo
w
VPO
Ta
bl T(falli
e ng).
15
2.
. BOT
R may
es be
et belo
w
C nomi
ha nal
ra mini
mum
ct oper
eri ating
sti volta
cs ge
for
som
Symbol
e
devic
es.
For
devic
es
wher
e
this
is
the
case
, the
devic
e is
teste
d
dow
n to
VCC
=
VBOT
V
durin
g the
No prod
tesuctio
: n
test.
1. This
Th guar-
e ante
Po es
we that
r- a
on Brow
Re n-out
setRese
wil t will
l occu
no r
t befor
wo e
rk VCC
unldrop
es s to
s a
th volta
e ge
su wher
pple
y corre
vol ct
ta oper
ge ation
ha of
s the
be micr
en ocon
246
6T–
AV
R–
07/
10
ATmega16(L)

Power-on Reset A Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detection level
is defined in Table 15. The POR is activated whenever VCC is below the detection level. The
POR circuit can be used to trigger the Start-up Reset, as well as to detect a failure in supply
voltage.
A Power-on Reset (POR) circuit ensures that the device is reset from Power-on. Reaching the
Power-on Reset threshold voltage invokes the delay counter, which determines how long the
device is kept in RESET after VCC rise. The RESET signal is activated again, without any delay,
when VCC decreases below the detection level.

Figure 16. MCU Start-up, RESET Tied to VCC.


V
V POT
CC

V
RESET RST

t
TIME-OUT TOUT

INTERNAL
RESET

Figure 17. MCU Start-up, RESET Extended Externally


V
POT
V
CC

V
RESET RST

t
TIME-OUT TOUT

INTERNAL
RESET

39
2466T–AVR–07/10
ATmega16(L)

External Reset An External Reset is generated by a low level on the RESET pin. Reset pulses longer than the
minimum pulse width (see Table 15) will generate a reset, even if the clock is not running.
Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the
Reset Threshold Voltage – VRST – on its positive edge, the delay counter starts the MCU after
the Time-out period tTOUT has expired.

Figure 18. External Reset During Operation


CC

Brown-out Detection ATmega16 has an On-chip Brown-out Detection (BOD) circuit for monitoring the V CC level dur-ing
operation by comparing it to a fixed trigger level. The trigger level for the BOD can be selected
by the fuse BODLEVEL to be 2.7V (BODLEVEL unprogrammed), or 4.0V (BODLEVEL
programmed). The trigger level has a hysteresis to ensure spike free Brown-out Detection. The
hysteresis on the detection level should be interpreted as VBOT+ = VBOT + VHYST/2 and VBOT- =
V -V /2.
BOT HYST
The BOD circuit can be enabled/disabled by the fuse BODEN. When the BOD is enabled (BODEN
programmed), and VCC decreases to a value below the trigger level (V BOT- in Figure 19), the
Brown-out Reset is immediately activated. When V CC increases above the trigger level
(VBOT+ in Figure 19), the delay counter starts the MCU after the Time-out period t TOUT has
expired.
The BOD circuit will only detect a drop in VCC if the voltage stays below the trigger level for lon-
ger than tBOD given in Table 15.

Figure 19. Brown-out Reset During Operation

V V
CC V BOT+
BOT-

RESET

t
TOUT
TIME-OUT

INTERNAL
RESET
40
2466T–AVR–07/10
ATmega16(L)

Watchdog Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On
the falling edge of this pulse, the delay timer starts counting the Time-out period t TOUT. Refer to
page 42 for details on operation of the Watchdog Timer.

Figure 20. Watchdog Reset During Operation


CC

CK

MCU Control and The MCU Control and Status Register provides information on which reset source caused an
Status Register – MCU Reset.
MCUCSR Bit 7 6 5 4 3 2 1 0
JTD ISC2 – JTRF WDRF BORF EXTRF PORF MCUCSR
Read/Write R/W R/W R R/W R/W R/W R/W R/W
Initial Value 0 0 0 See Bit Description

• Bit 4 – JTRF: JTAG Reset Flag


This bit is set if a reset is being caused by a logic one in the JTAG Reset Register selected by
the JTAG instruction AVR_RESET. This bit is reset by a Power-on Reset, or by writing a logic
zero to the flag.

• Bit 3 – WDRF: Watchdog Reset Flag


This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.

• Bit 2 – BORF: Brown-out Reset Flag


This bit is set if a Brown-out Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.

• Bit 1 – EXTRF: External Reset Flag


This bit is set if an External Reset occurs. The bit is reset by a Power-on Reset, or by writing a
logic zero to the flag.

• Bit 0 – PORF: Power-on Reset Flag


This bit is set if a Power-on Reset occurs. The bit is reset only by writing a logic zero to the flag.
To make use of the Reset Flags to identify a reset condition, the user should read and then
reset the MCUCSR as early as possible in the program. If the register is cleared before another
reset occurs, the source of the reset can be found by examining the Reset Flags.
41
2466T–AVR–07/10
ATmega16(L)

Internal Voltage ATmega16 features an internal bandgap reference. This reference is used for Brown-out Detec-
Reference tion, and it can be used as an input to the Analog Comparator or the ADC. The 2.56V reference
to the ADC is generated from the internal bandgap reference.

Voltage Reference The voltage reference has a start-up time that may influence the way it should be used. The
Enable Signals and start-up time is given in Table 16. To save power, the reference is not always turned on. The ref-
Start-up Time erence is on during the following situations:
1. When the BOD is enabled (by programming the BODEN Fuse).
2. When the bandgap reference is connected to the Analog Comparator (by setting the
ACBG bit in ACSR).
3. When the ADC is enabled.
Thus, when the BOD is not enabled, after setting the ACBG bit or enabling the ADC, the user
must always allow the reference to start up before the output from the Analog Comparator or
ADC is used. To reduce power consumption in Power-down mode, the user can avoid the three
conditions above to ensure that the reference is turned off before entering Power-down mode.

Table 16. Internal Voltage Reference Characteristics


Symbol Parameter Min Typ Max Units
V
BG Bandgap reference voltage 1.15 1.23 1.4 V
t
BG Bandgap reference start-up time 40 70 µs
I
BG Bandgap reference current consumption 10 µA

Watchdog Timer The Watchdog Timer is clocked from a separate On-chip Oscillator which runs at 1 MHz. This is
the typical value at VCC = 5V. See characterization data for typical values at other V CC levels. By
controlling the Watchdog Timer prescaler, the Watchdog Reset interval can be adjusted as
shown in Table 17 on page 43. The WDR – Watchdog Reset – instruction resets the Watchdog
Timer. The Watchdog Timer is also reset when it is disabled and when a Chip Reset occurs.
Eight different clock cycle periods can be selected to determine the reset period. If the reset
period expires without another Watchdog Reset, the ATmega16 resets and executes from the
Reset Vector. For timing details on the Watchdog Reset, refer to page 41.
To prevent unintentional disabling of the Watchdog, a special turn-off sequence must be fol-
lowed when the Watchdog is disabled. Refer to the description of the Watchdog Timer Control
Register for details.

Figure 21. Watchdog Timer

WATCHDOG
OSCILLATOR

42
2466T–AVR–07/10
ATmega16(L)
d bits in the
ATmega16
Wat and will
chd always read
Bit
og as zero.
Tim Read/Write
er • Bit 4 –
Initial Value
Con WDTOE:
trol Watchdog
• Turn-off
Reg
iste Enable
r– B
i This bit must
WD
t be set when
TC
s the WDE bit
R
is written to
7 logic zero.
. Otherwise,
. the
5 Watchdog
will not be
– disabled.
Once written
R to one,
e hardware will
s clear this bit
: after four
clock cycles.
R Refer to the
e description of
s the WDE bit
e for a
r
Watchdog
v
disable
e
procedure.
d

B • Bit 3 –
i WDE:
t Watchdog
s Enable

T When the
h WDE is
e written to
s logic one, the
e Watchdog
Timer is
b enabled, and
i if the WDE is
t written to
s logic zero,
the
a Watchdog
r Timer
e function is
disabled.
r WDE can
e only be
s
cleared if the
e
WDTOE bit
r
v has logic
e level one. To
disa ugh it is
ble set to
an one
ena before
bled the
Wat disable
chd operation
og starts.
Tim 2. Within the
er, next four
the clock cycles,
follo write a logic
win 0 to WDE.
g This disables
proc the
edu Watchdog.
re
mus • Bits 2..0 –
t be WDP2,
follo WDP1,
wed WDP0:
: Watchdog
Timer
1. I Prescaler 2,
n 1, and 0

t The WDP2,
h WDP1, and
e WDP0 bits
determine
s the
a Watchdog
m Timer
e prescaling
when the
o Watch-dog
p Timer is
e enabled. The
r different
a prescaling
t values and
i their
o correspondin
n g Timeout
, Periods are
shown in
w Table 17.
r
i
t
e

l
o
g
i
c

o
n
e
Table 17. Watchdog Timer Presca
Num
WDP2 WDP1 WDP0 Osci
0 0 0 16
0 0 1 32
0 1 0 64
0 1 1 128
1 0 0 256
1 0 1 512
1 1 0 1,024
1 1 1 2,048

4
3

2466
T–
AVR–
07/10
ATmega16(L)

The following code example shows one assembly and one C function for turning off the WDT.
The example assumes that interrupts are controlled (for example by disabling interrupts
globally) so that no interrupts will occur during execution of these functions.
Assembly Code Example
WDT_off:

1; Reset WDT
WDR

2; Write logical one to WDTOE and WDE


in r16, WDTCR
ori r16, (1<<WDTOE)|(1<<WDE)
out WDTCR, r16

3; Turn off WDT


ldi r16, (0<<WDE)
out WDTCR, r16
ret

C Code Example
void WDT_off(void)
{
/* Reset
WDT*/ _WDR();
/* Write logical one to WDTOE and WDE */
WDTCR |= (1<<WDTOE) | (1<<WDE);
/* Turn off WDT
*/ WDTCR = 0x00;
}
44
2466T–AVR–07/10
ATmega16(L)
performed
in
Int T ATmega16.
h For a
err general
up explanation
ts of the AVR
interrupt
handling,
refer to
“Reset and
Interrupt
Handling”
on page
13.
vari a so the
In ous l case if
te co the
T mbi Reset
rr
a nati Vector
u ons is in
p of the
t Vector BO
No.
Applic
V OT ation
e RS sectio
ct T n
o and while
r IVS the
EL Interru
s
sett pt
in ing Vector
A s. If s are
T the in the
m pro Boot
e gra sectio
m n or
g
nev vice
a er versa.
1 ena
6 ble
s
an
inte
rru
pt
sou
rce,
the
Inte
rru
pt
Vec
Notes:
tors
are
not
use
d,
and
T reg
ular
pro
gra
m
cod
e
can
be
pla
ced
at
the
se
loc
atio
ns.
Thi
s is
4
5
24
66
T–
AV
R–
07/
10
ATmega16(L)

(1)
Table 19. Reset and Interrupt Vectors Placement
BOOTRST IVSEL Reset address Interrupt Vectors Start Address
1 0 $0000 $0002
1 1 $0000 Boot Reset Address + $0002
0 0 Boot Reset Address $0002
0 1 Boot Reset Address Boot Reset Address + $0002
Note: 1. The Boot Reset Address is shown in Table 100 on page 257. For the BOOTRST Fuse “1” means
unprogrammed while “0” means programmed.
The most typical and general program setup for the Reset and Interrupt Vector Addresses in
ATmega16 is:
Address Labels Code Comments
$000 jmp RESET ; Reset Handler
$002 jmp EXT_INT0 ; IRQ0 Handler
$004 jmp EXT_INT1 ; IRQ1 Handler
$006 jmp TIM2_COMP ; Timer2 Compare Handler
$008 jmp TIM2_OVF ; Timer2 Overflow Handler
$00A jmp TIM1_CAPT ; Timer1 Capture Handler
$00C jmp TIM1_COMPA ; Timer1 CompareA Handler
$00E jmp TIM1_COMPB ; Timer1 CompareB Handler
$010 jmp TIM1_OVF ; Timer1 Overflow Handler
$012 jmp TIM0_OVF ; Timer0 Overflow Handler
$014 jmp SPI_STC ; SPI Transfer Complete Handler
$016 jmp USART_RXC ; USART RX Complete Handler
$018 jmp USART_UDRE ; UDR Empty Handler
$01A jmp USART_TXC ; USART TX Complete Handler
$01C jmp ADC ; ADC Conversion Complete Handler
$01E jmp EE_RDY ; EEPROM Ready Handler
$020 jmp ANA_COMP ; Analog Comparator Handler
$022 jmp TWSI ; Two-wire Serial Interface Handler
$024 jmp EXT_INT2 ; IRQ2 Handler
$026 jmp TIM0_COMP ; Timer0 Compare Handler
$028 jmp SPM_RDY ; Store Program Memory Ready Handler
;
$02A RESET: ldi r16,high(RAMEND) ; Main program start
$02B out SPH,r16 ; Set Stack Pointer to top of RAM
$02C ldi r16,low(RAMEND)
$02D out SPL,r16
$02E sei ; Enable interrupts
$02F <instr> xxx
... ... ...

46
2466T–AVR–07/10
ATmega16(L)

When the BOOTRST Fuse is unprogrammed, the Boot section size set to 2 Kbytes and the
IVSEL bit in the GICR Register is set before any interrupts are enabled, the most typical and
general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels Code Comments
$000 RESET: ldi r16,high(RAMEND) ; Main program start
$001 out SPH,r16 ; Set Stack Pointer to top of RAM
$002 ldi r16,low(RAMEND)
$003 out SPL,r16
$004 sei ; Enable interrupts
$005 <instr> xxx
;
.org $1C02
$1C02 jmp EXT_INT0 ; IRQ0 Handler
$1C04 jmp EXT_INT1 ; IRQ1 Handler
... .... .. ;
$1C28 jmp SPM_RDY ; Store Program Memory Ready Handler

When the BOOTRST Fuse is programmed and the Boot section size set to 2 Kbytes, the most
typical and general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels Code Comments
.org $002
$002 jmp EXT_INT0 ; IRQ0 Handler
$004 jmp EXT_INT1 ; IRQ1 Handler
... .... .. ;
$028 jmp SPM_RDY ; Store Program Memory Ready Handler
;
.org $1C00
$1C00 RESET: ldi r16,high(RAMEND) ; Main program start
$1C01 out SPH,r16 ; Set Stack Pointer to top of RAM
$1C02 ldi r16,low(RAMEND)
$1C03 out SPL,r16
$1C04 sei ; Enable interrupts
$1C05 <instr> xxx

When the BOOTRST Fuse is programmed, the Boot section size set to 2 Kbytes and the IVSEL
bit in the GICR Register is set before any interrupts are enabled, the most typical and general
program setup for the Reset and Interrupt Vector Addresses is:
Address Labels Code Comments
.org $1C00
$1C00 jmp RESET ; Reset handler
$1C02 jmp EXT_INT0 ; IRQ0 Handler
$1C04 jmp EXT_INT1 ; IRQ1 Handler
... .... .. ;
$1C28 jmp SPM_RDY ; Store Program Memory Ready Handler
;
$1C2A RESET: ldi r16,high(RAMEND) ; Main program start
$1C2B out SPH,r16 ; Set Stack Pointer to top of RAM
$1C2C ldi r16,low(RAMEND)
$1C2D out SPL,r16
$1C2E sei ; Enable interrupts
$1C2F <instr> xxx

47
2466T–AVR–
07/10
ATmega16(L)
• Bit 1 – IVSEL: Inter
Mo T
vin h
g e When the
Inte G IVSEL bit is
rru e cleared (zero),
pts n the Interrupt
Bet er Vectors are
wee al placed at the
n In start of the
App te Flash memory.
licat rr When this bit
ion u is set (one),
and pt the interrupt
Boo C vectors are
t o moved to the
Spa nt beginning of
ce ro
the Boot
l
Loader section
Gen R
of the Flash.
eral e
The actual
Inte gi
address of the
rru st
start of the
pt er
Boot Flash
Con c
trol o section is
Reg nt deter-mined
iste ro by the
r – ls BOOTSZ
GIC th Fuses. Refer
R e to the section
pl “Boot Loader
a Support –
c Read-While-
e Write Self-
m Programming”
e on page 246
nt
for details. To
of
avoid
th
e unintentional
In changes of
te Interrupt
rr Vector tables,
u a special write
pt procedure
V must be
e followed to
ct change the
or IVSEL bit:
ta
bl
1. Write the
e. Interrupt
Vector
Change
Enable (IVCE)
bit to one.
2. Within
Bit
four
cycles, write
the
Read/Write
desired
value
Initial Value
to IVSEL
while writing a
zero n utomatic
to ot disabling.
IVC w Note: If Interrupt
E. rit Vector
Inte te s are
rrup n, placed
in the
ts in
Boot
will te Loader
auto rr section
mati u and
call pt Boot
y bes Lock
disa re bit
bled m BLB02
whil ai is
e n progra
this di mmed,
interru
seq s
pts are
uen a disable
ce bl d while
is e executi
exe d ng
cute fo from
d. r the
Inte fo Applica
rrup ur tion
ts c section
are y . If
Interru
disa cl pt
bled e Vector
in s. s are
the T placed
cycl h in the
e e Applica
IVC I- tion
E isbi section
set, t and
and in Boot
they th Lock
bit
rem e BLB12
ain S is
disa ta progra
bled tu med,
until s interru
afte R pts are
r e disable
the gi d while
instr st executi
ucti er ng
on is from
the
follo u Boot
win n Loader
g af section
the fe . Refer
writ ct to the
e toe section
IVS d “Boot
EL. b Loader
If y Suppor
IVS th t –
EL e
Read-
While-
is a
Writ c ardware four
e o cycles after it
Self- n is written or
Prog e when IVSEL is
ram to written.
ming
e Setting the
” on
pag
n IVCE bit will
e a disable
246 bl interrupts, as
for e explained in
detai c the IVSEL
ls onh description
Boot a above. See
Lock n Code Example
bits. g below
• e
Bit of
0 – th
IVC e
E: I
Inte V
rru S
pt E
Vec L
tor bi
Cha t.
nge I
Ena V
ble C
The E
IVC is
E cl
bit e
mus ar
t bee
writt d
en b
to y
48
logi h
2466
T–
AVR–
07/10
ATmega16(L)
.

Assembly Code Example


Move_interrupts:

1; Enable change of interrupt vectors


ldi r16, (1<<IVCE)
out GICR, r16

2; Move interrupts to boot Flash section


ldi r16, (1<<IVSEL)
out GICR, r16
ret

C Code Example
void Move_interrupts(void)
{
/* Enable change of interrupt vectors */
GICR = (1<<IVCE);
/* Move interrupts to boot Flash section
*/ GICR = (1<<IVSEL);
}
49
2466T–AVR–07/10
ATmega16(L)
uctions. The
same
applies
I/O when
Po chang-ing
rts A drive value
l (if
configured
Intr as output)
od or
uct enabling/dis
abling of
ion pull-up
resistors (if
configured
as input).
Each output
buffer has
symmetrical
drive
characteristi
cs with both
high sink
and source
capability.
The pin
driver is
strong
enough to
drive LED
displays
directly. All
port pins
have indi-
vidually
selectable
pull-up
resistors
with a
supply-
voltage
invariant
resistance.
All I/O pins
have
protection
diodes to
both VCC
and Ground
as indicated
in Figure
22. Refer to
“Electrical
Charac-
teristics” on
page 291
for a
complete
list of
parameters.

Figure 22.
I/O Pin
Equ i Schematic
v
Pxn

C
pin

nt hen “ Data
s usin R Regi
th g T ster
A e the h and
l n regis the
u ter Data
m or Dire
b bit ction
er defin Regi
in es in ster
g a are
let prog read
te ram, /writ
r the e. In
fo preci addit
r se ion,
th form the
e must Pull-
p be up
or used Disa
t, , ble –
a that PUD
P n is, bit in
d POR SFI
o a TB3 OR
rt lo for disa
s w bit bles
a er no. the
ca 3 in pull-
s se Port up
G “n B, funct
e ” here ion
n re docu for
pr men all
e
es ted pins
r e gen in all
a nt erall ports
l s y as whe
th POR n
D
e Txn. set.
i bit The
g Usin
n phys
g the
it u ical
I/O
a m I/O
port
b Regi
l as
er s-
I/ Gen
. ters
eral
O H and
Digit
o bit
al
w locat
I/O
ev ions
is
er are
desc
, liste
ribed
w d in
in
“ s at gital
P e I/O.
oN n
rt o a The
s bli port
a n s
s g are
G th bi-
e e direc
n alt tiona
e er l I/O
r n port
al at s
D e with
ig fu optio
it nc nal
al tio inter
I/ n nal
O of pull-
” so ups.
o m Figu
n e re
p of 23
a th sho
g e ws a
e p funct
5 or ional
0. t desc
M pi riptio
o ns n of
st d one
p o I/O-
o es port
rt n pin,
ot here
pi
af gen
n
fe erica
s
ct lly
a
th calle
r
e d
e
us Pxn.
m
e
ul
of
ti
th
pl
e
e
ot
x
h
e er
d pi
w ns
it in
h th
al e
te p
r or
n t
at as
e g
fu e
n n
ct er
io al
n di
5
0
24
66
T–
AV
R–
07
/1
0
ATmega16(L)

Figure 23.
DATABUS
ORTxn, red as an
Note: 1. WPx, and output pin,
W PINxn. the port pin
Dx,
is driven
RR As
x, shown low (zero).
RP in
x, “Regist When
an switching
d
er between
RD Descrip tri-state
x tion for
({DDxn,
are I/O
co PORTxn} =
Ports” 0b00) and
m
mo on output high
n page ({DDxn,
to 66, the
all DDxn PORTxn} =
pin 0b11), an
s bits are intermediat
wit access e state with
hin ed at
the the either pull-
sa up enabled
me DDRx ({DDxn,
por I/O PORTxn} =
t. addres
0b01) or
clkI s, the output low
/O, PORTx ({DDxn,
SL n bits at PORTxn} =
EE the
P, 0b10) must
an PORTx occur.
d I/O Normally,
PU addres the pull-up
D s, and
are enabled
co the state is
m PINxn fully
mo bits at accept-
n the
to
able, as a
all
PINx high-
por I/O impedant
ts. addres environme
s. nt will not
Configuring the Pin Each notice the
The
po difference
DDxn
rt between a
bit in
pin strong high
the
co driver and
DDRx
nsi a pull-up. If
Registe
sts this is not
r
of selects the case,
thr the the PUD bit
ee directio in the
re n of this SFIOR
gis pin. If Register
ter DDxn can be set
bit is to disable
s: written all pull-ups
D logic in all ports.
Dx one,
n, Pxn is
P
51
246
6T–
AVR

07/1
0
ATmega16(L)

Switching between input with pull-up and output low generates the same problem. The user
must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn,
PORTxn} = 0b11) as an intermediate step.
Table 20 summarizes the control signals for the pin value.

Table 20. Port Pin Configurations


PUD
DDxn PORTxn (in SFIOR) I/O Pull-up Comment
0 0 X Input No Tri-state (Hi-Z)
Pxn will source current if ext. pulled
0 1 0 Input Yes low.
0 1 1 Input No Tri-state (Hi-Z)
1 0 X Output No Output Low (Sink)
1 1 X Output No Output High (Source)

Reading the Pin Value Independent of the setting of Data Direction bit DDxn, the port pin can be read through the PINxn
Register bit. As shown in Figure 23, the PINxn Register bit and the preceding latch consti-tute
a synchronizer. This is needed to avoid metastability if the physical pin changes value near the
edge of the internal clock, but it also introduces a delay. Figure 24 shows a timing diagram of
the synchronization when reading an externally applied pin value. The maximum and minimum
propagation delays are denoted tpd,max and tpd,min respectively.

Figure 24. Synchronization when Reading an Externally Applied Pin Value

SYSTEM CLK

INSTRUCTIONS XXX XXX in r17, PINx

SYNC LATCH

PINxn

r17 0x00 0xFF

t
pd, max

t
pd, min

Consider the clock period starting shortly after the first falling edge of the system clock. The latch is
closed when the clock is low, and goes transparent when the clock is high, as indicated by the
shaded region of the “SYNC LATCH” signal. The signal value is latched when the system clock goes
low. It is clocked into the PINxn Register at the succeeding positive clock edge. As
indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be
delayed between ½ and 1½ system clock period depending upon the time of assertion.
52
2466T–AVR–07/10
ATmega16(L)

When reading back a software assigned pin value, a nop instruction must be inserted as indi-
cated in Figure 25. The out instruction sets the “SYNC LATCH” signal at the positive edge of
the clock. In this case, the delay tpd through the synchronizer is one system clock period.

Figure 25. Synchronization when Reading a Software Assigned Pin Value

SYSTEM CLK

r16 0xFF

INSTRUCTIONS out PORTx, r16 nop in r17, PINx

SYNC LATCH

PINxn

r17 0x00 0xFF

t
pd
53
2466T–AVR–07/10
ATmega16(L)

The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define
the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. The resulting pin
values are read back again, but as previously discussed, a nop instruction is included to be
able to read back the value recently assigned to some of the pins.

(1)
Assembly Code Example
...

1; Define pull-ups and set outputs high

2; Define directions for port pins


ldi r16,(1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0)
ldi r17,(1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0)
out PORTB,r16
out DDRB,r17

1; Insert nop for synchronization nop

2; Read port pins

in r16,PINB
...
(1)
C Code Example
unsigned char i;
...
/* Define pull-ups and set outputs high
*/ /* Define directions for port pins */
PORTB = (1<<PB7)|(1<<PB6)|(1<<PB1)|(1<<PB0); DDRB
= (1<<DDB3)|(1<<DDB2)|(1<<DDB1)|(1<<DDB0); /*
Insert nop for synchronization*/
_NOP();
/* Read port pins */
i = PINB;
...

Note: 1. For the assembly program, two temporary registers are used to minimize the time from pull-
ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3
as low and redefining bits 0 and 1 as strong high drivers.

Digital Input Enable As shown in Figure 23, the digital input signal can be clamped to ground at the input of the
and Sleep Modes schmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in
Power-down mode, Power-save mode, Standby mode, and Extended Standby mode to avoid
high power consumption if some input signals are left floating, or have an analog signal level
close to VCC/2.
SLEEP is overridden for port pins enabled as External Interrupt pins. If the External Interrupt
Request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by vari-
ous other alternate functions as described in “Alternate Port Functions” on page 55.
If a logic high level (“one”) is present on an Asynchronous External Interrupt pin configured as
“Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while the External Inter-
rupt is not enabled, the corresponding External Interrupt Flag will be set when resuming from the
above mentioned sleep modes, as the clamping in these sleep modes produces the requested
logic change.

54
2466T–AVR–07/10
ATmega16(L)
these pins
have a
Unc I defined level.
onn f Even though
ect most of the
ed s digital inputs
pin o are disabled
s m in the deep
e sleep modes
as described
p above, float-
i ing inputs
n should be
s avoided to
reduce
a current
r consumption
e in all other
Alt modes where
ern u the digital
ate n inputs are
Po u enabled
(Reset,
rt s
Active mode
Fu e and Idle
d
nct , mode).
ion
The simplest
s i method to
t ensure a
defined level
i of an unused
s pin, is to
enable the
r internal pull-
e up. In this
case, the
c
pull-up will be
o disabled
m during reset.
m If low power
e consumption
n during reset
d is important,
e it is
d recommende
d to use an
t external pull-
up or pull-
o
down.
Connecting
e unused pins
n directly to
s
VCC or GND
u
is not
r recommende
e d, since this
may cause
t excessive
h currents if the
a pin is
t accidentally
configured as
an output.
a as a generic
Mos l description
t s applicable to
port all port pins
pins m in the AVR
hav a microcontroll
e y er family.
alter
Figure 26.
nate n Alternate Port
func o (1)
tion t Functions
s in
addi b
tion e
to
bein p
g r
Gen e
eral s
Digi e
tal n
I/Os t
.
Figu i
re n
26 Pxn

sho a
ws l
how l
the p
port o
pin r
cont t
rol
sign p
als i
fro n
m s
the ,
sim
plifi b PUOExn: Pxn PUL

ed u
PUOVxn: Pxn PUL
DDOExn: Pxn DAT

Figu t DDOVxn:
PVOExn:
Pxn DATA
Pxn POR
PVOVxn: Pxn POR
re DIEOExn: Pxn DIGI
23 t DIEOVxn: Pxn DIGI

can h
SLEEP: SLEEP C

be e Note: 1. WPx,
over W
ridd f Dx
,
en i R
by g Rx
alter u ,
- r R
Px
nate e ,
func an
tion s d
s. e R
Dx
The r ar
over v e
ridin e co
g s m
m
sign
on tot he
all o r
pins si
withi a gn
n thel al
sam l s
e p ar
port. o e
clkI/ r un
t iq
O, s ue
SLE . for
EP, A ea
and l ch
PUD l pi
are o n.
com t
mon
5
5
2466
T–
AVR–
07/10
ATmega16(L)

Table 21 summarizes the function of the overriding signals. The pin and port indexes from Fig-
ure 26 are not shown in the succeeding tables. The overriding signals are generated internally
in the modules having the alternate function.

Table 21. Generic Description of Overriding Signals for Alternate Functions


Signal Name Full Name Description
PUOE Pull-up Override If this signal is set, the pull-up enable is controlled by
Enable the PUOV signal. If this signal is cleared, the pull-up is
enabled when {DDxn, PORTxn, PUD} = 0b010.
PUOV Pull-up Override If PUOE is set, the pull-up is enabled/disabled when
Value PUOV is set/cleared, regardless of the setting of the
DDxn, PORTxn, and PUD Register bits.
DDOE Data Direction If this signal is set, the Output Driver Enable is
Override Enable controlled by the DDOV signal. If this signal is cleared,
the Output driver is enabled by the DDxn Register bit.
DDOV Data Direction If DDOE is set, the Output Driver is enabled/disabled
Override Value when DDOV is set/cleared, regardless of the setting of
the DDxn Register bit.
PVOE Port Value Override If this signal is set and the Output Driver is enabled,
Enable the port value is controlled by the PVOV signal. If
PVOE is cleared, and the Output Driver is enabled, the
port Value is controlled by the PORTxn Register bit.
PVOV Port Value Override If PVOE is set, the port value is set to PVOV,
Value regardless of the setting of the PORTxn Register bit.
DIEOE Digital Input Enable If this bit is set, the Digital Input Enable is controlled by
Override Enable the DIEOV signal. If this signal is cleared, the Digital
Input Enable is determined by MCU-state (Normal
Mode, sleep modes).
DIEOV Digital Input Enable If DIEOE is set, the Digital Input is enabled/disabled
Override Value when DIEOV is set/cleared, regardless of the MCU
state (Normal Mode, sleep modes).
DI Digital Input This is the Digital Input to alternate functions. In the
figure, the signal is connected to the output of the
schmitt trigger but before the synchronizer. Unless the
Digital Input is used as a clock source, the module with
the alternate function will use its own synchronizer.
AIO Analog Input/ output This is the Analog Input/output to/from alternate
functions. The signal is connected directly to the pad,
and can be used bi-directionally.

The following subsections shortly describe the alternate functions for each port, and relate the
overriding signals to the alternate function. Refer to the alternate function description for further
details.

56
2466T–AVR–07/10
ATmega16(L)

Spe
cial
Fun
ctio
n I/O
Reg
ister

SFI
OR
Bit 7 6 5
ADTS2 ADTS1 ADTS0
Read/Write R/W R/W R/W
Initial Value 0 0 0
T some
• BitPort
a 2 – PUD: Pull-up
Port A
disable
When this bit is written
to one, the pull-ups in
the I/O ports are
disabled even if the
DDxn and PORTxn
Registers are
configured to enable the
pull-ups ({DDxn,
PORTxn} = 0b01). See
“Con-
on page 51
details about this
feature.

Al
te
rn
at
e
F
u
nc
ti
o
ns
of
P
ort
A
ha
s
an
alt
er
na
te
fu
nc
tio
n
as
an
al
og
in 57
pu
t
for
th
e
A
D
C
as
sh
o
w
n
in
24
66
T–
AV
R–
07/
10
ATmega16(L)

Table 24. Overriding Signals for Alternate Functions in PA3..PA0


Signal Name PA3/ADC3 PA2/ADC2 PA1/ADC1 PA0/ADC0
PUOE 0 0 0 0
PUOV 0 0 0 0
DDOE 0 0 0 0
DDOV 0 0 0 0
PVOE 0 0 0 0
PVOV 0 0 0 0
DIEOE 0 0 0 0
DIEOV 0 0 0 0
DI – – – –
AIO ADC3 INPUT ADC2 INPUT ADC1 INPUT ADC0 INPUT

Alternate Functions of The Port B pins with alternate functions are shown in Table 25.
Port B
Table 25. Port B Pins Alternate Functions
Port Pin Alternate Functions
PB7 SCK (SPI Bus Serial Clock)
PB6 MISO (SPI Bus Master Input/Slave Output)
PB5 MOSI (SPI Bus Master Output/Slave Input)
PB4 SS (SPI Slave Select Input)
AIN1 (Analog Comparator Negative Input)
PB3
OC0 (Timer/Counter0 Output Compare Match Output)
AIN0 (Analog Comparator Positive Input)
PB2
INT2 (External Interrupt 2 Input)
PB1 T1 (Timer/Counter1 External Counter Input)
T0 (Timer/Counter0 External Counter Input)
PB0
XCK (USART External Clock Input/Output)

The alternate pin configuration is as follows:

• SCK – Port B, Bit 7


SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI is enabled as a
Slave, this pin is configured as an input regardless of the setting of DDB7. When the SPI is
enabled as a Master, the data direction of this pin is controlled by DDB7. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB7 bit.

• MISO – Port B, Bit 6


MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a
Master, this pin is configured as an input regardless of the setting of DDB6. When the SPI is
enabled as a Slave, the data direction of this pin is controlled by DDB6. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB6 bit.

58
2466T–AVR–07/10
ATmega16(L)

• MOSI – Port B, Bit 5


MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI is enabled as a
Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is
enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced
by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit.

• SS – Port B, Bit 4
SS: Slave Select input. When the SPI is enabled as a Slave, this pin is configured as an input
regardless of the setting of DDB4. As a Slave, the SPI is activated when this pin is driven low. When
the SPI is enabled as a Master, the data direction of this pin is controlled by DDB4. When the pin is
forced by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit.

• AIN1/OC0 – Port B, Bit 3


AIN1, Analog Comparator Negative Input. Configure the port pin as input with the internal pull-
up switched off to avoid the digital port function from interfering with the function of the analog
comparator.
OC0, Output Compare Match output: The PB3 pin can serve as an external output for the
Timer/Counter0 Compare Match. The PB3 pin has to be configured as an output (DDB3 set
(one)) to serve this function. The OC0 pin is also the output pin for the PWM mode timer
function.

• AIN0/INT2 – Port B, Bit 2


AIN0, Analog Comparator Positive input. Configure the port pin as input with the internal pull-up
switched off to avoid the digital port function from interfering with the function of the Analog
Comparator.
INT2, External Interrupt Source 2: The PB2 pin can serve as an external interrupt source to the
MCU.

• T1 – Port B, Bit 1
T1, Timer/Counter1 Counter Source.

• T0/XCK – Port B, Bit 0


T0, Timer/Counter0 Counter Source.
XCK, USART External Clock. The Data Direction Register (DDB0) controls whether the clock is
output (DDB0 set) or input (DDB0 cleared). The XCK pin is active only when the USART oper-
ates in Synchronous mode.
Table 26 and Table 27 relate the alternate functions of Port B to the overriding signals shown
in Figure 26 on page 55. SPI MSTR INPUT and SPI SLAVE OUTPUT constitute the MISO
signal, while MOSI is divided into SPI MSTR OUTPUT and SPI SLAVE INPUT.

59
2466T–AVR–
07/10
ATmega16(L)

Table 26. Overriding Signals for Alternate Functions in PB7..PB4


Signal
Name PB7/SCK PB6/MISO PB5/MOSI PB4/SS
PUOE SPE • MSTR SPE • MSTR SPE • MSTR SPE • MSTR
PUOV PORTB7 • PUD PORTB6 • PUD PORTB5 • PUD PORTB4 • PUD
DDOE SPE • MSTR SPE • MSTR SPE • MSTR SPE • MSTR
DDOV 0 0 0 0
PVOE SPE • MSTR SPE • MSTR SPE • MSTR 0
PVOV SCK OUTPUT SPI SLAVE OUTPUT SPI MSTR OUTPUT 0
DIEOE 0 0 0 0
DIEOV 0 0 0 0
DI SCK INPUT SPI MSTR INPUT SPI SLAVE INPUT SPI SS
AIO – – – –

Table 27. Overriding Signals for Alternate Functions in PB3..PB0


Signal
Name PB3/OC0/AIN1 PB2/INT2/AIN0 PB1/T1 PB0/T0/XCK
PUOE 0 0 0 0
PUOV 0 0 0 0
DDOE 0 0 0 0
DDOV 0 0 0 0
PVOE OC0 ENABLE 0 0 UMSEL
PVOV OC0 0 0 XCK OUTPUT
DIEOE 0 INT2 ENABLE 0 0
DIEOV 0 1 0 0
DI – INT2 INPUT T1 INPUT XCK INPUT/T0 INPUT
AIO AIN1 INPUT AIN0 INPUT – –

60
2466T–AVR–07/10
ATmega16(L)

Alternate Functions of The Port C pins with alternate functions are shown in Table 28. If the JTAG interface is enabled,
Port C the pull-up resistors on pins PC5(TDI), PC3(TMS) and PC2(TCK) will be activated even if a reset
occurs.

Table 28. Port C Pins Alternate Functions


Port Pin Alternate Function
PC7 TOSC2 (Timer Oscillator Pin 2)
PC6 TOSC1 (Timer Oscillator Pin 1)
PC5 TDI (JTAG Test Data In)
PC4 TDO (JTAG Test Data Out)
PC3 TMS (JTAG Test Mode Select)
PC2 TCK (JTAG Test Clock)
PC1 SDA (Two-wire Serial Bus Data Input/Output Line)
PC0 SCL (Two-wire Serial Bus Clock Line)

The alternate pin configuration is as follows:

• TOSC2 – Port C, Bit 7


TOSC2, Timer Oscillator pin 2: When the AS2 bit in ASSR is set (one) to enable asynchronous
clocking of Timer/Counter2, pin PC7 is disconnected from the port, and becomes the inverting
output of the Oscillator amplifier. In this mode, a Crystal Oscillator is connected to this pin, and
the pin can not be used as an I/O pin.

• TOSC1 – Port C, Bit 6


TOSC1, Timer Oscillator pin 1: When the AS2 bit in ASSR is set (one) to enable asynchronous
clocking of Timer/Counter2, pin PC6 is disconnected from the port, and becomes the input of the
inverting Oscillator amplifier. In this mode, a Crystal Oscillator is connected to this pin, and the
pin can not be used as an I/O pin.

• TDI – Port C, Bit 5


TDI, JTAG Test Data In: Serial input data to be shifted in to the Instruction Register or Data Reg-
ister (scan chains). When the JTAG interface is enabled, this pin can not be used as an I/O pin.

• TDO – Port C, Bit 4


TDO, JTAG Test Data Out: Serial output data from Instruction Register or Data Register. When
the JTAG interface is enabled, this pin can not be used as an I/O pin.
The TD0 pin is tri-stated unless TAP states that shifts out data are entered.

• TMS – Port C, Bit 3


TMS, JTAG Test Mode Select: This pin is used for navigating through the TAP-controller state
machine. When the JTAG interface is enabled, this pin can not be used as an I/O pin.

• TCK – Port C, Bit 2


TCK, JTAG Test Clock: JTAG operation is synchronous to TCK. When the JTAG interface is
enabled, this pin can not be used as an I/O pin.

61

2466T–AVR–
07/10
ATmega16(L)

• SDA – Port C, Bit 1


SDA, Two-wire Serial Interface Data: When the TWEN bit in TWCR is set (one) to enable the
Two-wire Serial Interface, pin PC1 is disconnected from the port and becomes the Serial Data
I/O pin for the Two-wire Serial Interface. In this mode, there is a spike filter on the pin to sup-
press spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver
with slew-rate limitation. When this pin is used by the Two-wire Serial Interface, the pull-up can
still be controlled by the PORTC1 bit.

• SCL – Port C, Bit 0


SCL, Two-wire Serial Interface Clock: When the TWEN bit in TWCR is set (one) to enable the
Two-wire Serial Interface, pin PC0 is disconnected from the port and becomes the Serial Clock
I/O pin for the Two-wire Serial Interface. In this mode, there is a spike filter on the pin to sup-
press spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver
with slew-rate limitation. When this pin is used by the Two-wire Serial Interface, the pull-up can
still be controlled by the PORTC0 bit.
Table 29 and Table 30 relate the alternate functions of Port C to the overriding signals shown
in Figure 26 on page 55.

Table 29. Overriding Signals for Alternate Functions in PC7..PC4


Signal
Name PC7/TOSC2 PC6/TOSC1 PC5/TDI PC4/TDO
PUOE AS2 AS2 JTAGEN JTAGEN
PUOV 0 0 1 0
DDOE AS2 AS2 JTAGEN JTAGEN
DDOV 0 0 0 SHIFT_IR + SHIFT_DR
PVOE 0 0 0 JTAGEN
PVOV 0 0 0 TDO
DIEOE AS2 AS2 JTAGEN JTAGEN
DIEOV 0 0 0 0
DI – – – –
AIO T/C2 OSC OUTPUT T/C2 OSC INPUT TDI –

62
2466T–AVR–07/10
ATmega16(L)

(1)
Table 30. Overriding Signals for Alternate Functions in PC3..PC0
Signal
Name PC3/TMS PC2/TCK PC1/SDA PC0/SCL
PUOE JTAGEN JTAGEN TWEN TWEN
PUOV 1 1 PORTC1 • PUD PORTC0 • PUD
DDOE JTAGEN JTAGEN TWEN TWEN
DDOV 0 0 SDA_OUT SCL_OUT
PVOE 0 0 TWEN TWEN
PVOV 0 0 0 0
DIEOE JTAGEN JTAGEN 0 0
DIEOV 0 0 0 0
DI – – – –
AIO TMS TCK SDA INPUT SCL INPUT
Note: 1. When enabled, the Two-wire Serial Interface enables slew-rate controls on the output pins
PC0 and PC1. This is not shown in the figure. In addition, spike filters are connected between
the AIO outputs shown in the port figure and the digital logic of the TWI module.

Alternate Functions of The Port D pins with alternate functions are shown in Table 31.
Port D
Table 31. Port D Pins Alternate Functions
Port Pin Alternate Function
PD7 OC2 (Timer/Counter2 Output Compare Match Output)
PD6 ICP1 (Timer/Counter1 Input Capture Pin)
PD5 OC1A (Timer/Counter1 Output Compare A Match Output)
PD4 OC1B (Timer/Counter1 Output Compare B Match Output)
PD3 INT1 (External Interrupt 1 Input)
PD2 INT0 (External Interrupt 0 Input)
PD1 TXD (USART Output Pin)
PD0 RXD (USART Input Pin)

The alternate pin configuration is as follows:

• OC2 – Port D, Bit 7


OC2, Timer/Counter2 Output Compare Match output: The PD7 pin can serve as an external
out-put for the Timer/Counter2 Output Compare. The pin has to be configured as an output
(DDD7 set (one)) to serve this function. The OC2 pin is also the output pin for the PWM mode
timer function.

• ICP1 – Port D, Bit 6


ICP1 – Input Capture Pin: The PD6 pin can act as an Input Capture pin for Timer/Counter1.

63
2466T–AVR–07/10
ATmega16(L)

• OC1A – Port D, Bit 5


OC1A, Output Compare Match A output: The PD5 pin can serve as an external output for the
Timer/Counter1 Output Compare A. The pin has to be configured as an output (DDD5 set (one)) to
serve this function. The OC1A pin is also the output pin for the PWM mode timer function.

• OC1B – Port D, Bit 4


OC1B, Output Compare Match B output: The PD4 pin can serve as an external output for the
Timer/Counter1 Output Compare B. The pin has to be configured as an output (DDD4 set (one)) to
serve this function. The OC1B pin is also the output pin for the PWM mode timer function.

• INT1 – Port D, Bit 3


INT1, External Interrupt Source 1: The PD3 pin can serve as an external interrupt source.

• INT0 – Port D, Bit 2


INT0, External Interrupt Source 0: The PD2 pin can serve as an external interrupt source.

• TXD – Port D, Bit 1


TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled,
this pin is configured as an output regardless of the value of DDD1.

• RXD – Port D, Bit 0


RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this
pin is configured as an input regardless of the value of DDD0. When the USART forces this pin
to be an input, the pull-up can still be controlled by the PORTD0 bit.
Table 32 and Table 33 relate the alternate functions of Port D to the overriding signals shown
in Figure 26 on page 55.

Table 32. Overriding Signals for Alternate Functions PD7..PD4


Signal Name PD7/OC2 PD6/ICP1 PD5/OC1A PD4/OC1B
PUOE 0 0 0 0
PUOV 0 0 0 0
DDOE 0 0 0 0
DDOV 0 0 0 0
PVOE OC2 ENABLE 0 OC1A ENABLE OC1B ENABLE
PVOV OC2 0 OC1A OC1B
DIEOE 0 0 0 0
DIEOV 0 0 0 0
DI – ICP1 INPUT – –
AIO – – – –

64
2466T–AVR–07/10
ATmega16(L)

Table 33. Overriding Signals for Alternate Functions in PD3..PD0


Signal Name PD3/INT1 PD2/INT0 PD1/TXD PD0/RXD
PUOE 0 0 TXEN RXEN
PUOV 0 0 0 PORTD0 • PUD
DDOE 0 0 TXEN RXEN
DDOV 0 0 1 0
PVOE 0 0 TXEN 0
PVOV 0 0 TXD 0
DIEOE INT1 ENABLE INT0 ENABLE 0 0
DIEOV 1 1 0 0
DI INT1 INPUT INT0 INPUT – RXD
AIO – – – –

65
2466T–AVR–07/10
ATmega16(L)
Re
gi
st
Re er
gis –
ter P
De O
scr R
T
ipti B
on
for
I/O
Por
ts P
or
Port t
A B
Data D
Regi at
ster a
– Di
PO re
RTA cti
on
R
eg
ist
er
Port –
A D
Dat D
a R
Dire B
ctio
n
Reg
ister

DD P
RA or
t
B
In
pu
t
Port Pi
A ns
InpuA
t dd
Pinsre
Add ss
ress –
– PI
PIN N
A B

Port
B
Data
Bit 7 6 5
PORTA7 PORTA6 PORTA5
Read/Write R/W R/W R/W
Initial Value 0 0 0

Bit 7 6 5
DDA7 DDA6 DDA5
Read/Write R/W R/W R/W
Initial Value 0 0 0

Bit 7 6 5
PINA7 PINA6 PINA5
Read/Write R R R
Initial Value N/A N/A N/A

Bit 7 6 5
PORTB7 PORTB6 PORTB5
Read/Write R/W R/W R/W
Initial Value 0 0 0

Bit 7 6 5
DDB7 DDB6 DDB5
Read/Write R/W R/W R/W
Initial Value 0 0 0

Bit 7 6 5
PINB7 PINB6 PINB5
Read/Write R R R
Initial Value N/A N/A N/A

6
6
2466T

AVR–
07/10
ATmega16(L)
cti
on
Port R
C eg
Data ist
Regi er
ster –
– D
PO D
RTC R
D

Port
C P
Dat or
a t
Dire D
ctio In
n pu
Reg t
isterPi
– ns
DD A
RC dd
re
ss

PI
N
Port
D
C
Inpu
t
Pins
Add
ress

PIN
C

Port
D
Data
Regi
ster

PO
RTD

Port
D
Dat
a
Dire
Bit 7 6 5
PORTC7 PORTC6 PORTC5
Read/Write R/W R/W R/W
Initial Value 0 0 0

Bit 7 6 5
DDC7 DDC6 DDC5
Read/Write R/W R/W R/W
Initial Value 0 0 0

Bit 7 6 5
PINC7 PINC6 PINC5
Read/Write R R R
Initial Value N/A N/A N/A

Bit 7 6 5
PORTD7 PORTD6 PORTD5
Read/Write R/W R/W R/W
Initial Value 0 0 0

Bit 7 6 5
DDD7 DDD6 DDD5
Read/Write R/W R/W R/W
Initial Value 0 0 0

Bit 7 6 5
PIND7 PIND6 PIND5
Read/Write R R R
Initial Value N/A N/A N/A

6
7

2466T

AVR–
07/10
ATmega16(L)

External The External Interrupts are triggered by the INT0, INT1, and INT2 pins. Observe that, if enabled,
the interrupts will trigger even if the INT0..2 pins are configured as outputs. This feature provides
Interrupts a way of generating a software interrupt. The external interrupts can be triggered by a falling or
rising edge or a low level (INT2 is only an edge triggered interrupt). This is set up as indicated in
the specification for the MCU Control Register – MCUCR – and MCU Control and Status Regis-
ter – MCUCSR. When the external interrupt is enabled and is configured as level triggered (only
INT0/INT1), the interrupt will trigger as long as the pin is held low. Note that recognition of falling
or rising edge interrupts on INT0 and INT1 requires the presence of an I/O clock, described in
“Clock Systems and their Distribution” on page 24. Low level interrupts on INT0/INT1 and the
edge interrupt on INT2 are detected asynchronously. This implies that these interrupts can be
used for waking the part also from sleep modes other than Idle mode. The I/O clock is halted in
all sleep modes except Idle mode.
Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed
level must be held for some time to wake up the MCU. This makes the MCU less sensitive to
noise. The changed level is sampled twice by the Watchdog Oscillator clock. The period of the
Watchdog Oscillator is 1 µs (nominal) at 5.0V and 25°C. The frequency of the Watchdog Oscilla-
tor is voltage dependent as shown in “Electrical Characteristics” on page 291. The MCU will
wake up if the input has the required level during this sampling or if it is held until the end of the
start-up time. The start-up time is defined by the SUT Fuses as described in “System Clock and
Clock Options” on page 24. If the level is sampled twice by the Watchdog Oscillator clock but
disappears before the end of the start-up time, the MCU will still wake up, but no interrupt will be
generated. The required level must be held long enough for the MCU to complete the wake up to
trigger the level interrupt.

MCU Control Register The MCU Control Register contains control bits for interrupt sense control and general MCU
– MCUCR functions.
Bit 7 6 5 4 3 2 1 0
SM2 SE SM1 SM0 ISC11 ISC10 ISC01 ISC00 MCUCR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0

• Bit 3, 2 – ISC11, ISC10: Interrupt Sense Control 1 Bit 1 and Bit 0


The External Interrupt 1 is activated by the external pin INT1 if the SREG I-bit and the corre-
sponding interrupt mask in the GICR are set. The level and edges on the external INT1 pin that
activate the interrupt are defined in Table 34. The value on the INT1 pin is sampled before
detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one clock
period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If
low level interrupt is selected, the low level must be held until the completion of the currently
executing instruction to generate an interrupt.

Table 34. Interrupt 1 Sense Control


ISC11 ISC10 Description
0 0 The low level of INT1 generates an interrupt request.
0 1 Any logical change on INT1 generates an interrupt request.
1 0 The falling edge of INT1 generates an interrupt request.
1 1 The rising edge of INT1 generates an interrupt request.

68
2466T–AVR–07/10
ATmega16(L)
t
r
o
• Bit 1, 0 –
l
ISC01,
R
ISC00:
e Interrupt
g Sense
i Control 0 Bit
s 1 and Bit 0
t
The External
e
r
Interrupt 0 is
activated by
– the external
G pin INT0 if
I the SREG I-
C flag and the
R corre-
sponding
interrupt
mask are set.
The level and
MC edges on the
U external INT0
Con pin that
trol
activate the
and
interrupt are
Stat
defined in
us
Table 35. The
Reg
value on the
iste
r– INT0 pin is
MC sampled
UC before
SR detecting
edges. If
edge or
toggle
interrupt is
selected,
pulses that
last longer
than one
clock period
will generate
an interrupt.
Shorter
pulses are
not
guaranteed
to generate
an interrupt.
If low level
interrupt is
selected, the
low level
Gen must be held
eral until the
Inte completion of
rru the currently
pt executing
Con instruction to
gen i falling edge
erat n on INT2
e ant activates the
inter e interrupt. If
rupt r ISC2 is
. r written to one,
u a rising edge
Tabl p on INT2
e t activates the
35. inter-rupt.
Inte m Edges on
rrup a INT2 are
t0 s registered
Sen k asynchronous
se ly. Pulses on
Con i INT2 wider
trol n than the
ISC01 minimum
G pulse width
0
I given in Table
0C 36 will
1R generate an
interrupt.
1
a Shorter
r pulses are not
e guaranteed to
Bit generate an
s interrupt.
Read/Write
e When
Initialt Value changing the
. ISC2 bit, an
• Bit 6 – ISC2: Interrupt
interrupt can Sense C
I occur.
f Therefore, it is
The
rec-
Asy
I ommended to
nchr
S first disable
ono
C INT2 by
us
2 clearing its
Exte
Interrupt
rnal
i Enable bit in
Inter
s the GICR
rupt
Register.
2 is
w Then, the
activ
r ISC2 bit can
ated
i be changed.
by
t Finally, the
the
t INT2 Interrupt
exte
e Flag should
rnal
n be cleared by
pin
writing a logi-
INT
t cal one to its
2 if
o Interrupt Flag
the
bit (INTF2) in
SRE
z the GIFR
G I-
e Register
bit
r before the
and
o interrupt is re-
the
, enabled.
corr
esp Table 36. Asynchrono
a
ondi
ng Symbol Parameter
tt ) is set (one),
h
INT the exter-nal
e pin interrupt is
enabled. The
Bit
S Interrupt
t Sense
a
Read/Write Control1 bits
Initialt Value 1/0 (ISC11
u and ISC10) in
• Bits 7 – INT1: the External
MCUInterrup
General
R Control
Whe e Register
n g (MCUCR)
the i define
INT s whether the
1 bitt External
is e Interrupt is
set r activated on
(one rising
) (
and S
the R
I-bit E
in G 69
2466
T–
AVR–
07/10
ATmega16(L)
tput. The
corresponding
an interrupt of
d/ External
or Interrupt
fal Request 1 is
lin executed from
g the INT1
ed interrupt
ge Vector.
of
th • Bit 6 –
e INT0: External
IN Interrupt
T1 Request 0
pi Enable
n When the INT0
or bit is set (one)
le and the I-bit in
ve the Status
l Register
se (SREG) is set
ns (one), the
Gen ed exter-nal pin
eral . interrupt is
Inte Ac enabled. The
rrup tivi Interrupt Sense
t ty Control0 bits
Flag on
1/0 (ISC01 and
Reg th ISC00) in the
iste e
MCU General
r – pi
Control
GIF n
Register
R wil
(MCUCR)
l
define whether
ca
the External
us
Interrupt is
e
activated on
an
rising and/or
int
falling edge of
err
the INT0 pin or
up
level sensed.
t
Activity on the
re
pin will cause
qu
an interrupt
es
t request even if
ev INT0 is
en configured as
if an output. The
IN corresponding
T1 interrupt of
is External
co Interrupt
nfi Request 0 is
gu executed from
re the INT0
d interrupt
as vector.
an
ou • Bit 5 –
INT U on the pin will
2: C cause an
Ext on interrupt
ern tro request even if
al l INT2 is
Inte an configured as
rru d an output. The
pt St corresponding
Req at interrupt of
ues us External
t2 R Interrupt
Ena eg Request 2 is
ble
ist executed from
Wh er the INT2
en (M Interrupt
the C Vector.
INT U
2 bitC
is S Bit 7
set R) INTF1 IN
(on de Read/Write R/W R
e) fin Initial Value 0
and es
the w • Bit 7 – INTF1: Extern
I-bit he
in th
the er When an edge
Stat th or logic change
us e on the INT1 pin
Reg Ex triggers an
ister ter interrupt
(SR na request, INTF1
EG) l becomes set
is Int (one). If the I-
set err bit in SREG
(on up and the INT1
e), t bit in GICR are
the is set (one), the
exte ac MCU will jump
r- tiv to the corre-
nal at sponding
pin ed Interrupt
inter on Vector. The
rupt ris flag is cleared
is in when the
ena g interrupt
bled or routine is
. fal executed.
The lin Alternatively,
Inte g the flag can be
rrup ed cleared by
t ge writing a logical
Sen of one to it. This
se th flag is always
Con e cleared when
trol2 IN INT1 is
bit T2 configured as a
(IS pi level interrupt.
C2) n.
in Ac • Bit 6 –
the tivi INTF0:
MC ty External
Inte co iting a logical
rru rre one to it. This
pt - flag is always
Fla sp cleared when
g 0 on INT0 is
Wh di configured as a
en ng level interrupt.
an int
edg err • Bit 5 –
INTF2:
e orup
External
logi t
Interrupt Flag
c ve
2
cha ct
nge or. When an event
on Th on the INT2 pin
the e triggers an
INT fla interrupt
0 g request, INTF2
pin is becomes set
trigg cl (one). If the I-
ers ea bit in SREG
an re and the INT2
inter d bit in GICR are
rupt w set (one), the
req he MCU will jump
uest n to the
, th corresponding
INT e Interrupt
F0 int Vector. The
bec err flag is cleared
ome up when the
s t interrupt
set ro routine is
(on uti executed.
e). ne Alternatively,
If is the flag can be
the ex cleared by
I-bit ec writing a logical
in ut one to it. Note
SR ed that when
EG . entering some
and Alt sleep modes
the er with the INT2
INT na interrupt
0 bittiv disabled, the
in ely input buffer on
GIC , this pin will be
R th disabled. This
are e may cause a
set fla logic change in
(on g internal signals
e), ca which will set
the n the INTF2
MC be Flag. See
U cl “Digital Input
will ea Enable and
jum re Sleep Modes”
p tod on page 54 for
the by more
wr information.
70
2466
T–
AVR–
07/10
ATmega16(L)
gle Compare
Unit Counter
2• Clear Timer
8- Ti on Compare
bit m
er/
Match
Reload)
(Auto

Ti C 3• Glitch-free,
Phase Correct
meount Pulse Width
Modulator
r/C er (PWM)
ou 0is 4• Frequency
Generator
nt a 5• External
er ge
ne
Event Counter
6• 10-bit Clock
0 ral Prescaler
wit pu
rp
7• Overflow and
Compare Match
h os Interrupt
Sources (TOV0
P e,si
and OCF0)
W ng
A simplified
M leco block diagram
m of the 8-bit
pa Timer/Counter
re is shown in
un Figure 27. For
it, the actual
place-ment of
Ov 8- I/O pins, refer
bit
erv Ti to “Pinout
iew m ATmega16” on
er/ page 2. CPU
C accessible I/O
ou Registers,
nt including I/O
er bits and I/O
m pins, are
od shown in bold.
ul The device-
e. specific I/O
Th Register and
e bit locations
m are listed in the
ai “8-bit
n Timer/Counter
fe Register
at
Description” on
ur
page 83.
es
ar
Figure 27. 8-
e:
bit
1• S
Timer/Counter
in
Block Diagram
DATABUS
Timer/Counter
TCNTn
=0 =

OCRn

Registers
24
66
T–
A
V
R

07
/1
0
ATmega16(L)

Unit” on page 73. for details. The compare match event will also set the Compare Flag (OCF0)
which can be used to generate an output compare interrupt request.

Definitions Many register and bit references in this document are written in general form. A lower case “n”
replaces the Timer/Counter number, in this case 0. However, when using the register or bit
defines in a program, the precise form must be used, that is, TCNT0 for accessing
Timer/Counter0 counter value and so on.
The definitions in Table 37 are also used extensively throughout the document.
Table 37. Definitions
BOTTOM The counter reaches the BOTTOM when it becomes 0x00.
MAX The counter reaches its MAXimum when it becomes 0xFF (decimal 255).
TOP The counter reaches the TOP when it becomes equal to the highest
value in the count sequence. The TOP value can be assigned to be the
fixed value 0xFF (MAX) or the value stored in the OCR0 Register. The
assignment is dependent on the mode of operation.
(TCCR0). For details on clock sources and
Timer/Counter The prescaler, see “Timer/Counter0 and
Clock Sources Timer/ Timer/Counter1 Prescalers” on page 87.
Counte
r can The main part of the 8-bit Timer/Counter is
be the programmable bi-directional counter unit.
Counter Unit clocke Figure 28 shows a block diagram of the
d by an counter and its surroundings.
internal
or an Figure 28. Counter Unit Block Diagram
extern TO
al DATA BUS (Int

clock
source.
The count
clock clear clk
TCNTn Control Logic
source direction
is
selecte
d by BOTTOM TOP
the
clock Signal description (internal signals):
select
logic count Increment or decrement TCNT0 by 1.
which direction Select between increment and decremen
is
controll clear Clear TCNT0 (set all bits to zero).
ed by clkTn Timer/Counter clock, referred to as clkT0
the
clock TOP Signalize that TCNT0 has reached maxi
select BOTTOM Signalize that TCNT0 has reached minim
(CS02:
0) bits
located Depending of the mode of operation used,
in the the counter is cleared, incremented, or
Timer/ decremented at each timer clock (clkT0). clkT0
Counte can be generated from an external or internal
r clock source, selected by the Clock Select
Control bits (CS02:0). When no clock source is
Regist selected (CS02:0 = 0) the timer is stopped.
However, the TCNT0 value can be accessed
er
by the CPU, regardless of
7
2
2466T–AVR–07/10
ATmega16(L)
ear or count
operations.
w The counting
h
sequence is
e
t determined by
h the setting of
e the WGM01
r and WGM00
cl bits located in
k the
T Timer/Counter
0
Control
is Register
Ou p (TCCR0).
tpu r There are
e close
t s
connections
Co e between how
mp n the counter
are to behaves
Uni r (counts) and
t n how
o waveforms
t. are generated
A on the Output
C Compare
P output OC0.
U For more
w
details about
ri
t advanced
e counting
o sequences
v and waveform
e generation,
rr see “Modes
i of Operation”
d on page 76.
e
s The
( Timer/Counter
h Overflow
a (TOV0) Flag
s is set
p according to
ri
o the mode of
ri operation
t selected by
y the WGM01:0
o bits. TOV0
v can be used
e for generating
r) a CPU
a interrupt.
ll
c
o The 8-bit
u comparator
n continuously
t compares
e TCNT0 with
r the Output
cl Compare
Reg i nterrupt. The
ister n OCF0 Flag is
(OC S automatically
R0). R cleared when
Wh E the interrupt is
ene G executed.
ver i Alternatively,
TC s the OCF0
NT0 s Flag can be
equ e cleared by
als t) software by
OC , writing a
R0, t logical one to
the h its I/O bit
com e location. The
par O waveform
ator u gen-erator
sign t uses the
als p match signal
a u to generate an
mat t output
ch. C according to
A o operating
mat m mode set by
ch p the WGM01:0
will a bits and
set r Compare
the e Output mode
Out F (COM01:0)
put l bits. The max
Co a and bottom
mpa g signals are
re g used by the
Flag e waveform
(OC n generator for
F0) e handling the
at r special cases
the a of the extreme
next t values in
time e some modes
r s of operation (
cloc a See “Modes
k n of Operation”
cycl o on page 76.).
e. Ifu
Figure 29
ena t
shows a block
bled p diagram of the
(OC u output
IE0 t compare unit.
= 1c
and o Figure 29.
Glo m Output
bal p Compare Unit,
Inte a Block
rrup r Diagram
t e
Flag i DATA BU

top
bottom

FOCn
a ion Compare
n (PWM) Register
y modes. to either
For thetop or
o normal bottom of
f and the
Th
Clear counting
e
t Timer sequence
O
h on . The
C
e Compa synchroni
R
re zation
0
P (CTC) prevents
R
u modes the
eg
l of occurrenc
ist
s operati e of odd-
er
e on, thelength,
is
double non-
do
W buff- symmetri
ub
i ering iscal PWM
le
d disable pulses,
bu
t d. Thethereby
ffe
h double making
re
bufferin the output
d
M g glitch-
w
o synchr free.
he
d onizes
n
u the
us
l update
in
a of the
g 73
t OCR0
246
6T–
AV
R–
07/
10
ATmega16(L)

The OCR0 Register access may seem complex, but this is not case. When the double buffering
is enabled, the CPU has access to the OCR0 Buffer Register, and if double buffering is disabled
the CPU will access the OCR0 directly.

Force Output In non-PWM waveform generation modes, the match output of the comparator can be forced by
Compare writing a one to the Force Output Compare (FOC0) bit. Forcing compare match will not set the
OCF0 Flag or reload/clear the timer, but the OC0 pin will be updated as if a real compare match
had occurred (the COM01:0 bits settings define whether the OC0 pin is set, cleared or toggled).

Compare Match All CPU write operations to the TCNT0 Register will block any compare match that occur in the
Blocking by TCNT0 next timer clock cycle, even when the timer is stopped. This feature allows OCR0 to be initialized
Write to the same value as TCNT0 without triggering an interrupt when the Timer/Counter clock is
enabled.

Using the Output Since writing TCNT0 in any mode of operation will block all compare matches for one timer clock
Compare Unit cycle, there are risks involved when changing TCNT0 when using the output compare unit, inde-
pendently of whether the Timer/Counter is running or not. If the value written to TCNT0 equals
the OCR0 value, the compare match will be missed, resulting in incorrect waveform generation.
Similarly, do not write the TCNT0 value equal to BOTTOM when the counter is downcounting.
The setup of the OC0 should be performed before setting the Data Direction Register for the port
pin to output. The easiest way of setting the OC0 value is to use the Force Output Compare
(FOC0) strobe bits in Normal mode. The OC0 Register keeps its value even when changing
between waveform generation modes.
Be aware that the COM01:0 bits are not double buffered together with the compare value.
Changing the COM01:0 bits will take effect immediately.

Compare Match The Compare Output mode (COM01:0) bits have two functions. The Waveform Generator uses
Output Unit the COM01:0 bits for defining the Output Compare (OC0) state at the next compare match. Also,
the COM01:0 bits control the OC0 pin output source. Figure 30 shows a simplified schematic of
the logic affected by the COM01:0 bit setting. The I/O Registers, I/O bits, and I/O pins in the fig-
ure are shown in bold. Only the parts of the general I/O port Control Registers (DDR and PORT)
that are affected by the COM01:0 bits are shown. When referring to the OC0 state, the reference
is for the internal OC0 Register, not the OC0 pin. If a System Reset occur, the OC0 Register is
reset to “0”.

74
2466T–AVR–
07/10
ATmega16(L)

Figure 30. Compare Match Output Unit, Schematic

COMn1
COMn0 Waveform
FOCn Generator
DATABUS

clkI/O
D Q

1
OCn
OCn Pin
0

D Q

PORT

D Q

DDR
still controlled
ator usesby the correct PWM
Data the Direction refer to Table
COM01:0
Register (DDR) for 41 on page
The
the bitsport pin. The 84.
gener
al I/O Data differently
Direction A change of
in normal,
Regis-ter bit for the
port the COM01:0
functi OC0 CTC, and pin bits state will
PWM must be
(DDR_OC0)
on is have effect at
set as modes.
output before
overri the first
dden the andOC0 value is compare
Waveform
by visible on the pin. match after
the The port override the bits are
For all
function is written. For
Outp modes, of the
ut independent non-PWM
setting the modes, the
Com Waveform
COM01:0 action can be
pare Generation mode.
= 0 tells forced to have
(OC0 The thedesign of the immediate
) from outputwaveform
compare pin effect by using
the logic generatorallows the
Wave that no of the
initialization FOC0 strobe
form OC0 action
stateonbefore bits.
Gene the theout-put
OC0 is
rator Generatio
enabled. Note that
if somen COM01:0 bit
either settings are
of the Register
reserved is
for certain
COM modes to be
of operation.
01:0 See performed“8-bit
bits on the next
Timer/Counter
are compare
Register
match. For on
Description”
set.
Howe pagecompare
83.
output
ver,
actions in
the Comp the non-
OC0 are PWM modes
pin Outpu refer to
direct t 39 on page 84
ion Mode For fast PWM
(input The mode, refer to
or Wavef
Table 40 on
outpu orm page 84 75
t) isGener and for phase
2466T–AVR–07/10
ATmega16(L)

Modes of The mode of operation, that is, the behavior of the Timer/Counter and the Output Compare pins,
Operation is defined by the combination of the Waveform Generation mode (WGM01:0) and Compare Out-
put mode (COM01:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM01:0 bits control whether the PWM out-
put generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM01:0 bits control whether the output should be set, cleared, or toggled at a compare
match ( See “Compare Match Output Unit” on page 74.).
For detailed timing information refer to Figure 34, Figure 35, Figure 36 and Figure 37 in
“Timer/Counter Timing Diagrams” on page 81.

Normal Mode The simplest mode of operation is the normal mode (WGM01:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bot-
tom (0x00). In normal operation the Timer/Counter Overflow Flag ( TOV0) will be set in the same
timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth
bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt
that automatically clears the TOV0 Flag, the timer resolution can be increased by software.
There are no special cases to consider in the normal mode, a new counter value can be written
anytime.
The output compare unit can be used to generate interrupts at some given time. Using the out-
put compare to generate waveforms in Normal mode is not recommended, since this will occupy
too much of the CPU time.

Clear Timer on In Clear Timer on Compare or CTC mode (WGM01:0 = 2), the OCR0 Register is used to manip-
Compare Match (CTC) ulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value
Mode (TCNT0) matches the OCR0. The OCR0 defines the top value for the counter, hence also its
resolution. This mode allows greater control of the compare match output frequency. It also sim-
plifies the operation of counting external events.
The timing diagram for the CTC mode is shown in Figure 31. The counter value (TCNT0)
increases until a compare match occurs between TCNT0 and OCR0, and then counter (TCNT0)
is cleared.

Figure 31. CTC Mode, Timing Diagram

OCn Interrupt Flag Set

TCNTn

OCn
(COMn1:0 = 1)
(Toggle)

Period 1 2 3 4

An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF0 Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the
TOP value. However, changing TOP to a value close to BOTTOM when the counter is running
with none or a low prescaler value must be done with care since the CTC mode does not have
76
2466T–AVR–07/10
ATmega16(L)

the double buffering feature. If the new value written to OCR0 is lower than the current value of
TCNT0, the counter will miss the compare match. The counter will then have to count to its
max-imum value (0xFF) and wrap around starting at 0x00 before the compare match can occur.
For generating a waveform output in CTC mode, the OC0 output can be set to toggle its logical level
on each compare match by setting the Compare Output mode bits to toggle mode (COM01:0 = 1).
The OC0 value will not be visible on the port pin unless the data direction for the
pin is set to output. The waveform generated will have a maximum frequency of f OC0 = fclk_I/O/2
when OCR0 is set to zero (0x00). The waveform frequency is defined by the following equation:
f
f clk_I/O
OCn
= ----------------------------------------------

2 N  1 + OCRn
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cycle that
the counter counts from MAX to 0x00.

Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM01:0 = 3) provides a high frequency
PWM waveform generation option. The fast PWM differs from the other PWM option by its sin-
gle-slope operation. The counter counts from BOTTOM to MAX then restarts from BOTTOM. In
non-inverting Compare Output mode, the Output Compare (OC0) is cleared on the compare
match between TCNT0 and OCR0, and set at BOTTOM. In inverting Compare Output mode, the
output is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the
operating frequency of the fast PWM mode can be twice as high as the phase correct PWM
mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited
for power regulation, rectification, and DAC applications. High frequency allows physically small
sized external components (coils, capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is incremented until the counter value matches the MAX value.
The counter is then cleared at the following timer clock cycle. The timing diagram for the fast
PWM mode is shown in Figure 32. The TCNT0 value is in the timing diagram shown as a histo-
gram for illustrating the single-slope operation. The diagram includes non-inverted and inverted
PWM outputs. The small horizontal line marks on the TCNT0 slopes represent compare
matches between OCR0 and TCNT0.

Figure 32. Fast PWM Mode, Timing Diagram

OCRn Interrupt Flag Set

OCRn Update and


TOVn Interrupt Flag Set

TCNTn

OCn (COMn1:0 = 2)

OCn (COMn1:0 = 3)

Period 1 2 3 4 5 6 7

The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches MAX. If the
inter-rupt is enabled, the interrupt handler routine can be used for updating the compare value.

77
2466T–AVR–07/10
ATmega16(L)

In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0 pin.
Set-ting the COM01:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM01:0 to 3 (See Table 40 on page 84). The actual OC0
value will only be visible on the port pin if the data direction for the port pin is set as output. The
PWM waveform is generated by setting (or clearing) the OC0 Register at the compare match
between OCR0 and TCNT0, and clearing (or setting) the OC0 Register at the timer clock cycle
the coun-ter is cleared (changes from MAX to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
f
f clk_I/O
OCnPWM
= ------------------

N 256
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0 Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR0 is set equal to BOTTOM, the output will be a
narrow spike for each MAX+1 timer clock cycle. Setting the OCR0 equal to MAX will result in a
constantly high or low output (depending on the polarity of the output set by the COM01:0 bits.)

78
2466T–AVR–
07/10
ATmega16(L)

Phase Correct PWM The phase correct PWM mode (WGM01:0 = 1) provides a high resolution phase correct PWM
Mode waveform generation option. The phase correct PWM mode is based on a dual-slope operation.
The counter counts repeatedly from BOTTOM to MAX and then from MAX to BOTTOM. In non-
inverting Compare Output mode, the Output Compare (OC0) is cleared on the compare match
between TCNT0 and OCR0 while upcounting, and set on the compare match while downcount-
ing. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has
lower maximum operation frequency than single slope operation. However, due to the symmet-
ric feature of the dual-slope PWM modes, these modes are preferred for motor control
applications.
The PWM resolution for the phase correct PWM mode is fixed to eight bits. In phase correct
PWM mode the counter is incremented until the counter value matches MAX. When the counter
reaches MAX, it changes the count direction. The TCNT0 value will be equal to MAX for one
timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 33.
The TCNT0 value is in the timing diagram shown as a histogram for illustrating the dual-slope
operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal
line marks on the TCNT0 slopes represent compare matches between OCR0 and TCNT0.

Figure 33. Phase Correct PWM Mode, Timing Diagram

OCn Interrupt Flag Set

OCRn Update

TOVn Interrupt Flag Set

TCNTn

OCn (COMn1:0 = 2)

OCn (COMn1:0 = 3)

Period 1 2 3

The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches BOTTOM. The
Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM
value.
In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0
pin. Setting the COM01:0 bits to 2 will produce a non-inverted PWM. An inverted PWM out-put can
be generated by setting the COM01:0 to 3 (see Table 41 on page 84). The actual OC0 value will
only be visible on the port pin if the data direction for the port pin is set as output. The PWM
waveform is generated by clearing (or setting) the OC0 Register at the compare match between
OCR0 and TCNT0 when the counter increments, and setting (or clearing) the OC0 Register at
compare match between OCR0 and TCNT0 when the counter decrements. The

79
2466T–AVR–07/10
ATmega16(L)

PWM frequency for the output when using phase correct PWM can be calculated by the follow-
ing equation:
f
f clk_I/O
OCnPCPWM = ------------------
N 510
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0 Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR0 is set equal to BOTTOM, the
out-put will be continuously low and if set equal to MAX the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values.
At the very start of Period 2 in Figure 33 OCn has a transition from high to low even though
there is no Compare Match. The point of this transition is to guarantee symmetry around
BOTTOM. There are two cases that give a transition without Compare Match:
1• OCR0A changes its value from MAX, like in Figure 33. When the OCR0A value is MAX the
OCn pin value is the same as the result of a down-counting Compare Match. To ensure
symmetry around BOTTOM the OCn value at MAX must be correspond to the result of an up-
counting Compare Match.
2• The Timer starts counting from a value higher than the one in OCR0A, and for that reason
misses the Compare Match and hence the OCn change that would have happened on the
way up.

80
2466T–AVR–07/10
ATmega16(L)
k (clkT0) is
therefore
Ti T shown as a
me h clock enable
e signal in the
r/C Ti
following
ou m figures. The
nte e figures include
r r/ information on
Ti C when Interrupt
mi o Flags are set.
u Figure 34
ng nt contains
Dia e timing data for
gra r basic
ms is Timer/Counter
a operation. The
s figure shows
y the count
n sequence
c close to the
h MAX value in
r all modes
o other than
n phase correct
o PWM mode.
u
s Figure 34.
d Timer/Counter
e Timing
si Diagram, no
g Prescaling
n
a
n
d
th clkI/O
e
ti clkTn
m (clkI/O/1)
e
r
cl TCNTn
o
c
TOVn
t with the
i prescal
m er
i enabled clkI/
Fi n .
gu g O
re Figure
35 d 35. clk
sh a Timer/C
Tn
o t ounter
(clkI/O
w a Timing /8)
s , Diagra
th m, with
Prescal TCNTn
e b
sa u er
mt (fclk_I/O/
e TO
8)
s
Vn g of
OCF0
t in all
h modes
e except
Fi CTC
gu s mode.
re e
36 t
sh t
o i
w n 81
246
6T–
AV
R–
07/
10
ATmega16(L)

Figure 36. Timer/Counter Timing Diagram, Setting of OCF0, with Prescaler (f clk_I/O/8)

clkI/O

clkTn
(clkI/O/8)

TCNTn OCRn - 1 OCRn OCRn + 1 OCRn + 2

OCRn OCRn Value

OCFn

Figure 37 shows the setting of OCF0 and the clearing of TCNT0 in CTC mode.

Figure 37. Timer/Counter Timing Diagram, Clear Timer on Compare Match Mode, with Pres-
caler (fclk_I/O/8)

clk
I/O

clkTn
(clkI/O/8)

TCNTn
TOP - 1 TOP BOTTOM BOTTOM + 1
(CTC)

OCRn TOP

OCFn
82
2466T–AVR–07/10
ATmega16(L)
C
R0
8
-
b
i
t

T Bit 7
FOC0 WG
i Read/Write W R
m Initial Value 0
e
• Bit 7 – FOC0: Force
r
/ The FOC0 bit
is only active
C when the
o WGM00 bit
u specifies a
n non-PWM
t mode.
However, for
e ensuring
r compatibility
with future
R devices, this bit
e must be set to
zero when
g TCCR0 is
i written when
s operating in
t PWM mode.
e When writing a
logical one to
r
the FOC0 bit,
an immediate
D com-pare
e match is forced
s on the
Waveform
c
Generation
r unit. The OC0
i output is
p changed
t according to its
COM01:0 bits
i
setting. Note
o that the FOC0
n bit is
implemented
Tim as a strobe.
er/C Therefore it is
oun the value
ter
present in the
Con
COM01:0 bits
trol
that determines
Reg
the effect of the
iste
r– forced
TC compare.
A co p-ported by the
FO ntr Timer/Counter
C0 ol unit are:
stro the Normal mode,
be co Clear Timer on
will unt Compare
not ing Match (CTC)
gen se mode, and two
erat qu types of Pulse
e en Width
any ce Modulation
inter of (PWM) modes.
rupt the See Table 38
, co and “Modes of
nor unt Operation” on
will er, page 76.
it the
clea so
Table 38. Waveform Ge
r urc
the e WGM01 WG
time for Mode (CTC0) (PW
r in the 0 0
CT ma 1 0
C xi
mod mu 2 1
e m 3 1
usin (T Note: 1. The
g O CTC
OC P) 0
R0 co and
as unt PW
TOPer M0
. bit
val defi
The ue, nitio
FO an n
C0 d nam
bit wh es
is at are
alw typ now
ays e obs
rea of olet
d as W e.
Use
zero av
the
. efo WG
• rm M01
Bit Ge :0
3, 6 ne defi
– rati nitio
WG on ns.
M01 to How
:0: be ever
Wa , the
us func
vef
ed. tion
orm
Mo ality
Gen and
erat de locat
ion s ion
Mo of of
de op thes
er e
The ati bits
se on are
bits su com
patib bit COM01:0 bits
le s are set, the
with co OC0 output
previ ntr overrides the
ous
ol normal port
versi
ons the functionality of
of Ou the I/O pin it is
the tpu connected to.
timert However, note
. Co that the Data
• mp Direction
Bit ar Register (DDR)
5:4 e bit
– pin corresponding
CO (O to the OC0 pin
M01 C0 must be set in
:0: ) order to enable
Co be the output
mp ha driver.
are vio
Mat r. If
ch on
Out e
put or
Mo bot
de
h
The of
se the 83
2466
T–
AVR–
07/10
ATmega16(L)

When OC0 is connected to the pin, the function of the COM01:0 bits depends on the WGM01:0
bit setting. Table 39 shows the COM01:0 bit functionality when the WGM01:0 bits are set to a
normal or CTC mode (non-PWM).

Table 39. Compare Output Mode, non-PWM Mode


COM01 COM00 Description
0 0 Normal port operation, OC0 disconnected.
0 1 Toggle OC0 on compare match
1 0 Clear OC0 on compare match
1 1 Set OC0 on compare match

Table 40 shows the COM01:0 bit functionality when the WGM01:0 bits are set to fast PWM
mode.
(1)
Table 40. Compare Output Mode, Fast PWM Mode
COM01 COM00 Description
0 0 Normal port operation, OC0 disconnected.
0 1 Reserved
1 0 Clear OC0 on compare match, set OC0 at BOTTOM,
(non-inverting mode)
1 1 Set OC0 on compare match, clear OC0 at BOTTOM,
(inverting mode)
Note: 1. A special case occurs when OCR0 equals TOP and COM01 is set. In this case, the compare
match is ignored, but the set or clear is done at TOP. See “Fast PWM Mode” on page 77 for
more details.
Table 41 shows the COM01:0 bit functionality when the WGM01:0 bits are set to phase correct
PWM mode.

(1)
Table 41. Compare Output Mode, Phase Correct PWM Mode
COM01 COM00 Description
0 0 Normal port operation, OC0 disconnected.
0 1 Reserved

1 0 Clear OC0 on compare match when up-counting. Set OC0 on compare match
when downcounting.

1 1 Set OC0 on compare match when up-counting. Clear OC0 on compare match
when downcounting.
Note: 1. A special case occurs when OCR0 equals TOP and COM01 is set. In this case, the compare
match is ignored, but the set or clear is done at TOP. See “Phase Correct PWM Mode” on
page 79 for more details.

84
2466T–AVR–07/10
A
T
m
e
g
a
1
6(
L)

• Bit 2:0 – CS02:0: Clock Select


The three Clock Select bits select the clock source to be used by the
Timer/Counter.
Table 42. Clock Select Bit Description
CS02 CS01 CS00 Description
0 0 0 No clock source (Timer/Counter stopped).

Timer/Count 0 0 1 clkI/O/(No prescaling)


er 0 1 0 clkI/O/8 (From prescaler)
Register –
TCNT0 0 1 1 clkI/O/64 (From prescaler)
1 0 0 clkI/O/256 (From prescaler)
1 0 1 clkI/O/1024 (From prescaler)
1 1 0 External clock source on T0 pin. Clock on falling edge.
1 1 1 External clock source on T0 pin. Clock on rising edge.

If external pin modes are used for the Timer/Counter0, transitions on the
T0 pin will clock the counter even if the pin is configured as an output.
This feature allows software control of the counting.
Output
Compare
Register – Bit 7 6 5 4 3 2 1 0
OCR0 TCNT0[7:0] TCN
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0

The Timer/Counter Register gives direct access, both for read and write
operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT0
Register blocks (removes) the compare match on the following timer
clock. Modifying the counter (TCNT0) while the counter is running,
introduces a risk of missing a compare match between TCNT0 and the
Timer/Count OCR0 Register.
er
Interrupt
Mask Bit 7 6 5 4 3 2 1 0
Register – OCR0[7:0] OC
TIMSK Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
Initial Value 0 0 0 0 0 0 0 0

The Output Compare Register contains an 8-bit value that is continuously


compared with the counter value (TCNT0). A match can be used to
generate an output compare interrupt, or to generate a waveform output
on the OC0 pin.
OCIE0 bit is written to one, and the I-bit in the Status Register is set
Bit 7
(one), the Timer/Counter0 Compare Match interrupt is enabled. The
OCIE2 corresponding interrupt is executed if a compare match in Timer/Counter0
Read/Write R/W occurs, that is, when the OCF0 bit is set in the Timer/Coun-ter Interrupt
Initial Value 0 Flag Register – TIFR.

• Bit 1 – OCIE0: Timer/Counter0 Output Compare Match Interrupt Enable


When the 85
2466T–AVR–
07/10
ATmega16(L)
mer/Counter0
Overflow
• interrupt is
Bit enabled. The
0– corresponding
TO interrupt is
IE executed if an
0: overflow in
Ti Timer/Counter0
Tim m occurs, that is,
er/C er/ when the TOV0
oun Co bit is set in the
ter un Timer/Counter
Inte ter
Inter-rupt Flag
rrup 0
t Register –
Ov TIFR.
Flag erf
Reg
lo
iste
w
r Bit 7
Int
– OCF2 T
err
TIF Read/Write R/W R
up
R Initial Value 0
t
En
ab • Bit 1 – OCF0: Outpu
le The OCF0 bit
W is set (one)
he when a
n compare match
the occurs
TO between the
IE Timer/Counter0
0 and the data in
bit OCR0 – Output
is Compare
wri Register0.
tte OCF0 is
n cleared by
to hardware when
on executing the
e, corresponding
an interrupt
d handling
the vector.
I- Alternatively,
bit OCF0 is
in cleared by
the writing a logic
St one to the flag.
atu When the I-bit
s in SREG,
Re OCIE0
gis (Timer/Counter
ter 0 Compare
is Match Interrupt
set Enable), and
(o OCF0 are set
ne (one), the
), Timer/Counter0
the Compare
Ti Match Interrupt
is ex bit, TOIE0
exe ec (Timer/Counter
cute uti 0 Overflow
d. ng Inter-rupt
the Enable), and
• cor TOV0 are set
Bit res (one), the
0 – po Timer/Counter0
TO ndi Overflow
V0: ng interrupt is
Tim int executed. In
er/C err phase correct
oun upt PWM mode,
ter0 ha this bit is set
Ove ndl when
rflo ing Timer/Counter0
w
ve changes
Fla
cto counting
g
r. direction at
The Alt $00.
bit er
TO nat
V0 ive
is ly,
set TO
(on V0
e) is
whe cle
n anar
over ed
flow by
occ wri
urs tin
in g a
Tim log
er/C ic
ount on
er0. e
TO to
V0 the
is fla
clea g.
red W
by he
har n
d- the
war SR
e E
whe G
n I- 86
2466
T–
AVR–
07/10
ATmega16(L)
e
r
Ti Timer/Counter
1 1 and
me
P Timer/Counter
r/C 0 share the
r same
ou
e prescaler
nt module, but
s
er the
c Timer/Counter
0 s can have
al
an different
e prescaler
d settings. The
r
Ti description
s below applies
me to both
r/C Timer/Counter
1 and
ou Timer/Counter
nt 0.
t rce.
In The a The
te E Timer/C p prescal
s ed
rn x ounter f clock
t
al can be r has a
e
Cl r clocked o frequen
o n directly m cy of
c a by the either
k l system t fCLK_I/O/
h
S C clock e 8,
o l (by fCLK_I/O/
ur o setting p 64,
c c the r fCLK_I/O/
e k CSn2:0 e 256, or
= 1). s f /
S c CLK_I/O
This a 1024.
o provide l
u s the e The
r
fastest r prescal
c
Pr e operati c
er is
e on, with a
n free
s a
running
c maximu b
, that is,
al m e operate
er Timer/C
s
R ounter u
e clock s
indepe
s e ndently
frequen
d of the
et cy
equal toa clock
system s select
clock a logic of
frequen the
cy c Timer/C
(fCLK_I/ l ounter,
o
O). c and it is
Alterna k shared
tively, s by
one ofo Timer/C
four u
o e lock ist n if the
u s used. h other
nt c One e Timer/C
er a exampl ounter
1 l e ofT that
a e prescal i shares
n r ing m the
d w artifact e same
Ti i s r prescal
ml occurs / er also
er l when C uses
/C h the o prescali
o a timer isu ng. A
u v enable n prescal
nt e d andt er reset
er clockede will
0. i by ther affect
Si m prescal t the
nc p er (6 >o prescal
e l CSn2:0 er
th i > 1).p period
e c The r for all
pr a numbero Timer/C
es t of g ounters
ca i system r it is
le o clock a connect
r n cycles m ed to.
is s from
n when e An
ot f the x externa
af o timer ise l clock
fe r enable c source
applied
ct s d to theu to the
e i first - T1/T0
d t count ti pin can
by u occurs o be
th a can ben used as
e t from 1. Timer/C
Ti i to N+1H ounter
mo system o clock
er n clock w (clkT1/cl
/C s cycles, e kT0).
o where v The
u w N e T1/T0
nt h equals r pin is
er e the , sample
d once
’s r prescal c every
cl e er a system
oc divisor r clock
k a (8, 64,e cycle
se 256, or by the
le p 1024). m pin
ct, r u synchro
It is nization
th e s
possibl logic.
e s t
e to The
st c b synchro
use the
at a e nized
Prescal
e l (sampl
er
of e t ed)
Reset signal
th d a
for is then
e k
synchr passed
pr c e
onizing through
th c lock s to the
e . (clkI/O). y counter
e T The s is
d h latch ist update
g e transpa e d.
e rent inm
d r the Enablin
et e high g and
ec g period c disablin
to i of thel g of the
r. s internal o
Fi t system c clock
g e clock. k input
ur r c must be
e s The
edge y done
3 when
8 a detecto c
sh r r l T1/T0
o e generate has
w es one s been
s c clkT1/cl f stable
a l kT0 r for at
fu o
pulse o least
nc c m
tio k for one
n e each system
al d positivea clock
e (CSn2: n
cycle,
q a 0 = 7)
or otherwis
ui t e
negativ d e it is a
va t
le h e risk that
g
nt e (CSn2: a false
bl 0 = 6) e Timer/C
oc p edge it ounter
k o detects h
a clock
di s .
s pulse is
a i
gr t Figure b generat
a i 38. e ed.
mv T1/T0 e Each
of e Pin n half
th Sampli period
e e ng a of the
T d p external
1/ g
p clock
T e
0 li applied
sy o e must be
Tn
nc f d longer
hr t than
o h t one
ni e o
clkI/O
system
za clock
tio i t cycle to
n n ensure
h
a t correct
n e The e samplin
d r synchr g. The
e n onizati T external
d a on and 1 clock
g l edge / must be
e s detecto T guarant
d y r logic 0 eed to
et s have
introdu
ec t less
to e ces a p
delay i than
r m
of 2.5 n half the
lo
to 3.5 sys-tem
gi c
cl n ExtClk <d cle.
oc c u Since
k y fclk_I/O/2t the
fr ) giveny edge
eq ( a c detector
ue f 50/50% y uses
8 7
24
66
T–
AV
R–
07/
10
ATmega16(L)
sampling fre-
quency
s (Nyquist
a sampling
m theorem).
p However, due
li to variation of
n the system
g clock
, frequency and
t duty cycle
h caused by
e Oscillator
m source
a (crystal,
x resonator, and
i capacitors)
m tolerances, it
u is
m recommende
f d that
r maximum
e frequency of
q an external
u clock source
e is less than
n fclk_I/O/2.5.
c An external
y clock source
o can not be
f
prescaled.
a
Spe n Figure 39.
cial e Prescaler for
Fun x Timer/Counter
ctio t 0 and
n IO e Timer/Counter
Reg r (1)
1
iste n
r– a
SFI l clkI/O
OR c
Clear

l
o PSR10
c
k
it
c
T0
a
n T1
d
e
t
e
c
t
i
s
h
a
lf Note: 1. The synchro
t
h
e
w is performed.
il Writing a zero
Bit l to this bit will
b have no
e
Read/Write effect. Note
InitialcValue that
l Timer/Counter
e
• Bit 0 – PSR10:1 and
Prescaler Rese
a Timer/Counter
Wh r 0 share the
en e same
this d prescaler and
bit b a reset of this
is y prescaler will
writt h affect both
en a timers. This
to r bit will always
one, d be read as
the w zero.
Tim a
er/C r
ount e
er1 a
and ft
Tim e
er/C r
ount t
er0 h
pres e
cale o
r p
will e
be r
rese a
t. ti
The o
bit n 88
2466
T–
AVR–
07/10
ATmega16(L)
easurement.
The main
features are:
16-Th
1• True 16-bit
bit e16 Design (that is,
allows 16-bit
Ti - PWM)
mebitTi
2• Two
Independent
r/C m Output
er/ Compare Units
ou C 3• Double
Buffered
nt ou Output
nt Compare
er er Registers
1 un 4• One Input
it Capture Unit
all 5• Input Capture
o Noise Canceler
w 6• Clear Timer
s on Compare
ac Match (Auto
cu Reload)
rat 7• Glitch-free,
e Phase Correct
Pulse Width
pr Modulator
og (PWM)
ra 8• Variable
Ov m PWM Period
erv ex 9• Frequency
iew ec Generator
uti 10• External
on Event Counter
ti 11• Four
mi Independent
ng Interrupt
Sources (TOV1,
(e OCF1A,
ve OCF1B, and
nt ICF1)
m
an Most register
ag and bit
e references in
m this section are
en written in
t), general form. A
w lower case “n”
av replaces the
e Timer/Counter
ge number, and a
ne lower case “x”
rat replaces the
io output
n,
compare unit.
an
However,
d
when using the
si
register or bit
gn
defines in a
al
ti program, the
mi precise form
ng must be used
m (that is, TCNT1
for , own in bold.
acc ref The device
essi er specific I/O
ng to Register and
Tim Fi bit locations
er/C gu are listed in the
ount re “16-bit
er1 1 Timer/Counter
cou on Register
nter pa Description” on
valu ge page 110.
e 2.
and C
so P
on). U
ac
A
ce
sim
ss
plifi
ibl
ed
e
bloc
I/
k
O
diag
R
ram
eg
of
ist
the
er
16-
s,
bit
in
Tim
cl
er/C
ud
ount
in
er is
g
sho
I/
wn
O
in
bit
Figu
s
re
an
40.
d
For
I/
the
O
actu
pi
al
ns
plac
,
eme
ar
nt of
e
I/O
sh
pins 89
2466
T–
AVR–
07/10
ATmega16(L)

(1)
Figure 40. 16-bit Timer/Counter Block Diagram

Count TOVn
Clear (Int.Req.)
Control Logic
Direction clkTn Clock Select
Edge
Tn
Detector

TOP BOTTOM

( From Prescaler )
Timer/Counter
TCNTn
= =0
OCnA
(Int.Req.)

Waveform
= Generation
OCnA

OCRnA

Fixed OCnB
TOP (Int.Req.)
Values
DATABUS

Waveform
= Generation
OCnB

OCRnB ( From Analog


Comparator Ouput )
ICFn (Int.Req.)

Edge Noise
ICRn
Detector Canceler
ICPn

TCCRnA TCCRnB

Note: 1. Refer to Figure 1 on page 2, Table 25 on page 58, and Table 31 on page 63 for
Timer/Counter1 pin placement and description.

Registers The Timer/Counter (TCNT1), Output Compare Registers (OCR1A/B), and Input Capture Regis-
ter (ICR1) are all 16-bit registers. Special procedures must be followed when accessing the 16-
bit registers. These procedures are described in the section “Accessing 16-bit Registers” on
page 92. The Timer/Counter Control Registers (TCCR1A/B) are 8-bit registers and have no CPU
access restrictions. Interrupt requests (abbreviated to Int.Req. in the figure) signals are all visible
in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the Timer
Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure since these regis-
ters are shared by other timer units.
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the
T1 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to
increment (or decrement) its value. The Timer/Counter is inactive when no clock source is selected.
The output from the clock select logic is referred to as the timer clock (clk T1).
The double buffered Output Compare Registers (OCR1A/B) are compared with the Timer/Coun-ter
value at all time. The result of the compare can be used by the Waveform Generator to generate a
PWM or variable frequency output on the Output Compare pin (OC1A/B). See “Out- put Compare
Units” on page 98. The compare match event will also set the Compare Match Flag (OCF1A/B)
which can be used to generate an output compare interrupt request.
90
2466T–AVR–07/10
ATmega16(L)

The Input Capture Register can capture the Timer/Counter value at a given external (edge trig-
gered) event on either the Input Capture Pin (ICP1) or on the Analog Comparator pins ( See
“Analog Comparator” on page 201.) The Input Capture unit includes a digital filtering unit (Noise
Canceler) for reducing the chance of capturing noise spikes.
The TOP value, or maximum Timer/Counter value, can in some modes of operation be defined
by either the OCR1A Register, the ICR1 Register, or by a set of fixed values. When using
OCR1A as TOP value in a PWM mode, the OCR1A Register can not be used for generating a
PWM output. However, the TOP value will in this case be double buffered allowing the TOP
value to be changed in run time. If a fixed TOP value is required, the ICR1 Register can be used
as an alternative, freeing the OCR1A to be used as PWM output.

Definitions The following definitions are used extensively throughout the document:

Table 43. Definitions


BOTTOM The counter reaches the BOTTOM when it becomes 0x0000.

MAX The counter reaches its MAXimum when it becomes 0xFFFF (decimal 65535).

The counter reaches the TOP when it becomes equal to the highest value in the
count sequence. The TOP value can be assigned to be one of the fixed values:
TOP
0x00FF, 0x01FF, or 0x03FF, or to the value stored in the OCR1A or ICR1 Regis-
ter. The assignment is dependent of the mode of operation.

Compatibility The 16-bit Timer/Counter has been updated and improved from previous versions of the 16-bit
AVR Timer/Counter. This 16-bit Timer/Counter is fully compatible with the earlier version
regarding:
• All 16-bit Timer/Counter related I/O Register address locations, including Timer Interrupt
Registers.
• Bit locations inside all 16-bit Timer/Counter Registers, including Timer Interrupt Registers.
• Interrupt Vectors.
The following control bits have changed name, but have same functionality and register location:
1• PWM10 is changed to WGM10.
2• PWM11 is changed to WGM11.
3• CTC1 is changed to WGM12.
The following bits are added to the 16-bit Timer/Counter Control Registers:
1• FOC1A and FOC1B are added to TCCR1A.
2• WGM13 is added to TCCR1B.
The 16-bit Timer/Counter has improvements that will affect the compatibility in some special
cases.
91
2466T–AVR–07/10
ATmega16(L)
y the AVR
CPU via the
Ac T 8-bit data bus.
ces h The 16-bit
register must
sin e
be byte
g T accessed
16- C using two
bit N read or write
T
Re 1 operations.
gis , Each 16-bit
ter O timer has a
single 8-bit
s C
R register for
1 temporary
A storing of the
/ High byte of
B the 16-bit
, access. The
a same
n temporary
d register is
I shared
C between all
R 16-bit
1 registers
a within each
r 16-bit timer.
e Accessing the
1 Low byte
6 triggers the
- 16-bit read or
b write
it operation.
r When the Low
e byte of a 16-
g bit register is
is written by the
t CPU, the High
e byte stored in
r the temporary
s register, and
t the Low byte
h written are
a both copied
t into the 16-bit
c register in the
a same clock
n cycle. When
b the Low byte
e of a 16-bit
a register is
c read by the
c CPU, the High
e byte of the 16-
s bit register is
s copied into
e the tem-
d porary register
b in the same
cloc H ust be read
k i before the
cycl g High byte.
e ash
The following
the b
code
Low y
examples
byte t
show how to
is e
access the
rea m
16-bit Timer
d. u
s Registers
Not t assuming that
all b no interrupts
16- e updates the
bit w temporary
acc ri register. The
ess tt same principle
es e can be used
use n directly for
s b accessing the
the e OCR1A/B and
tem f ICR1
por o Registers.
ary r Note that
regi e when using
ster t “C”, the
for h compiler
the e handles the
Hig L 16-bit access.
h o
Assembly
byte w
Code
. (1)
Rea b Example
ding y ...
the t
OC e
1
R1A . ;
/B F S
16- o e
bit r t
regi a
ster 1 T
s 6 C
doe - N
s b T
not it 1
invo r
lve e t
usin a o
g d
the ,
0
tem t
x
por h
0
ary e
1
regi L
F
ster. o
F
To w
do a l
16- b d
bit y i
writ t
e, e r
the m 1
7 6 ...
, ,
0 T
Note: 1.
See “About
x C
Code
0 N Examples” on
1 T page 7.
1
The assembly
L
ldi
code example
r16 returns the
in
,0x TCNT1 value
r17,T
FF
CNT1H
in the r17:r16
out register pair.
...
TCN
C It is important
T1H to notice that
,r1
C accessing 16-
7
o bit registers
d
out are atomic
e
TCN operations. If
T1L an interrupt
E
,r1 occurs
6 x between the
a two
2 m instructions
p accessing the
; l
R 16-bit register,
e and the
e
a
interrupt code
( updates the
d
1 temporary
)
register by
T
accessing the
C
unsigsame or any
N ned other of the
T int
i; 16-bit Timer
1
... Regis-ters,
then the result
i /*
of the access
n Set
outside the
t TCNT1
interrupt will
o to
be corrupted.
0x01F
Therefore,
r F */
when both the
1 TCNT
main code
7 =
and the
: 0x1FF
interrupt code
r ;
update the
1 /*
temporary
6 Read
register, the
TCNT1
main code
into
i must disable
i */
n the interrupts
i =
during the 16-
r TCNT1bit access.
1 ;
9
2

2466
T–
AVR–
07/10
ATmega16(L)

The following code examples show how to do an atomic read of the TCNT1 Register contents.
Reading any of the OCR1A/B or ICR1 Registers can be done by using the same principle.
(1)
Assembly Code Example
TIM16_ReadTCNT1:

1; Save global interrupt flag


in r18,SREG

2; Disable interrupts
cli

1; Read TCNT1 into r17:r16


in r16,TCNT1L
in r17,TCNT1H

2; Restore global interrupt flag


out SREG,r18
ret
(1)
C Code Example
unsigned int TIM16_ReadTCNT1( void )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag
*/ sreg = SREG;
/* Disable interrupts
*/ _CLI();
/* Read TCNT1 into i
*/ i = TCNT1;
/* Restore global interrupt flag */
SREG = sreg;
return i;
}

Note: 1. See “About Code Examples” on page 7.


The assembly code example returns the TCNT1 value in the r17:r16 register pair.
93
2466T–AVR–07/10
ATmega16(L)

The following code examples show how to do an atomic write of the TCNT1 Register contents.
Writing any of the OCR1A/B or ICR1 Registers can be done by using the same principle.
(1)
Assembly Code Example
TIM16_WriteTCNT1:

1; Save global interrupt flag in r18,SREG

2; Disable interrupts
cli

1; Set TCNT1 to r17:r16 out TCNT1H,r17

out TCNT1L,r16

2; Restore global interrupt flag out SREG,r18


ret
(1)
C Code Example
void TIM16_WriteTCNT1 ( unsigned int i )
{
unsigned char sreg;
unsigned int i;
/* Save global interrupt flag */
sreg = SREG;
/* Disable interrupts */
_CLI();
/* Set TCNT1 to i */
TCNT1 = i;
/* Restore global interrupt flag */
SREG = sreg;
}

Note: 1. See “About Code Examples” on page 7.


The assembly code example requires that the r17:r16 register pair contains the value to be writ-
ten to TCNT1.

Reusing the If writing to more than one 16-bit register where the High byte is the same for all registers writ-
Temporary High Byte ten, then the High byte only needs to be written once. However, note that the same rule of
Register atomic operation described previously also applies in this case.

Timer/Counter The Timer/Counter can be clocked by an internal or an external clock source. The clock source
Clock Sources is selected by the Clock Select logic which is controlled by the Clock Select (CS12:0) bits
located in the Timer/Counter Control Register B (TCCR1B). For details on clock sources and
prescaler, see “Timer/Counter0 and Timer/Counter1 Prescalers” on page 87.

94
2466T–AVR–07/10
ATmega16(L)
ectly
accessed by
Co T the CPU.
h When the
unt
CPU does
Figure 41.
er an access
Uni to the
t TCNT1H I/O
location, the
CPU
accesses
the High
byte
temporary
register
(TEMP).
The
Signal description (internal sig
temporary
Count register is
updated
Direction
with the
Clear TCNT1H
value when
clk
the TCNT1L
TOP is read, and
TCNT1H is
BOTTOM
updated
with the
T temporary
h register
value when
TCNT1L is
written. This
allows the
CPU to read
or write the
entire 16-bit
counter
value within
one clock
cycle via the
8-bit data
bus. It is
important to
notice that
there are
special
cases of
writing to
the TCNT1
Register
when the
counter is
counting
that will give
unpredictabl
e results.
The special
cases are
described in
the b (CS12:0).
sect y When no
ions clock source
is selected
whe
(CS12:0 =
re 0) the timer
they is stopped.
are However,
of the TCNT1
imp value can
orta be
nce. accessed by
the CPU,
Dep independent
endi of whether
ng clkT1 is
on present or
the not. A CPU
mod write
e of overrides
ope (has priority
ratio over) all
n counter
use clear or
d, count
the operations.
cou
nter The
is counting
clea sequence is
red, determined
incr
eme by the
nted setting of
, or the
decr Waveform
eme Generation
nted Mode bits
at (WGM13:0)
eac
located in
h
time the
r Timer/Coun
cloc ter Control
k Registers A
(clk and B
T1). (TCCR1A
The and
clkT TCCR1B).
1 There are
can close
be connections
gen between
erat how the
ed counter
fro
behaves
m
an (counts) and
exte how
rnal waveforms
or are
inter generated
nal on the
cloc Output
k
sour Compare
ce, outputs
sele OC1x. For
cted more details
abo w set
ut a according to
adv T the mode of
anc h operation
ed selected by
cou the
ntin WGM13:0
g bits. TOV1
seq can be used
uen for
ces generating a
and CPU
interrupt.
9
5
2466
T–
AVR–
07/10
ATmega16(L)

Input Capture Unit The Timer/Counter incorporates an Input Capture unit that can capture external events and give them
a time-stamp indicating time of occurrence. The external signal indicating an event, or mul-tiple
events, can be applied via the ICP1 pin or alternatively, via the Analog Comparator unit. The time-
stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied.
Alternatively the time-stamps can be used for creating a log of the events.
The Input Capture unit is illustrated by the block diagram shown in Figure 42. The elements of
the block diagram that are not directly a part of the Input Capture unit are gray shaded. The
small “n” in register and bit names indicates the Timer/Counter number.

Figure 42. Input Capture Unit Block Diagram

DATA BUS (8-bit)

TEMP (8-bit)

ICRnH (8-bit) ICRnL (8-bit) TCNTnH (8-bit) TCNTnL (8-bit)

WRITE ICRn (16-bit Register) TCNTn (16-bit Counter)

ACO* ACIC* ICNC ICES

Analog
Comparator Noise Edge
ICFn (Int.Req.)
Canceler Detector
ICPn

When a change of the logic level (an event) occurs on the Input Capture pin (ICP1),
alternatively on the Analog Comparator output (ACO), and this change confirms to the setting of
the edge detector, a capture will be triggered. When a capture is triggered, the 16-bit value of
the counter (TCNT1) is written to the Input Capture Register (ICR1). The Input Capture Flag
(ICF1) is set at the same system clock as the TCNT1 value is copied into ICR1 Register. If
enabled (TICIE1 = 1), the Input Capture Flag generates an Input Capture Interrupt. The ICF1
Flag is automatically cleared when the interrupt is executed. Alternatively the ICF1 Flag can be
cleared by software by writing a logical one to its I/O bit location.
Reading the 16-bit value in the Input Capture Register (ICR1) is done by first reading the Low
byte (ICR1L) and then the High byte (ICR1H). When the Low byte is read the High byte is
copied into the High byte temporary register (TEMP). When the CPU reads the ICR1H I/O
location it will access the TEMP Register.
The ICR1 Register can only be written when using a Waveform Generation mode that utilizes
the ICR1 Register for defining the counter’s TOP value. In these cases the Waveform Genera-
tion mode (WGM13:0) bits must be set before the TOP value can be written to the ICR1
Register. When writing the ICR1 Register the High byte must be written to the ICR1H I/O loca-
tion before the Low byte is written to ICR1L.
96
2466T–AVR–07/10
ATmega16(L)

For more information on how to access the 16-bit registers refer to “Accessing 16-bit Registers”
on page 92.

Input Capture Pin The main trigger source for the Input Capture unit is the Input Capture pin (ICP1).
Source Timer/Counter1 can alternatively use the Analog Comparator output as trigger source for the
Input Capture unit. The Analog Comparator is selected as trigger source by setting the Analog
Comparator Input Capture (ACIC) bit in the Analog Comparator Control and Status Register
(ACSR). Be aware that changing trigger source can trigger a capture. The Input Capture Flag
must therefore be cleared after the change.
Both the Input Capture pin (ICP1) and the Analog Comparator output (ACO) inputs are sampled
using the same technique as for the T1 pin ( Figure 38 on page 87). The edge detector is also
identical. However, when the noise canceler is enabled, additional logic is inserted before the
edge detector, which increases the delay by four system clock cycles. Note that the input of the
noise canceler and edge detector is always enabled unless the Timer/Counter is set in a wave-
form generation mode that uses ICR1 to define TOP.
An Input Capture can be triggered by software by controlling the port of the ICP1 pin.

Noise Canceler The noise canceler improves noise immunity by using a simple digital filtering scheme. The
noise canceler input is monitored over four samples, and all four must be equal for changing the
output that in turn is used by the edge detector.
The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNC1) bit in
Timer/Counter Control Register B (TCCR1B). When enabled the noise canceler introduces addi-
tional four system clock cycles of delay from a change applied to the input, to the update of the
ICR1 Register. The noise canceler uses the system clock and is therefore not affected by the
prescaler.

Using the Input The main challenge when using the Input Capture unit is to assign enough processor capacity
Capture Unit for handling the incoming events. The time between two events is critical. If the processor has
not read the captured value in the ICR1 Register before the next event occurs, the ICR1 will be
overwritten with a new value. In this case the result of the capture will be incorrect.
When using the Input Capture Interrupt, the ICR1 Register should be read as early in the inter-
rupt handler routine as possible. Even though the Input Capture Interrupt has relatively high
priority, the maximum interrupt response time is dependent on the maximum number of clock
cycles it takes to handle any of the other interrupt requests.
Using the Input Capture unit in any mode of operation when the TOP value (resolution) is
actively changed during operation, is not recommended.
Measurement of an external signal’s duty cycle requires that the trigger edge is changed after
each capture. Changing the edge sensing must be done as early as possible after the ICR1
Register has been read. After a change of the edge, the Input Capture Flag (ICF1) must be
cleared by software (writing a logical one to the I/O bit location). For measuring frequency only,
the clearing of the ICF1 Flag is not required (if an interrupt handler is used).

97
2466T–AVR–07/10
ATmega16(L)
re Register
(OCR1x). If
Ou T TCNT equals
OCR1x the
tpu h
comparator
t e signals a
Co 1 match. A
6
mp - match will set
are b the Output
Uni it Compare Flag
ts c (OCF1x) at
o the next timer
m clock cycle. If
p enabled
a (OCIE1x = 1),
r the Output
a Com-pare
t Flag
o generates an
r output
c compare
o interrupt. The
n OCF1x Flag is
ti automatically
n cleared when
u the interrupt is
o executed.
u Alternatively
sl the OCF1x
y Flag can be
c cleared by
o software by
m writ-ing a
p logical one to
a its I/O bit
r location. The
e Waveform
s Generator
T uses the
C match signal
N to generate an
T output
1 according to
w operating
it mode set by
h the Waveform
t Generation
h mode
e (WGM13:0)
O bits and
u Compare
t Output mode
p (COM1x1:0)
u bits. The TOP
t and BOTTOM
C signals are
o used by the
m Waveform
p Generator for
a handling the
spe r od time for
cial e waveforms
cas s generated by
es o the Waveform
of l Generator.
the u
Figure 43
extr ti
shows a block
eme o
diagram of the
valu n
output
es ).
compare unit.
in I
The small “n”
som n
in the register
e a
and bit names
mod d
indicates the
es d
device
of iti
number (n = 1
ope o
for
ratio n
Timer/Counter
n (t
1), and the “x”
See o
indicates
“Mo t
output com-
des h
pare unit
of e
(A/B). The
Ope c
elements of
ratio o
the block
n” u
diagram that
on n
are not
pag t
directly a part
e e
of the output
101. r
r compare unit
)
e are gray
A s shaded.
spe o
cial l Figure 43.
feat u Output
ure ti Compare Unit,
of o Block
outp n Diagram
ut ,
com t DATA BU
par h
e e
unit T TEMP (8-bit)

A O
allo P
ws v
it toa
defi l
ne u
the e
Tim d OCR
er/C e
ount fi
er n
TO e
P s
valu t B
e h
(tha e
t is,p
cou e The OCR1x
nter ri Register is
dou e r BOTTOM of
ble ri the counting
buff n sequence. The
ered g synchronizatio
whe s n prevents the
n y occurrence of
usin n odd-length,
g c non-
any h symmetrical
of r PWM pulses,
the o thereby
twel ni making the
ve z output glitch-
Puls e free.
e s
The OCR1x
Widt t
Register
h h
access may
Mod e
seem complex,
ulati u
but this is not
on p
case. When
(PW d
the double
M) a
buffering is
mod t
enabled, the
es. e
CPU has
For o
access to the
the f
OCR1x Buffer
nor t
Register, and if
mal h
double
and e
buffering is dis-
Cle O
abled the CPU
ar C
will access the
Tim R
OCR1x
er 1
directly. The
on x
content of the
Co C
OCR1x (Buffer
mpa o
or Compare)
re m
Register is
(CT p
only changed
C) a
by a write
mod r
operation (the
es e
Timer/Counter
of R
does not
oper e
update this
atio gi
register
n, st
automatically
the e
as the TCNT1
dou- r
and ICR1
ble t
Register).
buff o
Therefore
erin ei
OCR1x is not
g ist
read via the
disa h
High byte
bled e
. r
The T
dou O
ble P 98
buff o
2466
T–
AVR–
07/10
ATmega16(L)

temporary register (TEMP). However, it is a good practice to read the Low byte first as when
accessing other 16-bit registers. Writing the OCR1x Registers must be done via the TEMP Reg-
ister since the compare of all 16 bits is done continuously. The High byte (OCR1xH) has to be
written first. When the High byte I/O location is written by the CPU, the TEMP Register will be
updated by the value written. Then when the Low byte (OCR1xL) is written to the lower eight
bits, the High byte will be copied into the upper 8-bits of either the OCR1x buffer or OCR1x Com-
pare Register in the same system clock cycle.
For more information of how to access the 16-bit registers refer to “Accessing 16-bit Registers”
on page 92.

Force Output In non-PWM Waveform Generation modes, the match output of the comparator can be forced by
Compare writing a one to the Force Output Compare (FOC1x) bit. Forcing compare match will not set the
OCF1x Flag or reload/clear the timer, but the OC1x pin will be updated as if a real compare
match had occurred (the COM1x1:0 bits settings define whether the OC1x pin is set, cleared or
toggled).

Compare Match All CPU writes to the TCNT1 Register will block any compare match that occurs in the next timer
Blocking by TCNT1 clock cycle, even when the timer is stopped. This feature allows OCR1x to be initialized to the
Write same value as TCNT1 without triggering an interrupt when the Timer/Counter clock is enabled.

Using the Output Since writing TCNT1 in any mode of operation will block all compare matches for one timer clock
Compare Unit cycle, there are risks involved when changing TCNT1 when using any of the output compare
units, independent of whether the Timer/Counter is running or not. If the value written to TCNT1
equals the OCR1x value, the compare match will be missed, resulting in incorrect waveform
generation. Do not write the TCNT1 equal to TOP in PWM modes with variable TOP values. The
compare match for the TOP will be ignored and the counter will continue to 0xFFFF. Similarly,
do not write the TCNT1 value equal to BOTTOM when the counter is downcounting.
The setup of the OC1x should be performed before setting the Data Direction Register for the
port pin to output. The easiest way of setting the OC1x value is to use the force output compare
(FOC1x) strobe bits in Normal mode. The OC1x Register keeps its value even when changing
between waveform generation modes.
Be aware that the COM1x1:0 bits are not double buffered together with the compare value.
Changing the COM1x1:0 bits will take effect immediately.

99
2466T–AVR–07/10
ATmega16(L)
he Waveform
Generator
Co T uses the
mp h COM1x1:0
bits for
are e
defining the
Mat Output
ch C Compare
o
Ou m (OC1x) state
tpu p at the next
t a compare
Uni r match.
Secondly the
t e COM1x1:0
O bits control
u the OC1x pin
t output
p source.
u Figure 44
t shows a
m simplified
o schematic of
d the logic
e affected by
the
( COM1x1:0 bit
C setting. The
O I/O Registers,
M I/O bits, and
1 I/O pins in the
x figure are
1 shown in
: bold. Only the
0 parts of the
) general I/O
b Port Control
i Registers
t (DDR and
s PORT) that
are affected
h by the
a COM1x1:0
v bits are
e shown. When
referring to
t the OC1x
w state, the
o reference is
for the
f internal OC1x
u Register, not
n the OC1x pin.
c If a System
t Reset occur,
i the OC1x
o Register is
n reset to “0”.
s
. Figure 44.
T Compare
Match Output
Unit
,
Sch
ema
tic

clk
function The COM1x1:0
generally bits
normal,
is
The general
independent CTC,
have I/O port
andeffect
no
of the on
function
Waveform is overridden
PWM
the Input by
Capture
Generation
the
mode,Output modes.
butunit.Compare
there are
(OC1x)
some exceptions. and
from Waveform
the
Refer
Waveform
to Generationif
Comp Generator
and are
either of the COM1x1:0
bits areOutpu set. However,
the t
The OC1x
designpin direction
of the output
(input Mode
or out-put) isallows
still
compareThe pin logic
controlled
initialization byof the
the OC1x
Wavef
Directionbefore the Register
state orm out-put is
(DDR)
enabled. for
Gener the
Note port
that pin.
some
The
COM1x1:0 Data bitDirection
ator settings
Registeruses bit for
are reserved for certain
the
OC1x
modes thepin (DDR_OC1x)
of operation.
“16-bitCOM1
must be set as output
Timer/Counter
before x1:0
Register theDescription”
OC1x valueon
is
page bits
visi-ble
110. on the pin.
The differe port override
ntly in
24
66
T–
AV
R–
07/
10
ATmega16(L)

Modes of The mode of operation, that is, the behavior of the Timer/Counter and the output compare pins,
Operation is defined by the combination of the Waveform Generation mode (WGM13:0) and Compare Out-
put mode (COM1x1:0) bits. The Compare Output mode bits do not affect the counting sequence,
while the Waveform Generation mode bits do. The COM1x1:0 bits control whether the PWM out-
put generated should be inverted or not (inverted or non-inverted PWM). For non-PWM modes
the COM1x1:0 bits control whether the output should be set, cleared or toggle at a compare
match ( See “Compare Match Output Unit” on page 100.)
For detailed timing information refer to “Timer/Counter Timing Diagrams” on page 108.

Normal Mode The simplest mode of operation is the Normal mode (WGM13:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the
BOTTOM (0x0000). In normal operation the Timer/Counter Overflow Flag (TOV1) will be set in
the same timer clock cycle as the TCNT1 becomes zero. The TOV1 Flag in this case behaves
like a 17th bit, except that it is only set, not cleared. However, combined with the timer overflow
interrupt that automatically clears the TOV1 Flag, the timer resolution can be increased by soft-
ware. There are no special cases to consider in the Normal mode, a new counter value can be
written anytime.
The Input Capture unit is easy to use in Normal mode. However, observe that the maximum
interval between the external events must not exceed the resolution of the counter. If the interval
between events are too long, the timer overflow interrupt or the prescaler must be used to
extend the resolution for the capture unit.
The output compare units can be used to generate interrupts at some given time. Using the out-
put compare to generate waveforms in Normal mode is not recommended, since this will occupy
too much of the CPU time.

Clear Timer on In Clear Timer on Compare or CTC mode (WGM13:0 = 4 or 12), the OCR1A or ICR1 Register
Compare Match (CTC) are used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when
Mode the counter value (TCNT1) matches either the OCR1A (WGM13:0 = 4) or the ICR1 (WGM13:0 =
12). The OCR1A or ICR1 define the top value for the counter, hence also its resolution. This
mode allows greater control of the compare match output frequency. It also simplifies the opera-
tion of counting external events.
The timing diagram for the CTC mode is shown in Figure 45. The counter value (TCNT1)
increases until a compare match occurs with either OCR1A or ICR1, and then counter (TCNT1)
is cleared.

Figure 45. CTC Mode, Timing Diagram

OCnA Interrupt Flag Set


or ICFn Interrupt Flag Set
(Interrupt on TOP)

TCNTn

OCnA
(COMnA1:0 = 1)
(Toggle)

Period 1 2 3 4
101
2466T–AVR–07/10
ATmega16(L)

An interrupt can be generated at each time the counter value reaches the TOP value by either using
the OCF1A or ICF1 Flag according to the register used to define the TOP value. If the interrupt is
enabled, the interrupt handler routine can be used for updating the TOP value. How-ever, changing
the TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value
must be done with care since the CTC mode does not have the double buff-ering feature. If the new
value written to OCR1A or ICR1 is lower than the current value of TCNT1, the counter will miss the
compare match. The counter will then have to count to its max-imum value (0xFFFF) and wrap
around starting at 0x0000 before the compare match can occur. In many cases this feature is not
desirable. An alternative will then be to use the fast PWM mode using OCR1A for defining TOP
(WGM13:0 = 15) since the OCR1A then will be double buffered.
For generating a waveform output in CTC mode, the OC1A output can be set to toggle its
logical level on each compare match by setting the compare output mode bits to toggle mode
(COM1A1:0 = 1). The OC1A value will not be visible on the port pin unless the data direction for
the pin is set to output (DDR_OC1A = 1). The waveform generated will have a maximum fre-
quency of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). The waveform frequency is
defined by the following equation:
f
clk_I/O

f =
OCnA 2 --------------------------------------------------N1+OCRnA
The N variable represents the prescaler factor (1, 8, 64, 256, or 1024).
As for the Normal mode of operation, the TOV1 Flag is set in the same timer clock cycle that
the counter counts from MAX to 0x0000.

Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM13:0 = 5,6,7,14, or 15) provides a
high frequency PWM waveform generation option. The fast PWM differs from the other PWM
options by its single-slope operation. The counter counts from BOTTOM to TOP then restarts
from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared
on the compare match between TCNT1 and OCR1x, and set at BOTTOM. In inverting Compare
Output mode output is set on compare match and cleared at BOTTOM. Due to the single-slope
operation, the operating frequency of the fast PWM mode can be twice as high as the phase cor-
rect and phase and frequency correct PWM modes that use dual-slope operation. This high
frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC
applications. High frequency allows physically small sized external components (coils, capaci-
tors), hence reduces total system cost.
The PWM resolution for fast PWM can be fixed to 8-bit, 9-bit, or 10-bit, or defined by either ICR1
or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and the
maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can be
calculated by using the following equation:

R = log TOP + 1
FPWM
----------------------------------log2
In fast PWM mode the counter is incremented until the counter value matches either one of the
fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 5, 6, or 7), the value in ICR1 (WGM13:0 =
14), or the value in OCR1A (WGM13:0 = 15). The counter is then cleared at the following timer
clock cycle. The timing diagram for the fast PWM mode is shown in Figure 46. The figure shows
fast PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing
diagram shown as a histogram for illustrating the single-slope operation. The diagram includes
non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes
represent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set
when a compare match occurs.

102
2466T–AVR–
07/10
ATmega16(L)

Figure 46. Fast PWM Mode, Timing Diagram

OCRnx / TOP Update and


TOVn Interrupt Flag Set
and OCnA Interrupt Flag
Set OCnA Interrupt Flag
Set (Interrupt on TOP)

TCNTn

OCnx (COMnx1:0 = 2)

OCnx (COMnx1:0 = 3)

Period 1 2 3 4 5 6 7 8

The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches TOP. In addition
the OC1A or ICF1 Flag is set at the same timer clock cycle as TOV1 is set when either OCR1A
or ICR1 is used for defining the TOP value. If one of the interrupts are enabled, the interrupt
han-dler routine can be used for updating the TOP and compare values.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x.
Note that when using fixed TOP values the unused bits are masked to zero when any of the
OCR1x Registers are written.
The procedure for updating ICR1 differs from updating OCR1A when used for defining the TOP
value. The ICR1 Register is not double buffered. This means that if ICR1 is changed to a low value
when the counter is running with none or a low prescaler value, there is a risk that the new ICR1
value written is lower than the current value of TCNT1. The result will then be that the counter will
miss the compare match at the TOP value. The counter will then have to count to the MAX value
(0xFFFF) and wrap around starting at 0x0000 before the compare match can occur. The OCR1A
Register however, is double buffered. This feature allows the OCR1A I/O location to be written
anytime. When the OCR1A I/O location is written the value written will be put into the OCR1A Buffer
Register. The OCR1A Compare Register will then be updated with the value in the Buffer Register at
the next timer clock cycle the TCNT1 matches TOP. The update is done at the same timer clock
cycle as the TCNT1 is cleared and the TOV1 Flag is set.
Using the ICR1 Register for defining TOP works well when using fixed TOP values. By using
ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. However,
if the base PWM frequency is actively changed (by changing the TOP value), using the OCR1A
as TOP is clearly a better choice due to its double buffer feature.
In fast PWM mode, the compare units allow generation of PWM waveforms on the OC1x pins.
Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM1x1:0 to 3 (See Table 44 on page 110). The actual OC1x
value will only be visible on the port pin if the data direction for the port pin is set as output
(DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Register at
the compare match between OCR1x and TCNT1, and clearing (or setting) the OC1x Register at
the timer clock cycle the counter is cleared (changes from TOP to BOTTOM).
103
2466T–AVR–07/10
ATmega16(L)

The PWM frequency for the output can be calculated by the following equation:
f
f clk_I/O
OCnxPWM
= ----------------------------------

N  1 + TOP
The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represents special cases when generating a PWM
waveform output in the fast PWM mode. If the OCR1x is set equal to BOTTOM (0x0000) the
out-put will be a narrow spike for each TOP+1 timer clock cycle. Setting the OCR1x equal to
TOP will result in a constant high or low output (depending on the polarity of the output set by
the COM1x1:0 bits.)
A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by set-
ting OC1A to toggle its logical level on each compare match (COM1A1:0 = 1). This applies only
if OCR1A is used to define the TOP value (WGM13:0 = 15). The waveform generated will have
a maximum frequency of fOC1A = fclk_I/O/2 when OCR1A is set to zero (0x0000). This feature is
similar to the OC1A toggle in CTC mode, except the double buffer feature of the output compare
unit is enabled in the fast PWM mode.

Phase Correct PWM The phase correct Pulse Width Modulation or phase correct PWM mode (WGM13:0 = 1,2,3,10,
Mode or 11) provides a high resolution phase correct PWM waveform generation option. The phase
correct PWM mode is, like the phase and frequency correct PWM mode, based on a dual-slope
operation. The counter counts repeatedly from BOTTOM (0x0000) to TOP and then from TOP to
BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared on
the compare match between TCNT1 and OCR1x while upcounting, and set on the compare
match while downcounting. In inverting Output Compare mode, the operation is inverted. The
dual-slope operation has lower maximum operation frequency than single slope operation. How-
ever, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for
motor control applications.
The PWM resolution for the phase correct PWM mode can be fixed to 8-bit, 9-bit, or 10-bit, or
defined by either ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set
to 0x0003), and the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM reso-
lution in bits can be calculated by using the following equation:

R = log TOP + 1
PCPWM
----------------------------------log2
In phase correct PWM mode the counter is incremented until the counter value matches either
one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM13:0 = 1, 2, or 3), the value in ICR1
(WGM13:0 = 10), or the value in OCR1A (WGM13:0 = 11). The counter has then reached the
TOP and changes the count direction. The TCNT1 value will be equal to TOP for one timer clock
cycle. The timing diagram for the phase correct PWM mode is shown on Figure 47. The figure
shows phase correct PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1
value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. The
diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on
the TCNT1 slopes represent compare matches between OCR1x and TCNT1. The OC1x Inter-
rupt Flag will be set when a compare match occurs.

104
2466T–AVR–
07/10
ATmega16(L)

Figure 47. Phase Correct PWM Mode, Timing Diagram

OCRnx/TOP Update and


OCnA Interrupt Flag Set
or ICFn Interrupt Flag Set
(Interrupt on TOP)

TOVn Interrupt Flag Set


(Interrupt on Bottom)

TCNTn

OCnx (COMnx1:0 = 2)

OCnx (COMnx1:0 = 3)

Period 1 2 3 4

The Timer/Counter Overflow Flag (TOV1) is set each time the counter reaches BOTTOM.
When either OCR1A or ICR1 is used for defining the TOP value, the OC1A or ICF1 Flag is set
accord-ingly at the same timer clock cycle as the OCR1x Registers are updated with the double
buffer value (at TOP). The Interrupt Flags can be used to generate an interrupt each time the
counter reaches the TOP or BOTTOM value.
When changing the TOP value the program must ensure that the new TOP value is higher or
equal to the value of all of the Compare Registers. If the TOP value is lower than any of the
Compare Registers, a compare match will never occur between the TCNT1 and the OCR1x.
Note that when using fixed TOP values, the unused bits are masked to zero when any of the
OCR1x Registers are written. As the third period shown in Figure 47 illustrates, changing the
TOP actively while the Timer/Counter is running in the phase correct mode can result in an
unsymmetrical output. The reason for this can be found in the time of update of the OCR1x
Reg-ister. Since the OCR1x update occurs at TOP, the PWM period starts and ends at TOP.
This implies that the length of the falling slope is determined by the previous TOP value, while
the length of the rising slope is determined by the new TOP value. When these two values differ
the two slopes of the period will differ in length. The difference in length gives the
unsymmetrical result on the output.
It is recommended to use the phase and frequency correct mode instead of the phase correct
mode when changing the TOP value while the Timer/Counter is running. When using a static
TOP value there are practically no differences between the two modes of operation.
In phase correct PWM mode, the compare units allow generation of PWM waveforms on the OC1x
pins. Setting the COM1x1:0 bits to 2 will produce a non-inverted PWM and an inverted PWM output
can be generated by setting the COM1x1:0 to 3 (See Table 44 on page 110). The actual OC1x
value will only be visible on the port pin if the data direction for the port pin is set as output
(DDR_OC1x). The PWM waveform is generated by setting (or clearing) the OC1x Regis-ter at the
compare match between OCR1x and TCNT1 when the counter increments, and clearing (or setting)
the OC1x Register at compare match between OCR1x and TCNT1 when

105
2466T–AVR–07/10
ATmega16(L)

the counter decrements. The PWM frequency for the output when using phase correct PWM
can be calculated by the following equation:
f
clk_I/O

f =
OCnxPCPWM ---------------------------NTOP
2

The N variable represents the prescaler divider (1, 8, 64, 256, or 1024).
The extreme values for the OCR1x Register represent special cases when generating a PWM
waveform output in the phase correct PWM mode. If the OCR1x is set equal to BOTTOM the
output will be continuously low and if set equal to TOP the output will be continuously high for
non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. If
OCR1A is used to define the TOP value (WGM13:0 = 11) and COM1A1:0 = 1, the OC1A output
will toggle with a 50% duty cycle.

Phase and Frequency The phase and frequency correct Pulse Width Modulation, or phase and frequency correct PWM
Correct PWM Mode mode (WGM13:0 = 8 or 9) provides a high resolution phase and frequency correct PWM wave-form
generation option. The phase and frequency correct PWM mode is, like the phase correct PWM
mode, based on a dual-slope operation. The counter counts repeatedly from BOTTOM
(0x0000) to TOP and then from TOP to BOTTOM. In non-inverting Compare Output mode, the
Output Compare (OC1x) is cleared on the compare match between TCNT1 and OCR1x while
upcounting, and set on the compare match while downcounting. In inverting Compare Output
mode, the operation is inverted. The dual-slope operation gives a lower maximum operation fre-
quency compared to the single-slope operation. However, due to the symmetric feature of the
dual-slope PWM modes, these modes are preferred for motor control applications.
The main difference between the phase correct, and the phase and frequency correct PWM
mode is the time the OCR1x Register is updated by the OCR1x Buffer Register, (see Figure 47
and Figure 48).
The PWM resolution for the phase and frequency correct PWM mode can be defined by either
ICR1 or OCR1A. The minimum resolution allowed is 2-bit (ICR1 or OCR1A set to 0x0003), and
the maximum resolution is 16-bit (ICR1 or OCR1A set to MAX). The PWM resolution in bits can
be calculated using the following equation:

R = log TOP + 1
PFCPWM
----------------------------------log2
In phase and frequency correct PWM mode the counter is incremented until the counter value
matches either the value in ICR1 (WGM13:0 = 8), or the value in OCR1A (WGM13:0 = 9). The
counter has then reached the TOP and changes the count direction. The TCNT1 value will be
equal to TOP for one timer clock cycle. The timing diagram for the phase correct and frequency
correct PWM mode is shown on Figure 48. The figure shows phase and frequency correct
PWM mode when OCR1A or ICR1 is used to define TOP. The TCNT1 value is in the timing
diagram shown as a histogram for illustrating the dual-slope operation. The diagram includes
non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT1 slopes
repre-sent compare matches between OCR1x and TCNT1. The OC1x Interrupt Flag will be set
when a compare match occurs.

106
2466T–AVR–
07/10

Das könnte Ihnen auch gefallen