– 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
• Non-volatile Program and Data Memories
– 16K Bytes of In-System Self-programmable Flash
Endurance: 10,000 Write/Erase Cycles
– Optional Boot Code Section with I ndependent Lock Bits
In-System Programming by On-chip Boot Program
T rue R ead- While -W ri te Operation
– 512 Bytes EEPROM
Endurance: 100,000 Write/Erase Cycles
– 1K Bytes Internal SRAM
– Up to 64K Bytes Optional External Memory Space
– Programming Lock for Software Security
• JTAG (IEEE std. 1149.1 Compliant) Interface
– Boundary-scan Capabilities According to the JTAG Standard
– Extensive On-chip Debug Support
– Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface
• Peripheral Features
– Two 8-bit Timer/Counters with Separate Prescalers and Compare Modes
– Two 16-bit Timer/Counters with Separate Prescalers, Compare Modes, and
Capture Modes
– Real Time Counter with Separate Oscillator
– Six PWM Channels
– Dual Programmable Serial USARTs
– Master/Slave SPI Serial Interface
– Programmable Watchdog Timer with Separate On-chip Oscillator
– On-chip Analog Comparator
• Special Microcontroller Features
– Power-on Reset and Programmable Brown-out Detection
– Internal Calibrated RC Oscillator
– External and Internal Interrupt Sources
– Five Sleep Modes: Idle, Power-save, Power-down, Standby, and Extended Standby
NOTE:
MLF bottom pad should
be soldered to ground.
XTAL1
(RD) PD7
(WR) PD6
(A8/PCINT8) PC0
(A9/PCINT9) PC1
(A11/PCINT11) PC3
(A10/PCINT10) PC2
(TCK/A12/PCINT12) PC4
DisclaimerTypical values contained i n this dat asheet are based on simulatio ns and ch aracteriza-
tion of other AVR microcontrollers manufactured on the same process technology. Min
and Max values will be available af ter the device is characterized.
2
ATmega162/V
2513E–AVR–09/03
ATmega162/V
OverviewThe ATmega162 is a low-power CMOS 8-bit microc ontroller based on the AVR
enhanced RISC architecture. By executing powerful instructions in a singl e clock cycle,
the ATmega162 achieves throughputs app roaching 1 MIPS per MH z allowing the system designer to optimize power consumption versus processing speed.
Block DiagramFigure 2. Block Diagram
VCC
PA0 - PA7PC0 - PC7
PORTA DRIVERS/BUFFERS
PE0 - PE2
PORTE
DRIVERS/
BUFFERS
PORTC DRIVERS/BUFFERS
GND
PORTA DIGITAL INTERFACE
PROGRAM
COUNTER
PROGRAM
FLASH
INSTRUCTION
REGISTER
INSTRUCTION
DECODER
CONTROL
LINES
AVR CPU
PROGRAMMING
LOGIC
STACK
POINTER
SRAM
GENERAL
PURPOSE
REGISTERS
X
Y
Z
ALU
STATUS
REGISTER
SPI
PORTE
DIGITAL
INTERFACE
PORTC DIGITAL INTERFACE
INTERNAL
OSCILLATOR
WATCHDOG
TIMER
MCU CTRL.
& TIMING
INTERRUPT
UNIT
TIMERS/
COUNTERS
EEPROM
USART0
OSCILLATOR
INTERNAL
CALIBRATED
OSCILLATOR
OSCILLATOR
XTAL1
XTAL2
RESET
2513E–AVR–09/03
+
-
PORTB DIGITAL INTERFACE
PORTB DRIVERS/BUFFERS
COMP.
INTERFACE
USART1
PORTD DIGITAL INTERFACE
PORTD DRIVERS/BUFFERS
PD0 - PD7PB0 - PB7
3
The AVR core combines a ric h instr uctio n set wit h 32 general purpose worki ng regi sters .
All the 32 regi sters are dire ctly conn ected to the Arithm etic Logic U nit (A LU), all owing
two independent regist ers t o be acces sed i n one sing le inst ructi on execut ed in one clo ck
cycle. The resulting arc hitect ur e is more code eff icient whil e achievi ng throug hput s up to
ten times faster than conventional CISC microcontrollers.
The ATmega162 provides the foll owing feat ures: 16 K bytes of In-Sy stem Progra mmable
Flash with Read-While-Write ca pabilities, 512 bytes EEP ROM, 1K bytes SRAM, an
external memory i nterface, 35 ge neral pu rpose I/O lin es, 32 genera l purpose work ing
registers, a JTAG interface for Boundary-scan, On-c hip Debugging support and programming, four flexible Time r/Counters with compa re modes, internal and externa l
interrupts, two serial programmable USARTs, a programmable Watchdog Timer with
Internal Oscillator, an SPI serial port, and five software sel ectable power saving modes.
The Idle mode stops the CPU while allowing the 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 interrupt
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. In
Standby mode, the crystal/resonator Oscillat or 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 non-volatile memory technology.
The On-chip ISP Flash allows the program memory to be reprogrammed In-System
through an SPI serial interface, by a conventional non-volat ile memory programmer, or
by an On-chip Boot Program running on the AVR core. The Boot Program can use any
interface to down load the Ap plicatio n Program in t he Applica tion Flash m emory. Soft ware in the Boot Flash section will continue to run while the Applicati on Flash section is
updated, providing true Read-While-Write operation. By combining an 8-bit RISC C PU
with In-System Self-Pr ogrammable Flash on a monolithic chip, the Atmel ATmega162 is
a powerful micro controll er that provi des a highly flexible and cost effe ctive solu tion to
many embedded control applications.
ATmega161 and
ATmega162
Compatibility
4
ATmega162/V
The ATmega162 AVR is supported with a full suite of program and system development
tools including: C comp ilers , macro assem blers, pr ogram debugg er/simul ators, In-Circuit Emulators, and evaluation kits.
The ATmega162 is a highly complex microcontroller where t he number of I/O locations
supersedes the 64 I/O locations reserv ed in the AVR instru ction set. To ensure ba ckward compatibility with the ATmega 161, all I/O lo cations present in A Tmega161 ha ve
the same locations in ATmega162. Some additional I/O locations are added in an
Extended I/O spa ce starting from 0x60 to 0xFF, (i .e., in th e ATm ega162 interna l RA M
space). These locations can be reached by using LD/LDS/LDD and ST/STS/STD
instructions only, not by using IN and OUT instructions. The relocation of the interna l
RAM space may still be a problem for ATmega161 users. Also, the increased number of
Interrupt Vectors might be a problem if the code uses absolute addresses. To solve
these problems, an ATmega161 compa tibility mode can be selected by programming
the fuse M161C. I n this mod e, none of the fun ctions in th e Extended I/O space are in
use, so the internal RAM is l ocated as in ATmega161. Also, the Extended Interrupt Vectors are removed. The ATme ga162 is 100% pin compa tible with ATm ega161, and ca n
replace the ATmega161 on current Printed Circuit Boards. However, the location of
Fuse bits and the electrical characteristics differs between the two devices.
2513E–AVR–09/03
ATmega162/V
ATmega161 Compatibility
Mode
Programming the M161C will change the following functionality:
•The extended I/O map will be configured as internal RAM once the M161C Fuse is
programmed.
•The timed sequence for changing the Watchdog Time-out period i s disabled. See
“Timed Sequences for Changing t he Configurat ion of the Watchdog Timer” on page
55 for details .
•The double buffering of the USART Receive Registers is disabl ed. See “AVR
USART vs. AVR UART – Compatibility” on page 167 for detai ls.
•Pin change interrupts ar e not supported (Control Registers ar e located in Extended
I/O).
•One 16 bits Timer/Counter (Timer/Counter1) only. Timer/Counter3 is not accessib le .
Note that the shared UBRRHI Register in ATmega161 is split int o two separate re gister s
in ATmega162, UBRR0H and UBRR1H . The location of these registers will not be
affected by the ATmega161 compatibility fuse.
Pin Descriptions
VCCDigital supply voltage
GNDGround
Port A (PA7..PA0)Port A is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each
bit). The Port A output buf fers have symmetrical 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.
Port A also serves the functions of various special features of the ATmega162 as listed
on page 71.
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 buf fers have symmetrical drive characteristics with both high sink
and source capability. As inputs, Por t B pins that are externally p ulled low w ill source
current if the pull-up resi stors 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 ATmega162 as listed
on page 71.
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 charact eristics with both high sink
and source capability. As inputs, Port C pins that are externally pulled low will s ource
current if the pull-up resistors are activated. The Port C pins are tri-stated when a reset
condition become s acti ve, even if the clock is n ot runni ng. If the JTA G int erface is
enabled, the pull-up resistors on pins PC7(TDI), PC5(TMS) and PC4(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
ATmega162 as listed on page 74.
2513E–AVR–09/03
5
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 charact eristics with both high sink
and source capability. As inputs, Port D pins that are externally pulled low will s ource
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 ATmega162 as listed
on page 77.
Port E(PE2..PE0)Port E is an 3-bit bi-directional I/O port with internal pull-up resistors (selected for each
bit). The Port E output buf fers have symmetrical drive characteristics with both high sink
and source capability. As inputs, Por t E pins that are externally p ulled low w ill source
current if the pull-up resi stors are activated. The Port E pins are tri- stated when a reset
condition becomes active, even if the clock is not running.
Port E also serves the functions of various special features of the ATmega162 as listed
on page 80.
RESET
XTAL1Input to the Inverting Oscillator amplifier and input to the int ernal clock operating circuit .
XTAL2Output from the Inverting Oscillator amplifier.
Reset input. A low level on this pin for longer than the minimum pulse length will generate a Reset, even if t he clock is not running. The minimum pulse length is given in Table
18 on page 47. Shorter pulses are not guara nteed to generate a reset.
About Code Exam pl e s This documentation contai ns simpl e code examples that bri efly show how to use var ious
parts of the device. These cod e example s assume tha t the part speci fic header file is
included before compilation. Be aware that not all C compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent. Please
confirm with the C compiler documentation for more details.
6
ATmega162/V
2513E–AVR–09/03
ATmega162/V
AVR CPU Core
IntroductionThis section discusses the AV R core architecture in general. The main function of the
CPU core is to e nsu re corre ct program exec ution. The CP U mu st there fore b e abl e to
access memories, perform cal culations, control peripher als, and handle interrupts.
Architectural OverviewFigure 3. Block Diagram of the AVR Architecture
Data Bus 8-bit
Flash
Program
Memory
Instruction
Register
Instruction
Decoder
Control Lines
Program
Counter
Direct Addressing
Status
and Control
32 x 8
General
Purpose
Registrers
ALU
Indirect Addressing
Data
SRAM
EEPROM
Interrupt
Unit
SPI
Unit
Watchdog
Timer
Analog
Comparator
I/O Module1
I/O Module 2
I/O Module n
2513E–AVR–09/03
I/O Lines
In order to maximize per formance and parallelism, the AVR uses a Harvard architecture
– with separate memories and buses f or program and data. Instructions in the program
memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program mem ory. This concept
enables instructions to be executed in every clock cycle. The program memory is InSystem Reprogrammable Flash memory.
The fast-access Regist er File contains 32 x 8-bit general purpose working registers with
a single clock cycle a ccess time. This a llows single -cycle Arithmetic Logic Unit (ALU)
operation. In a typical AL U operation, two operands are out put from the Registe r File,
the operation is executed, and the result is stored back in the Regi ster File – in one
clock cycle.
7
Six of the 32 registers can be used as three 16-bit indirect address register pointers for
Data Space addressing – enabling efficient address calculations. One of the these
address pointers can also be used as an address pointer for look up tables in Flash Program memory. These adde d function registers are the 1 6-bit X-, Y-, and Z-register,
described later in t his section.
The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations can also be executed in the ALU. After
an arithmetic operation, the St atus Regist er is updat ed to reflect i nformation a bout the
result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions,
able to directly address the whole address space. Most AVR instructions have a single
16-bit word format. Every program memory address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program section and
the Application Program secti on. Both sections hav e dedicated Lock bits for write and
read/write protect ion. The SPM instruction that writ es into the Application Flas h memory
section must reside in the Boot Program section.
During interrupts and subroutine cal ls, the return address Program Counter (PC) is
stored on the Stack . Th e Stac k is effectiv ely al locat ed in t he general data SRAM , a nd
consequently the Stack size is only limited by the total SRAM size and the usage of the
SRAM. All user programs must initialize the SP in the reset routine (before subroutines
or interrupts are executed). The Stack Pointer SP is read/write accessible in the I/O
space. The data SRAM can easily be accessed through the five different addressing
modes supported in the AVR architecture.
The memory spaces in the AVR architecture ar e all linear and regular memory maps.
A flexible inte rrupt modu le has its con trol regist ers in the I/O space with an additio nal
Global Interrupt Enabl e bit in the St atus Regis ter. All i nterr upts have a sep arat e Interrup t
Vector in the Interrupt Vector table. The interrupts have priority in accordance with their
Interrupt Vector pos ition. The lower the Interrupt Vect or address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control
Registers, SPI, and other I/O functions. The I/O memory can be accessed directly, or as
the Data Space locations follow ing t hose of t he Register File, 0x20 - 0x5F.
ALU – Arithmetic Logic
Unit
The high-performance AVR ALU operates in direct connection with all the 32 general
purpose worki ng register s. Withi n a single cl ock cycle, arithmet ic operat ions betw een
general purp ose regis ters or be tween a re giste r and an imme diate ar e ex ecuted . T he
ALU operations are divided i nto three main categories – ari thmet ic, logical, and bit-functions. Some implementations of the architecture also provide a powerful multiplier
supporting both signed/unsi gned m ultiplic ation and fractio nal format. See the “Ins truction Set” section for a detailed description.
Status RegisterThe Status Register contains information about the result of the most recently executed
arithmetic instruction. This information can be used for altering program flow i n order to
perform conditi onal opera tions. Note that the Stat us Registe r is update d after all AL U
operations, as specified in the Instruction Set Reference. This will in many cases
remove the need for using the dedicat ed compare instructions, resulting in faster and
more compact code.
The Status Register is not a utomaticall y stored wh en ent ering an i nterrupt routine and
restored when returning from an interrupt. This must be handled by software.
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate control registers. If the Global
Interrupt Enable Register is cleared, none of the interrupts are enabled independent of
the individual interrupt enable sett ings. The I-bit is cl eared by hardwar e after an in terrup t
has occurred, and is set by the RETI instruction to enable subsequent interrupts. The Ibit can also be set and cleared by the application with the SEI and CLI instructions, as
described in the instruction set reference.
• Bit 6 – T: Bit Copy Storage
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T bit as source or
destination for the operated bit. A bit from a register in the Reg ister File can be copied
into T by the BST instruction, and a bit i n T can be copied into a b it in a reg ister in the
Register File by the BLD instruct ion.
• Bit 5 – H: Half Car ry Flag
The Half Carry Flag H indicates a half carry in some ari thmetic operations. Half Carry is
useful in BCD arithmetic. See the “Instru cti on Set Description” for detailed information.
• Bit 4 – S: Sign Bit, S = N
⊕ V
The S-bit is always an exclusiv e or between t he Negative Flag N and the Two’ s Complement Overflow Flag V. See the “Instruction Set Descr iption” for detailed informati on.
• Bit 3 – V: Two ’s Comp le m ent Overfl ow F lag
The Two’s C omplem ent O verflow Fla g V s upports two’s compl eme nt a rithmet ics. S ee
the “Instruction Set Descr iption” for detailed inform ation.
• Bit 2 – N: N e gative F lag
The Negative Flag N indicat es a negative result in an arithmetic or logic operation. See
the “Instruction Set Descr iption” for detailed inform ation.
• Bit 1 – Z: Zero Flag
The Zero Flag Z indicates a zero result i n an arith metic or logic operation. S ee 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.
2513E–AVR–09/03
9
General Purpose
Register File
The Register F ile is optim ized f or the A VR E nhanc ed RIS C in struction set. I n orde r to
achieve the required performance and flexibility, the following input/output schemes are
supported by the Register File:
•One 8-bit output operand and one 8-bit result input
•Two 8-bit output operands and one 8-bit result input
•Two 8-bit output operands and one 16-bit result input
•One 16-bit output operand and one 16-bit result input
Figure 4 shows the structure of the 32 general purpose working registers in the CPU.
Figure 4. AVR CPU General Purpose Wor king Registers
70Addr.
R0 0x00
R10x01
R20x02
…
R130x0D
GeneralR140x0E
PurposeR150x0F
WorkingR160x10
RegistersR170x11
…
R260x1AX-register Low Byte
R270x1BX-register High Byte
R280x1CY-register Low Byte
R290x1DY-reg ister High Byte
R300x1EZ-register Low Byte
R310x1FZ-register High Byte
Most of the instruction s operati ng on the Regist er File have di rec t access to al l regi sters ,
and most of them are single cycle instructions.
As shown in Figure 4, each register is also assigned a data memory address, mapping
them directly into the first 32 locati ons of the user Data Space. Although not being physically implemented as SRAM locations, t his memory organizati on provides great
flexibility in access of the registers, as the X-, Y-, and Z-poi nter registers can be set to
index any register in the file.
10
ATmega162/V
2513E–AVR–09/03
ATmega162/V
The X-register, Y-register, and
Z-register
The registers R26..R31 have some added functions to their general purpose usage.
These registers are 16-bit address pointers for i ndirect addressing of the Data Sp ace.
The three indirect address registers X, Y, and Z are defined as described in Figure 5.
Figure 5. The X-, Y-, and Z-registers
15XHXL0
X - register7070
R27 (0x1B)R26 (0x1A)
15YHYL0
Y - register7070
R29 (0x1D)R28 (0x1C)
15ZHZL0
Z - register7070
R31 (0x1F)R30 (0x1E)
In the different addressi ng mode s these ad dress registe rs have f unctions as f ixed di splacement, autom atic increment, and aut omatic decreme nt (see the instruction set
reference for details).
Stack PointerThe Stack is mainly used for storing temp orary data, for storing l ocal variables and for
storing return addresses aft er interrupts and subroutine calls. The Stack Pointer Register always points to the top of the Stack. Note that the Stack is implemented as growing
from higher memory locati ons to lower mem ory locations. This implies that a Stack
PUSH command decreases the Stack Pointer.
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the
program before any subroutine calls are executed or interrupts are enabled. The Stack
Pointer must be set to point a bove 0x60. The Stack Poi nter is decremented by one
when data is pushed ont o the Stack with the PUSH instruction, and it i s decremented by
two when the return address is pushed onto the Stack with subroutine call or interrupt.
The Stack Pointer is incremented by one when dat a is popped f rom the Stack with the
POP instruction, and it is incremented by two when data is popped from the Stack with
return from subroutine RET or return from interrupt RETI.
The AVR Stack Pointer is implemented as two 8-bi t registers in the I/O space. The number of bits actually used i s implementation dependent. Note that the data space in some
implementations of the AVR architecture is so small that only SPL is needed. In this
case, the SPH Register will not be present.
Bit1514131211109 8
SP15SP14SP13SP12SP11SP10SP9SP8SPH
SP7SP6SP5SP4SP3SP2SP1SP0SPL
76543210
Read/WriteR/WR/WR/WR/WR/WR/WR/WR/W
R/WR/WR/WR/WR/WR/WR/WR/W
Initial Value00000000
00000000
2513E–AVR–09/03
11
Instruction Execution
Timing
This section describes the gener al access timing conc epts for i nstruct ion execut ion. The
AVR CPU is driven by the CPU clock clk
, directly generated from the selected clock
CPU
source for the chip. No internal clock division is used.
Figure 6 shows the parallel instructi on fetches and instruc tion exec utions enab led by the
Harvard architecture and the fast-access Register File concept. This is the basic pi pelining concept t o obtain up t o 1 M IPS p er MH z with t he co rrespondin g u nique res ults for
functions per cost, functions per clocks, and functions per power-unit.
Figure 6. The Paral lel Instruction Fetches and Instruction Execut ions
T1T2T3T4
clk
CPU
1st Instruction Fetch
1st Instruction Execute
2nd Instruction Fetch
2nd Instruction Execute
3rd Instruction Fetch
3rd Instruction Execute
4th Instruction Fetch
Figure 7 shows the internal timing concept for the Register File. In a single clock cycle
an ALU operation using two register operands is executed, and the result is st ored back
to the destination regis ter.
Reset and Interrupt
Handling
Figure 7. Single Cycle ALU Operation
T1T2T3T4
clk
CPU
Total Execution Time
Register Operands Fetch
ALU Operation Execute
Result Write Back
The AVR provides several different interrupt sources. These interrupts and the separate
Reset Vector each have a separate program vector in t he program memo ry space. Al l
interrupts are assigned indi vidual en able bits w hich must b e wr itten logic one together
with the Global Interru pt Ena ble bit i n the Stat us Reg ister in orde r to enabl e the i nterr upt.
Depending on the Program Counter value, interrupts may be automatically disabled
when Boot Lock bits BLB02 or BLB12 are programmed. This feature improves software
security. See the section “Memor y Programming” on page 230 for details.
The lowest addresses in the p rogram memory spa ce are by def ault def ined as t he Rese t
and Interrupt Vectors. The complete list of vectors is shown in “Interrupts” on page 56.
The list also determines the priori ty levels of the different interrupts. The lower the
address the higher is the priority level. RESET has the highest priority, and next is INT0
– the External Interrupt Request 0. The Int errupt 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 56 for more information. The Reset Vector can
12
ATmega162/V
2513E–AVR–09/03
ATmega162/V
also be moved to the start of the Boot Flash section by programming the BOOTRST
Fuse, see “Boot Loader Support – Read-While-Write Self-programming” on page 216.
When an interrupt occurs, the Global In terrupt Enab le I-bit is cleared and al l interrupts
are disabled. The user softw are ca n wri te logi c on e to the I-bit t o en able n este d int errupts. All enabled interrupts can then i nterrupt the current interrupt routine. The I-bit is
automatically set when a Return from Int errupt instruction – RETI – is executed.
There are basicall y two types of inter rupts. 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 Vector 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 bi t posi tion( s) to be c leared. If an i nterr upt condi tion oc cur s while the
corresponding interrupt enable bit is cleared, the Interrupt Fl ag 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 pri ority.
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 tri ggered.
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 Regi ster 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 interr upt 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 int errupts 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 val ue (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) */
2513E–AVR–09/03
13
When using the SEI instruction to enable interrupts, the instruction following SEI will be
executed before any pending inter rupt s, as shown in this example.
Assembly Code Example
sei; set global interrupt enable
sleep ; enter sleep, waiting for interrupt
; note: will enter sleep before any pending
; 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 TimeThe interrupt execution response for all the enabled AVR interrupts is four clock cycles
minimum. 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 vect or i s normall y a jum p to t he int errupt routin e, and thi s
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, t he 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.
14
ATmega162/V
2513E–AVR–09/03
ATmega162/V
AVR ATmega162
Memories
In-System
Reprogramma ble Flash
Program Memory
This section describes the different memories in the ATmega162. The AVR architecture
has two main memory spaces, the Data Memory and t he Program Memory space. In
addition, the ATmega162 features an EE PROM Memory for data storage. All three
memory spaces are linear and regul ar.
The ATmega162 contains 16K bytes On-chip In-System Reprogrammable Flash memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is
organized as 8K x 16. For software security, t he Flash Program memory space is
divided into two sections, Boot Program section and Application Program section.
The Flash me mory has an endurance of at least 10 ,000 write/erase cycles. The
ATmega162 Program Counter (PC) is 13 bits wide, thus addressing the 8K program
memory locations. The operation of Boot Program section and associated Boot Lock
bits for software protection are described in detail in “Boot Loader Support – ReadWhile-Write Self-pro gramming” on page 216. “Memory Programming” on page 230 contains a detailed description on Flash dat a serial download ing using the S PI pins or the
JTAG interface.
Constant tables can be allocated within the entire program memory address space (s ee
the LPM – Load Program Memory instruction description) .
Timing diagrams for instruction fetch and execution are presented in “Instruction Execution Timing” on page 12.
Figure 8. Program Memory Map
(1)
Program Memory
Application Flash Section
0x0000
2513E–AVR–09/03
Boot Flash Section
0x1FFF
Note:1. The address reflects word addresses.
15
SRAM Data MemoryFigure 9 shows how the ATm ega162 SRAM Mem ory is o rganized. Memory configura-
tion B refers to the ATmega161 compatibility mode, conf iguration A to the noncompatible mode.
The ATmega162 is a complex microcontroller with more peripheral units than can be
supported within the 64 l ocat ion res erv ed in the Opc ode for t he IN and OUT instru ctions .
For the Extended I/O space from 0x6 0 - 0xFF in SRAM, only the ST/STS/ST D and
LD/LDS/LDD instructions can be used. The Extende d I/O space does not exist when the
ATmega162 is in the ATmega161 compatibility m ode.
In Normal mode, t he first 1280 Data M emory locations a ddress bot h the Re gister File,
the I/O Memory, Extended I/O Memory, and the i nternal data SRAM. Th e first 32 locations address the Register File, the next 64 location the standard I/O memory, then 160
locations of Extended I/O memory, and the next 1024 locations address the internal
data SRAM.
In ATmega161 compatibility mode, the lower 1120 Data Memory locations address the
Register File , the I/O Mem ory, and t he internal da ta SRAM. T he first 96 lo cations
address the Register File and I/O Memory, and the next 1024 locations address the
internal data SRAM.
An optional external data SRAM can be used with the ATmega162. This SRAM will
occupy an area in the rem aining address locations in the 64K address space. This area
starts at the address following the internal SRAM. The Register File, I/O, Extended I/O
and Internal SRAM uses the o ccupies the l owest 1280 bytes in N ormal mode, and the
lowest 1120 bytes in the ATmega161 compatibil ity mode (Extended I/O not present), so
when using 64KB (65,536 bytes) of External Memory, 64,256 Bytes of External Memory
are available in Normal mode, and 64 ,416 Bytes in ATmega161 compat ibility mode. See
“External Memory Interface” on page 24 for details on how to take advantage of the
external memory map.
When the addresses accessing the SR AM memory space exceeds the internal data
memory locations, the external data SRAM is accessed using the same instructions as
for the internal data memo ry access. When the internal data memori es are accessed,
the read and write strobe pins (PD7 and PD6) are inactive during the whole access
cycle. External SRAM operation is enabled by setting the SRE bit in the MCUCR
Register.
Accessing external SRAM takes one additional clock cycl e per byte compar ed to acce ss
of the internal SRAM. This means that the commands LD, ST, LD S, STS, LDD, STD,
PUSH, and POP take one additional clock cycle. If the Stack is placed in external
SRAM, interrupts, subrou tine cal ls and r eturn s take t hre e clock cy cles ext ra because t he
2-byte Program Counter is pushed and popped, and external memory access does not
take advantage of the internal pipeline memory access. When external SRAM interface
is used with wait-state, one-byte external access takes two, three, or four additional
clock cycles for one, two, and three wait-states respectively. Interrupt, subroutine calls
and returns will need five, seven, or nine clock cycles more than specified in the instruction set manual for one, two, and three wait -states.
The five dif ferent addressing modes for the data memory cover: Direct, Indirect with Displacement, 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 rea ches the entire data space.
The Indirect with Displacement mode reaches 63 address locations from the base
address given by the Y- or Z-register.
16
ATmega162/V
2513E–AVR–09/03
ATmega162/V
When using register indirect addressing modes with automatic pre-decrement and postincrement, the address regis ter s X, Y, and Z are decremented or incremented.
The 32 general purpose working registers, 64 (+160) I/O Registers, and the 1024 bytes
of internal data SRAM in the ATmega162 are al l accessibl e through all thes e addressi ng
modes. The Register File is described in “General Purpose Register File” on page 10.
Figure 9. Data Memory Map
Memory configuration A
Data Memory
32 Registers
64 I/O Registers
160 Ext I/O Reg.
Internal SRAM
(1024 x 8)
External SRAM
(0 - 64K x 8)
0x0000 - 0x001F
0x0020 - 0x005F
0x0060 - 0x00FF
0x0100
0x04FF
0x0500
0xFFFF
Memory configuration B
Data Memory
32 Registers
64 I/O Registers
Internal SRAM
(1024 x 8)
External SRAM
(0 - 64K x 8)
0x0000 - 0x001F
0x0020 - 0x005F
0x0060
0x045F
0x0460
0xFFFF
Data Memory Access TimesThis section describes the general access timing concepts for int ernal memory access.
The internal data SRAM access is perf ormed in two clk
cycles as described in Figure
CPU
10.
2513E–AVR–09/03
Figure 10. On-chip Data SRAM Access Cycles
T1T2T3
clk
CPU
Address
Data
WR
Data
RD
Compute Address
Memory Access Instruction
Address valid
Write
Read
Next Instruction
17
EEPROM Data MemoryThe ATmega162 contains 512 bytes of data EEPROM memory. It is organize d as a sep-
arate data space, in which single bytes can be read and written. The EEPROM has an
enduranc e of at lea st 100, 000 write /erase cycle s. The acc ess be tween th e EEPR OM
and the CPU is described in the following, specifying the EEPROM Address Registers,
the EEPROM Data Register, and the EEPROM Control Register.
“Memory Programming” on page 230 contains a detailed description on EEPROM Programming in SPI, JTAG, or Parallel Programming mode.
EEPROM Read/Write AccessThe EEPROM Access Registers are accessible in the I/O space.
The write access time for the EEPROM i s given in Table 1. A selftiming function, however, lets the us er softw are detec t wh en the n ext b yte can be written. If the u ser code
contains instructions that write the EEPROM, some precautions must be taken. In
heavily filtered power supplies, V
causes the device for some period of time to run at a voltage lower than specified as
minimum for the clock frequency used. See “Preventing EEPROM Corruption” on page
22 for details on how to avoid problems in these situations.
In order to prevent unintenti onal EEPROM writes, a specific wr ite pro cedure must be f ollowed. Refer to the description of the EEPROM Control Register for details on this.
When the EEPROM is read, the CPU i s halted for four clock cycles before the next
instruction is execut ed. Wh en the E EPRO M is w ritten, the CPU is h alted fo r two cl ock
cycles before the next instr u ction is executed.
is likely to rise or fal l slowly on Power-up/down. This
CC
The EEPROM Address
Register – EEARH and EEARL
Bit151413121110 9 8
–––––––EEAR8EEARH
EEAR7EEAR6EEAR5EEAR4EEAR3EEAR2EEAR1EEAR0EEARL
76543210
Read/WriteRRRRRRRR/W
R/WR/WR/WR/WR/WR/WR/WR/W
Initial Value0000000X
XXXXXXXX
• Bits 15..9 – Res: Reserved Bits
These bits are reserved bits in the ATmega162 and will always read as zero.
• Bits 8..0 – EEAR8..0: EEPROM Address
The EEPROM Address Registers – EEARH and EEARL specify the EEPROM address
in the 512 bytes E EPROM space. The E EPROM da ta bytes are addressed li nearly
between 0 and 511. The initi al value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed.
For the EEPROM write operation, the EEDR Register contains the data to be written to
the EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by
EEAR.
Bit76543210
––––EERIEEEMWEEEWEEEREEECR
Read/WriteRRRRR/WR/WR/WR/W
Initial Valu e000000X0
• Bits 7..4 – Res: Reserved Bits
These bits are reserved bits in the ATmega162 and will always read as zero.
• Bit 3 – EERIE: EEPROM Ready Interrupt Enable
Writing EERIE to one enables the EEPROM Ready Interrupt if the I bit in SREG is set.
Writing EERIE to zero disables the interrupt. The EEPROM Ready interrupt generate s a
constant interrupt when EEWE is cleared.
• Bit 2 – EEMWE: EEPROM Master Write Enable
The EEMWE bit determines wh ether setting E EWE to one causes the EEP ROM to be
written. When EEMWE is set, setting EEWE within four clock cyc les will write data to the
EEPROM at the selected address. If EEMWE is zero, setting EEWE will have no effect.
When EEMWE has been written to one by software, hardware cl ears the bit to zero after
four clock cycles. See the description of the EEWE bit for an EEPROM write procedure.
• Bit 1 – EEWE: EEPROM Write Enable
The EEPROM Write Enable signal EEW E 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, otherwise 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 cloc k cycles after setting EEMWE, write a logical one to EEWE.
The EEPROM can not be progra mmed du ring a CPU write to the Flash me mory. 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 al lowing
the CPU to program the F lash. If the F lash is never being u pdated by the CPU, st ep 2
2513E–AVR–09/03
19
can be omitted. See “Bo ot Loader Sup port – Read-W hile-Write Sel f-programmi ng” on
page 216 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 th e inte rrupted E EPROM acce ss to fa il. It is recom mended to ha ve
the Global Interrupt Flag cleared during all the steps to avoid these pro blems.
When the write access time has elapsed, the EEWE bit is cleared by hardware. The
user software 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 n ext instruction is
executed.
• Bit 0 – EERE: EEPROM Read Enable
The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When the
correct 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 be fore st artin g the read oper ation. If a wri te opera tion
is in progress, it is neither pos sible to read the EEPRO M, nor to change the EEAR
Register.
The calibrated Oscil lator is used to t ime the EEPROM accesses. Table 1 lists the typical
programming time for EEPROM access from the CPU.
Table 1. E EPROM Programming Time
Number of Calibrated RC
Symbol
EEPROM write (from CPU)84488.5 ms
Note:1. Uses 1 MHz clock, independent of CKSEL Fuse settings
Oscillator Cycles
(1)
Typ Programming Time
20
ATmega162/V
2513E–AVR–09/03
ATmega162/V
The following code examples show one assembl y and one C function for writing to t he
EEPROM. The examples assume that interrupts are controlled (e.g., by disabling interrupts globally) so that no inte rrupts w ill occur d uring execut ion of t hese functions. T he
examples 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:
; Wait for completion of previous write
sbic EECR,EEWE
rjmp EEPROM_write
; Set up address (r18:r17) in address register
out EEARH, r18
out EEARL, r17
; Write data (r16) to data register
out EEDR,r16
; Write logical one to EEMWE
sbi EECR,EEMW E
; Start eeprom wri te by setting EEWE
sbi EECR,EEWE
ret
C Code Example
void EEPROM_write(uns igned 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);
}
2513E–AVR–09/03
21
The next code examples show assembly and C functions for reading the EEPROM. The
examples assume that interru pts are controlled so that no interrupts will occur during
execution of these functions.
Assembly Code Example
EEPROM_read:
; Wait for completion of previous write
sbic EECR,EEWE
rjmp EEPROM_read
; Set up address (r18:r17) in address register
out EEARH, r18
out EEARL, r17
; 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 reg ister */
EEAR = uiAddress;
/* Start eeprom read by writing EERE */
EECR |= (1<<EERE);
/* Return data from data register */
return EEDR;
}
EEPROM Write During Power down Sleep Mode
Preventing EEPROM
Corruption
22
ATmega162/V
When entering Power-down sleep mode whi le an EEPROM write opera tion i s activ e, the
EEPROM write o peration w ill contin ue, and w ill compl ete before the w rite access time
has passed. H owev er, wh en the write opera tion is comp lete, the O scillato r co ntinues
running, and as a consequence, the device does not enter Power-down entirely. It is
therefore recommended to verify that the EEPROM wri te operation is completed before
entering Power-down.
During periods of low V
the EEPROM data can be corrupted because the suppl y volt-
CC,
age is too low for t he 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 wh en the voltage is too
low. First, a regular write sequence to t he EEPROM requires a minimum volt age to
operate correctly. Second ly, the CPU itself can execute ins tructions incorrectly , if the
supply voltage is too low.
EEPROM da ta corruption can easily be avoided by fol lowing this design
recommendation:
2513E–AVR–09/03
ATmega162/V
Keep the AVR RESET ac tive (low) during periods of insuf ficient power supp ly voltage.
This can be do ne by enab ling the i nternal B rown- out Detect or (BOD). If the de tection
level of the internal BOD does not match the needed detection level, an external low
Reset Protection circuit can be used. If a Reset occurs while a write operation is in
V
CC
progress, the write oper ation will be compl et ed provide d that the power supply voltage i s
sufficient.
I/O MemoryThe I/O spac e definiti on of the A Tmega 162 is sh own in “ Regis ter Summa ry” on page
303.
All ATmega162 I/Os and peripherals are placed in the I/O space. All I/O locations may
be accessed by the LD/LDS/LDD and ST/STS/STD instructions, transf erring data
between the 32 general purpose working registers and the I/O space. I/O Registers
within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI
instructions. In these registers, the value of single bits can be checked by usi ng the
SBIS and SBIC instructions. Refer to the instruction set section for more details. When
using the I/O specific commands IN and OUT, t he I/O addresses 0x00 - 0 x3F must be
used. When addressing I/O Registers as data space using LD and ST instructions, 0x20
must be added to these addresses. The ATm ega162 is a complex microcontroller with
more peripheral units than can be supported within the 64 location reserved in Opcode
for the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM,
only the ST/STS/STD and LD/LDS/LDD instructions can be used. The Extended I/ O
space is replaced with SRAM locations when the ATmega162 i s in the ATmega161
compatibility mode.
For compatibility wit h future devices, reserved bits should be written to zero if accessed.
Reserved I/O memory addresses should never be written.
Some of the Status Flags are cleared by writi ng a logical one to them. Note that the CBI
and SBI instructions will operate on all bits in the I/O Register, writing a one back into
any flag read as set, thus clearing the flag. The CBI and SBI instructions work with registers 0x00 to 0x1F only.
The I/O and peripherals control registers are explained in later sections.
2513E–AVR–09/03
23
External Memory
Interface
With all the features the External Memory Interface provides, it is well suited to operate
as an interface to memory devices such as external SRAM and FLASH, and periphe rals
such as LCD-display, A/D, and D/A. The main features are:
Four Different Wait-state Settings (Including No Wait-state)
•
• Independent Wait-state Setting for Different External Memory Sectors (C onfigurable
Sector Size)
• The Number of Bits Dedicated to Address High Byte is Selectable
• Bus Keepers on Data Lines to Minimize Current Consumption (Optional)
OverviewWhen the eXternal MEMory (XMEM) is enabled, address space outside the internal
SRAM becomes availab le us ing the de dicated exte rnal mem ory pi ns (see Figure 1 o n
page 2, Table 29 on page 69, Table 35 on page 74, and Table 41 on page 80). The
memory configuration is shown in Figure 11.
Figure 11. External Memory with Sector Select
0x0000
Internal Memory
Using the External Memory
Interface
0x04FF/0x045F
Lower Sector
SRW01
SRW00
External Memory
(0-64K x 8)
Note:1. Address depends on the ATmega161 compatibility Fuse. See “SRAM Data Memory”
on page 16 and Figure 9 on page 17 for details.
Upper Sector
SRW11
SRW10
0x0500/0x0460
SRL[2..0]
0xFFFF
(1)
(1)
The interface consists of:
•AD7:0: Multiple xed low-order address bus and data bus
•A15:8: High-order address bus (configurable number of bits)
•ALE: Address latch enable
•RD
•WR
: Read strobe.
: Write strobe.
24
ATmega162/V
2513E–AVR–09/03
ATmega162/V
The control bits for the External Memory Interface are located in three registers, the
MCU Control Register – MCUCR, the Extended MCU Control Register – EMCUCR, and
the Special Function IO Register – SFIOR.
When the XMEM int erface is ena bled, it will ove rride the setting s in the Data Direction
registers corr esponding to the po rt s dedicat ed to t he i nterfa ce. For de tail s about t his port
override, see the alternate functions in section “I/O-Ports” on page 62. The XMEM interface will autodetect whether an access is internal or external. If the access is ext ernal,
the XMEM interface will output address, da ta, and the control signals on the ports
according to Figure 13 (this figure shows the wave forms without wait-states). When
ALE goes from high to low, there is a valid address on AD7:0. ALE is low during a data
transfer. When the XM EM interface is enabled, also an internal access will cause activity on address-, data- and ALE ports, but the RD
internal access. When the External Memory Interface is disabled, the normal pin and
data direction settings are used. Note that when the XMEM interface is disabled, the
address space above the internal SRAM boundary is not mapped into the internal
SRAM. Figure 12 illustrat es how to conn ect an ext ern al SRAM to th e AVR using an oc tal
latch (typically “74x573” or equivalent) which is transparent when G is high.
Address Latch RequirementsDue to the high-sp eed operat ion of the XRAM interf ace, the add ress latch m ust be
selected with care for syste m frequencies abo ve 8 MHz @ 4V and 4 MHz @ 2.7V.
When operating a t conditions above these frequencies, the typical old style 74HC series
latch becomes inadequate. The external memory interface is designed in compliance to
the 74AHC series l atch. How ever, m ost latch es can b e used a s long they com ply w ith
the main timing parameters. The main para meters for the address latch are:
•D to Q propagation delay (t
•Data setup time before G low (t
•Data (address) hold time after G low (
).
pd
).
su
th
The external memory interface is desi gned to guaran ty minimum address hol d time afte r
G is asserted low of t
= 5 ns (refer to t
h
LAXX_LD/tLLAXX_ST
page 271). The D to Q pro pagat ion delay (t
calculating the access time requirement of the external component. The data setup time
before G low (t
) must not exceed address valid to ALE low (t
su
delay (dependent on the capaciti ve load).
and WR strobes will not toggle during
).
in Table 115 to Table 122 on
) must be taken into considera tion when
pd
) minus PCB wiring
AVLLC
2513E–AVR–09/03
Figure 12. External SRAM Connected to the AVR
AD7:0
ALE
DQ
G
AVR
A15:8
RD
WR
D[7:0]
A[7:0]
SRAM
A[15:8]
RD
WR
25
Pull-up and Bus KeeperThe pull-up resistors on th e AD7:0 port s may be acti vated if the corresponding Port reg-
ister is written to one. To reduce power consumption in sleep mode, it is recommended
to disable the pull-ups by writing the Port register to zero before entering sleep.
The XMEM interface also provides a bus keeper on the AD7:0 lines. The Bus Keeper
can be disabled and enabl ed in soft ware as desc ribed i n “Speci al Funct ion IO Regi ster –
SFIOR” on page 30. When enabled, the Bus Keeper will k e ep th e p re v io us value on the
AD7:0 bus while these lines are tri-stat ed by the XMEM interface.
TimingExternal memory devices have various timing requirements. To meet these require-
ments, the ATmega162 XMEM interface provides four different wait-states as shown in
Table 3. It is imp ortant to conside r the timing specific ation of the ex ternal me mory
device before selecting the wa it-state. The mo st important paramet ers are the access
time for the external memory in conjunction with the set-up requirement of the
ATmega162. Th e access time fo r the external me mory is defined to be the time from
receiving the chip select/address until the data of this address actually is driven on the
bus. The access time cannot exceed the time fr om the AL E pulse is asserted low until
data must be stable during a read sequence (t
LLRL
+ t
RLRH
- t
in Table 115 to Table
DVRH
122 on page 271). The diff erent wait-states are set up in software. As an additional feature, it is possible to divide the external memory space in two sectors with individual
wait-state settings. This makes it possible to connect two different memory devices with
different timing requireme nts to the s ame XM EM inte rface. For XM EM int erface timing
details, please refer to Figure 118 to Fi gure 121, and Table 115 to Table 122.
Note that the XMEM interface is asynchronous and that the waveforms in the figures
below are related to the internal system clock. The skew between the internal and external clock (XTAL1) is not gu aranteed ( it var ies bet ween devices , temperat ure, and suppl y
voltage). Consequently, the XMEM interface is not suited for synchronous operation.
Figure 13. External Data Memory Cycles without Wait-state
Writing SRE to one enables the External Memory Interface.The pin functions AD7:0,
A15:8, ALE, WR
, and RD are activated as the alternate pin functions. The SRE bit overrides any pin direction settings in the respective Data Direction Registers. Writing SRE
to zero, disables the Ext ernal Me mo ry Interfac e and th e n ormal pin a nd data di rection
settings are used.
• Bit 6 – SRW10: Wait State Select Bit
For a detailed description, see common description for the SRWn bits below (EMCUCR
description).
• Bit 6..4 – SRL2, SRL1, SRL0: Wait State Sector Limit
28
It is possible to configure different wait-states for different external memory addresses.
The external memory address space can be divided in two sectors that have separate
wait-state bits. The SRL2, SRL1, and SRL0 bits select the splittin g of t hese sectors, see
Table 2 and Figure 11. By default, the SRL2, SRL1, and SRL0 bits are set to zero and
the entire external memory address space is treated as one sector. When the entire
ATmega162/V
2513E–AVR–09/03
ATmega162/V
SRAM address space is configured as one sector, the wait-states are configured by the
SRW11 and SRW10 bits.
Table 2. Sector Limits with Different Settings of SRL2. .0
• Bit 1 and Bit 6 MCUCR – SRW11, SRW10: Wait-state Select Bits for Upper
Sector
The SRW11 and SRW10 bits co ntrol the n umber of wait-stat es for the u pper s ector of
the external memory address space , see Tabl e 3.
2513E–AVR–09/03
• Bit 3..2 – SRW01, SRW00: Wait-state Select Bits for Lower Sector
The SRW01 and S RW00 b its co ntrol the num ber o f wai t-states f or the lower secto r of
the external memory address space , see Tabl e 3.
Table 3. Wait-states
SRWn1SRWn0Wait-states
00No wait-states
01Wait one cycle during read/write strobe
10Wait two cycles during read/write strobe
11
Note:1. n = 0 or 1 (lower/upper sector).
For further details of the timing and wait-state s of the External Memory Interf ace , see
Figure 13 to Figure 16 how the setting of the SRW bits affects the timing.
(1)
Wait two cycles during read/write and wait one cycle before driving out
new address
Writing XMBK to one enables the Bus Keeper on the AD7:0 line s. When the Bus Keeper
is enabled, AD7:0 will keep the last driven value on the lines even if the XMEM interface
has tri-stated the lines. Writing XMBK to zero disables the Bus Keeper. XMBK is not
qualified with SRE, so even if the XMEM interface is disabled, the bus keepers are still
activated as long as XMBK is one.
• Bit 6..3 – XMM2, XMM1, XMM0: External Memory High Mask
When the External Memory is enabled, all Port C pins are used for the high address
byte by default. If the full 60KB address space is not required to access the external
memory, some, or all, Port C pins can be released for normal Port Pin function as
described in Table 4. As described in “Using all 64KB Locations of External Memory” on
page 32, it is possible to use the XMMn bits to access all 64KB locations of the external
memory.
Table 4. Port C Pins Released as Normal Port Pins when the External Memory is
Enabled
XMM2XMM1XMM0# Bits for External Memory AddressReleased Port Pins
0008 (Full 60 KB space)None
Using all Locations of
External Memory Small er than
64 KB
0017PC7
0106PC7 - PC6
0115PC7 - PC5
1004PC7 - PC4
1013PC7 - PC3
1102PC7 - PC2
111No Address high bitsFull Port C
Since the external memory is mapped after the internal memory as shown in Figure 11,
the external memory is not addressed when addressing the first 1,280 bytes of data
space. It may appear that the first 1, 280 bytes of the external memory are inaccessible
(external memory addresses 0x0000 to 0x04FF). However, when connecting an external memory smaller than 64 KB, for exampl e 32 KB, these lo cations are easily acces sed
simply by addressing from address 0x80 00 to 0x84FF. Sinc e the External Memory
Address bit A15 is not connected to the external memory, addresses 0x8000 to 0x84FF
will appear as addresses 0x0 000 to 0x04FF for the external memory. Addressing above
address 0x84FF is not recommended, since this will address an external memory location that is already accessed by anoth er (lower) address. To the Ap plication softw are,
the external 32 KB memory will appear as one linear 32 KB address space from 0x0500
to 0x84FF. Thi s is illustrated in Figure 17. Memory conf iguration B refers to the
ATmega161 compatibility mode, configuration A to the non-compatible mode.
30
ATmega162/V
2513E–AVR–09/03
When the device is set in ATmega161 compatibility mode, the int ernal address space is
1,120 bytes. This implies that the first 1,120 bytes of the external memory can be
accessed at addresses 0x8000 to 0x845F. To the Application software, the external 32
KB memory will appear as one linear 32 KB address space from 0x046 0 to 0x845F.
Figure 17. Address Map with 32 KB External Memory
Memory Configuration A
AVR Memory Map
0x0000
Internal Memory
0x04FF
0x0500
External 32K SRAM
0x0000
0x04FF
0x0500
0x0000
0x045F
0x0460
Memory Configuration B
AVR Memory Map
Internal Memory
ATmega162/V
External 32K SRAM
0x0000
0x045F
0x0460
0x7FFF
0x8000
0x84FF
0x8500
0xFFFF
External
Memory
(Unused)
0x7FFF
0x7FFF
0x8000
0x845F
0x8460
0xFFFF
External
Memory
(Unused)
0x7FFF
2513E–AVR–09/03
31
Using all 64KB Locations of
External Memory
Since the external memory is mapped after the internal memory as shown in Figure 11,
only 64,256 Bytes of external memory are availa ble by default (address space 0x0000
to 0x05FF is reserved for internal memory). However, it is possible to take adv antage of
the entire external memory by masking the higher address bits to zero. This can be
done by using the XMMn bits and control by software the most signifi cant bits of the
address. By setting Port C to ou tput 0x00, and releasing the most significant bits for normal Port Pin operation, the Memory Interface will address 0x0000 - 0x1FFF. See code
example below.
Assembly Code Example
; OFFSET is defined to 0x2000 to ensure
; external memory access
; Configure Port C (address high byte) to
; output 0x00 when the pins are released
; for normal Port Pin operation
Note:1. The example code assumes that the part specific header file is included.
Care must be exercised using this option as most of the memory is masked away.
ATmega162/V
2513E–AVR–09/03
System Clock and
Clock Options
ATmega162/V
Clock Systems and their
Distribution
Figure 18 presen ts the princip al clo ck system s in the AV R and the ir distributi on. All of
the clocks need not be active at a given time. In order to redu ce power consump tion, the
clocks to modules not being used can be halted by using different sleep modes, as
described in “Power Management and Sleep Modes” on page 41. The clock systems
are detailed below.
Figure 18. Clock Distribution
Asynchronous
Timer/Counter
General I/O
Modules
clk
clk
ASY
CPU CoreRAM
I/O
AVR Clock
Control Unit
Source clock
Clock
Multiplexer
clk
CPU
clk
FLASH
Reset Logic
Watchdog Timer
Watchdog clock
Watchdog
Oscillator
Flash and
EEPROM
CPU clock – clk
I/O clock – cl k
Flash clock – clk
CPU
I/O
FLASH
Asynchronous Timer c lock –
clk
ASY
2513E–AVR–09/03
Timer/Counter
Oscillator
External Clock
Crystal
Oscillator
Low-frequency
Crystal Oscillator
Calibrated RC
Oscillator
The CPU clock is routed to parts of the system concerned with operation of the AVR
core. Examples of such module s are the General Purpose Reg ister File, the Stat us Register and the data memory holding the Stack Pointer. Halting the CPU clock inhibits the
core from performing general operations and calculations.
The I/O clock is used by the majority of the I/O modules, like Timer/Counters, SPI, and
USART. The I/O clock is also used by the External Interrupt module, but note that some
external inter rupts are d etected by as ynchrono us logic, al lowing suc h interrup ts to be
detected even if the I/O clock is halted.
The Flash clock controls operat ion of the Flash interface. The Flash clock is usually
active simultaneously with th e CPU clock.
The Asynchronous Timer cl ock allo ws the A synchronous Tim er/Counter t o be c locked
directly from an external 32 kHz clock crystal. The dedicated clock domain allows using
this Timer/Counter as a realtime counter even when the device is in sleep mode.
33
Clock SourcesThe 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 A VR cl ock gene rator,
and routed to the appropriate module s.
Note:For all fuses “1” means unprogrammed while “0” means programmed.
The various choices for each clocki ng optio n is given i n the followi ng secti ons. When the
CPU wakes up from Power-down or Power-save, the selected clock source is used to
time the start-up, ens uring st able Osci llat or operat ion bef ore i nstruc tion exe cution s tarts .
When the CPU starts from Reset, there is an additional delay allowing the power to
reach a stable level before com mencing norm al operation. The W atchdog Oscil lator is
used for tim ing th is realtim e par t of the s tart-up time. T he numbe r of WDT Oscilla tor
cycles used for each Time-out is shown in Table 6. The frequency of the Watchdog
Oscillator is voltage depe ndent as show n in “ATmega162 Typical Charac teristics” on
page 274.
Table 6. Number of Watchdog Oscillator Cycles
Typ Time-out (VCC = 5.0V)Typ Time-out (VCC = 3.0V)Number of Cycles
4.1 ms4.3 ms4K (4,096)
65 ms69 ms64K (65,536)
Default Clock SourceThe device is shipped with CKSEL = “0010”, SUT = “10” and CKDIV8 programmed. The
default clock so urce setti ng is t herefore the I nternal R C Os cillato r with longest startup
time and an initial system clock prescaling of 8. This default setting ensures that all
users can make their desired clock source setting usi ng an In-System or Parallel
programmer.
Crystal OscillatorXTAL1 and XTAL2 are input and output , respectively, of an invert ing amplifier which can
be configured for use as an On-chip Osc illator, as shown i n F igure 19. Either a quartz
crystal or a ceramic resonator may be used.
C1 and C2 should always be equal for both crystals and resonators. The optimal value
of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. Some initial guidelines for
choosing capacitors for use with crystals are given in Table 7. For ceramic resonators,
the capacitor values given by the manufacturer should be used.
34
ATmega162/V
2513E–AVR–09/03
Figure 19. Crystal Oscillator Connections
ATmega162/V
C2
C1
XTAL2
XTAL1
GND
The Oscillator can operate in four different modes, each optimized for a specific frequency range. The operating mode is selected by the fuses CKSEL3:1 as shown in
Table 7.
Note:1. This option should not be used with crystals, only with ceramic resonators.
(MHz)
0.4 - 0.9–
Recommended Range for Capacito rs C1 and
C2 for Use with Crystals (pF)
The CKSEL0 Fuse together with the SUT1..0 Fuses select the start-up times as shown
in Table 8.
Table 8. Start-up Times for the Crystal Oscillator Clock Selection
Start-up Time from
Power-down and
CKSEL0SUT1:0
000258 CK
001258 CK
0101K CK
0111K CK
1001K CK
10116K CK–Crystal Oscillator,
11016K CK4.1 msCrystal Oscillator,
11116K CK65 msCrystal Oscillator,
Power-save
(1)
(1)
(2)
(2)
(2)
Additional Delay from
Reset (VCC = 5.0V)
4.1 msCeramic resonator,
65 msCeramic resonator,
–Ceramic resonator ,
4.1 msCeramic resonator,
65 msCeramic resonator,
Recommended
Usage
fast rising power
slowly rising power
BOD enabled
fast rising power
slowly rising power
BOD enabled
fast rising power
slowly rising power
2513E–AVR–09/03
35
Notes: 1. These options should only be used when not operating cl ose to the maximum fre-
quency 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 frequency of the device, and if frequency stability at start-up is
not important for the application.
Low-frequency Crystal
Oscillator
To use a 32.7 68 kHz watch crystal as the c lock source for the device , the Low -frequency Crystal Oscillator must be selected by setting the CKSEL Fuses to “0100”,
“0101”, “0110” or “0111”. The crystal should be connected as shown in Figure 19. If
CKSEL equals “0110” or “0111”, the internal capacitors on XTAL1 and XTAL2 are
enabled, thereby removing the need for external capacitors. The internal capacitors
have a nominal val ue of 10 pF.
When this Oscillator is selected, start-up times are determined by the SUT Fuses (real
time-out from Reset) and CKSEL0 (number of clock cycles) as shown in Table 9 and
Table 10.
Table 9. S tart-up Delay from Reset when Low-frequency Crystal Oscillator is Selected
SUT1:0Additional Delay from Reset (VCC = 5.0V)Recommended Usage
000 msFast rising power or BOD enabled
014.1 msFast rising power or BOD enabled
1065 msSlowly rising power
11Reserved
Table 10. Start-up Times for the Low-frequency Crystal Oscillator Clock Selec ti on
Start-up Time fro m
Internal Capaci tors
CKSEL1:0
(1)
00
01No32K CKStable Frequency at start-up
(1)
10
11Yes32K CKStable Frequency at start-up
Enabled?
No1K CK
Yes1K CK
Power-down and
Power-saveRecommended Usage
Calibrated Internal RC
Oscillator
36
ATmega162/V
Note:1. These options should only be used if frequency stability at star t-up is not important
for the applicati on.
The calibrated internal R C Oscillator provides a f ixed 8.0 MH z clock. T he frequ ency is
nominal value at 3V and 25°C. If 8.0 MHz frequency exceed the specification of the
device (depends on V
), the CKDIV8 Fuse must be programmed in order to divide th e
CC
internal frequency by 8 during start-up. See “System Clock Prescaler” on page 39 for
more details. This cloc k may be selected as the syste m clock by program ming the
CKSEL Fuses as shown in Table 11. If selected, it will operat e with no external components. During Reset, hardware loads the calibrat ion byte into the OSCCAL Register and
thereby automaticall y calibrates the RC Oscil lat or. At 3V and 25°C, this calibration gives
a frequency within ± 1% o f the no minal frequ ency. Whe n this O scillator is used as t he
chip clock, the Watchdog Oscillator will still be used for the Watchdog Timer and for the
2513E–AVR–09/03
ATmega162/V
Reset Time-out. For more information on the pre-programmed calibration value, see the
section “Calibration Byte” on page 233.
Note:1. The device is shipped with this option selected.
When this Oscilla tor is sele cted, sta rt-up times are determ ined by the SUT Fuse s as
shown in Table 12. XTAL1 and XTAL2 should be left unconnected (NC).
Table 12. Start-up Times for the Internal Cali brated RC Oscillator Clock Selection
8.0 MHz
Oscillator Calibrat ion Register
– OSCCAL
Start-up Time from Power-
SUT1:0
006 CK–BOD enabled
016 CK4.1 msFast rising power
(1)
10
11Reserved
Note:1. The device is shipped with this option selected.
Bit76543210
Read/WriteRR/WR/WR/WR/WR/WR/WR/W
Initial Value0Device Specific Calibration Value
down and Power-save
6 CK65 msSlowly rising power
–CAL6CAL5CAL4CAL3CAL2CAL1CAL0OSCCAL
Additional Delay from
Reset (VCC = 5.0V)Recommended Usage
• Bit 7 – Res: Reserved Bit
This bit is reserved bit in the ATmega162, and will always read as zer o.
• Bits 6..0 – CAL6..0: Oscillator Calibration Value
Writing the calibration byte to this address will trim the Internal Oscillator to remove process variations from the Oscillator frequency. This is done automatically during Chip
Reset. When OSCCAL is zero, the lowest avai lable frequency is chosen. Writing nonzero values to this register will increase the frequency of the Internal Oscillator. Writing
0x7F to the register gives the hi ghest availab le frequency . The calibrated Os cillator is
used to time EEPRO M and Fla sh acc ess. If EEPRO M or Flas h is writt en, do no t calibrate to more than 10% above the nominal fre quency. Ot herwise, th e EEPROM or Flash
write may fail.
2513E–AVR–09/03
37
Table 13. Internal RC Oscillator Frequency Range.
Min Frequency in Percentage of
OSCCAL Value
0x0050%100%
0x3F75%150%
0x7F100%200%
Nominal Frequency
Max Frequency in Percentage of
Nominal Frequency
External ClockTo drive the device from an external clock source, XTAL1 should be driven as shown in
Figure 20. To run the de vice on an exte rnal clock, the CK SEL Fuses must be programmed to “0000”.
Figure 20. External Clock Drive Configuration
EXTERNAL
CLOCK
SIGNAL
When this clock source is select ed, start-up times are determined by the SUT Fuses as
shown in Table 14.
Table 14. St art-up Times for the External Clock Selection
Start-up Time from
Power-down and
SUT1..0
006 CK–BOD enabled
016 CK4.1 msFast rising power
106 CK65 msSlowly rising power
11Reserved
Power-save
Additional Delay from
Reset (VCC = 5.0V)Recommended Usage
When applying an external clock, it is required to avoid sudden changes in the applied
clock frequency to ensure stable operation of the MCU. A variation in frequency of more
than 2% from one clock cycle to the next can lead to unpredictable behavior. It is
required to ensure that the MCU i s kept in reset during such changes in the clock
frequency.
Note that the Sy stem Cl ock Presc aler can be us ed to imp lement ru n-time changes of
the internal clock f requency while still ensuring stable operation. Refer to “System Clock
Prescaler” on page 39 for details.
Clock outpu t bufferWhen the CKOUT Fuse is programmed , the system clock will be output on Port B 0. This
mode is suitable when ch ip clock is used to driv e other circuits on the system. The clock
38
ATmega162/V
2513E–AVR–09/03
ATmega162/V
will be output also during Rese t and the normal ope ration of PortB will be overridden
when the fuse is programmed. Any clock sources, including Internal RC Oscillator, can
be selected when PortB 0 serves as clock output .
If the system clock prescaler is used, it is the divided system clock that is output when
the CKOUT Fuse is program med. See “System Clock Pre scaler” on page 39. for a
description of the sys tem cl ock prescaler.
Timer/Counter OscillatorFor AVR microcontrollers with Timer/Counter Oscillator pins (TOSC1 and TOSC2), the
crystal is connected directly be tween the pi ns. The O scillator pr ovides internal ca pacitors on TOSC1 and TOSC2, thereby removing the need for external capacitors. The
internal capacitors have a nomin al value of 10 pF. The Oscillator is optimize d for u se
with a 32.768 kHz watch crystal. Applying an external clock source to TOSC1 is not
recommended.
System Clock PrescalerThe ATmega162 system clock can be divided by setting the Clock Prescale Register –
CLKPR. This feature can be used to decrease power consumption when the requirement for processing power is low. This can be used w ith all clock source options, and it
will affect the clock frequency of the CPU and all synchr onous peripherals. clk
and clk
of clk
are divided by a factor as shown in Table 15. Note t hat t he clock frequency
FLASH
(asynchronously Timer/Counter) only will be scaled if the Timer/Counter is
ASY
clocked synchronousl y.
I/O
, clk
CPU
,
Clock Prescale Register –
CLKPR
Bit76543210
CLKPCE–––CLKPS3CLKPS2CLKPS1CLKPS0CLKPR
Read/WriteR/WRRRR/WR/WR/WR/W
Initial Value0000See Bit Descript ion
• Bit 7 – CLKPCE: Cl ock Prescaler Change Enable
The CLKPCE bit must be written to logic one to enable change of the CLKPS bits. CLKPCE is cleared by hardware four cycles after it is written or when CLKPS is written.
Setting the C LKPC E bit will disa ble interru pts, as expl ained in the CLKPS de scription
below.
These bits define the division factor between the selected clock source and the internal
system clock. These bits can be written run-time to vary the clock frequency to suit the
application requirements. As the divider divides the master cl ock input to the MCU, the
speed of all synchronous peripherals is reduced when a division factor is used. The division factors are given in Table 15.
To avoid uni ntenti onal ch ang es of c lock freque ncy, a spec ial wr ite pr ocedure must be
followed to change the CLKPS bits:
1. Write the Clock Prescaler Change Enable (CLKPCE) bit to one and all other bits
in CLKPR to zero.
2. Within four cycles, write the desired value to CLKPS while writing a zero to
CLKPCE.
2513E–AVR–09/03
Caution: An interrupt between step 1 and step 2 will make the timed sequence fail. It is
recommended to have the Global Interrupt Flag cleared during these steps to avoid this
problem.
39
The CKDIV8 Fu se determi nes the initia l value of the CLK PS bits. If CKDIV8 is unp rogrammed, the CLKPS bits will be reset to “0000”. If CKDIV8 is programmed , CLKPS bits
are reset to “ 0011”, giving a division factor of 8 at start up. This feature should be used if
the selected c lock sou rce has a highe r frequen cy tha n the maxi mum freq uency of the
device at the present operating conditions. Note that any value can be written to the
CLKPS bits reg ardless of the CKD IV8 Fuse setting. T he Applic ation softwa re must
ensure that a sufficient division f acto r is chosen if th e selected clock sourc e has a highe r
frequency than the maximum frequency of the device at the present operating conditions. The device is shipped with the CKDIV8 Fuse programmed.
Sleep modes enable the application to shut down unused modules in the MCU, thereby
saving power. The AVR provides various sleep modes allowing the user to tailor the
power consumption to the application’s requirements.
To enter any of the five sleep modes, the SE bit in MCUCR must be written to logic one
and a SLEEP instruction must be executed . The SM2 bit in MCUCSR, the SM1 bit in
MCUCR, and the S M0 bit i n the EM CUCR Register select w hich sle ep mode (Idle,
Power-down, Power-save, Sta ndby, or Extended Standby) will be activated by the
SLEEP instruction. See Table 16 for a summary. If an enabled interrupt occurs while the
MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in
addition to the start -up time, executes the interrupt routine, and res umes execution from
the instruction following SLEEP. The contents of the Register File and SRAM are unaltered when the dev ice w akes up from sle ep. If a Reset o ccurs duri ng sleep m ode, t he
MCU wakes up and executes from the Reset Vector.
Figure 18 on page 33 presents the different clock systems in the ATmega162, and their
distribution. The figure is helpful in selecting an approp riate sleep mode.
The SE bit must be written to lo gic one t o make the MCU enter the sle ep mode when the
SLEEP instruction is executed. To avoi d the MCU entering the sleep mode unl ess it is
the programmer’s purpose, it is recommended to write the Sleep Enable (SE) bit to one
just before the execution of the SLEEP instruction and to clear it immediately after waking up.
• Bit 4 – SM1: Sleep Mode Select Bit 1
The Sleep Mode Select bits select between the five available sleep modes as shown in
Table 16.
Note:1 . Standby mode and E xtended Standby mode are only available with external crystals
or resonators.
Idle ModeWhen the SM2..0 bit s are written to 000, the SLEE P instructi on makes the MCU enter
Idle mode, stopping the CPU but allowing the SPI, USART, A nalog Comparator,
Timer/Counters, Watchdog, and the interrupt system to continue operating. T his sleep
mode basically halts clk
CPU
and clk
, while allowing the other clocks to run.
FLASH
Idle mode enables the MCU to wake up from external triggered interrupts as well as
internal ones like the Timer Overflow and USART Transmit Complete interrupts. If
wake-up from the Analog 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 reduce power consumption in Idle mode.
Power-down ModeWhen the SM 2..0 bits are written to 010, the SLEE P instruction m akes the MCU enter
Power-down mode . In this m ode, the extern al Osci llator is stopp ed, whil e the e xternal
interrupts and the Watchdog continue operat ing (if enabled). Only an External Reset, a
Watchdog Res et, a Brow n-out Rese t, an E xtern al Lev el In terrupt on IN T0 or INT1, an
external interrupt on INT2, or a pin change interrupt can wake up t he MCU. Th is sleep
mode basically halts all generated clocks, allowing operation of asynchronous modules
only.
Note that if a level triggered interrupt is used for wake-up f rom Power-down mode, the
changed level must be held for some time to wake up the MCU. Refer to “External Interrupts” on page 83 for details.
42
When waking up from Power-down mode, there is a delay from the wake -up con dition
occurs until the wake-up becomes effective. This allows the clock to restart and become
stable after having been stopp ed. The wake-u p p eriod is defined b y th e same CKS EL
Fuses that define the Reset Time-out period, as described in “Clock Sources” on page
34.
ATmega162/V
2513E–AVR–09/03
ATmega162/V
Power-save ModeWhen the SM2. .0 bits are written t o 011, the S LEEP i nstruction m akes the M CU enter
Power-save mode. This mode is identical to Power-down, with one exception:
If Timer/Counter2 is clocked asynchronously, i.e., the AS2 bit in ASSR is set,
Timer/Counter2 will run during sleep. The device can wake up from either Timer Overflow or Output Compare event from Timer/Count er2 if the corresponding
Timer/Counter2 interrupt enable bits are set in TIMSK, and the Global Interrupt Enable
bit in SREG is s e t.
If the Asynchronous Tim er is NOT clocked asynchrono usly, P ower-dow n mod e is recommended instead of Power-save mode because the contents of the registers in the
Asynchronous Time r should be considered und efined aft er wake-up in P ower-save
mode if AS2 is 0.
This sleep mode basicall y halts all clocks except clk
, allowing operation only of asyn-
ASY
chronous modules, including Timer/Counter 2 if clocked asynchronously.
Standby ModeWhen the SM2..0 bits are 110 and an external crystal/resonator clock option is selected,
the SLEEP instruction ma kes the MCU enter Stan dby mode. This mode i s identical to
Power-down with the excep tion that the main Osci llator is kept runn ing. From St andby
mode, the device wakes up in six clock cycles.
Extended Standby ModeWhen the SM2..0 bits are 111 and an external crystal/resonator clock option is selected,
the SLEEP instruct ion makes the MCU enter Extended Standby mode. This mode is
identical to Power-save mode with the excepti on that the main Oscillator is kep t running .
From Extended Standby mode, the device wakes up in six clock cycles.
Table 17. Active Clock domains and Wake up sources in the different sleep modes
Active Clock domainsOscillatorsWake-up Sources
INT2
Main Clock
Sleep Modeclk
CPU
clk
FLASH
clkIOclk
Source Enabled
ASY
IdleXXXX
Timer Osc
Enabled
(2)
and Pin Change Timer2
Power-downX
Power-saveX
Standby
Extended Standby
(1)
(1)
(2)
XX
(2)
X
XX
(2)
X
(2)
Notes: 1. External Crystal or resonator selected as clock source
2. If AS2 bit in ASSR is set
3. For INT1 and INT0, only level inte rrupt
INT1
INT0
XXXX
(3)
(3)
X
(3)
(3)
X
(2)
X
(2)
X
SPM/
EEPROM
Ready
Other
I/O
2513E–AVR–09/03
43
Minimizing Power
Consumption
Analog ComparatorWhen entering Idle mode, the Analog Compa rator should be disabled if not needed. In
Brown-out DetectorIf the Brown-out Detector is not needed in the application, this module should be turned
Interna l Voltage Refe re n c eThe Internal Voltage Reference will be enabled when needed by the Brown-o ut Detector
There are several issues to consider when trying to minimize the power consumption in
an AVR controlled system. In general, sleep modes should be used as much as possible, and the slee p mode shoul d be se lected s o that as few a s p ossible of the devi ce’s
functions are op erating. A ll function s no t needed shoul d be d isabled. In part icular, the
following modules may need special consideration when trying to achieve the lowest
possible power consumption.
the other sleep modes, the Analog Comparator is automatically disabled. However, if
the Analog Comparator is set up to use the Int ernal Voltage Reference as i nput, the
Analog Comparator should be disabled in all sleep modes. Otherwise, the Internal Voltage Reference will be ena bled, independent of sleep mode. Refer to “Analog
Comparator” on page 194 for details on how to configure the Analog Comparator.
off. If the Brown-out Detector is enabled by the BODLEVEL Fuses, it will be enabled in
all sleep m odes, and h enc e, al ways consum e po wer. In t he d eeper slee p mo des, t his
will contribute significantly to the total current consumption. Refer to “Brown-out Detection” on page 49 for details on how to configure the Brown-out Detector.
or the Analog Co mp arator. If these modules are disab led as d escribed in the s ections
above, the internal voltage reference will be disabled and it will not b e consuming
power. When turned on again, the user must al low 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 t o “Internal Voltage Refer ence” on page 51 for details on the star t-up time.
Watchdog TimerIf the W atchdog Timer is not needed in the application, this module should be turned off.
If the Watchdog Timer is enab led, it will be ena bled in all sleep modes, and hence,
always consume power. In the deeper sleep mo des, this will contribute significant ly to
the total current consumption. Refer to “Watchdog Timer” on page 51 for details on how
to configure the Watchdog Timer.
Port PinsWhen entering a sleep mode, all port pins should be configured to use minimum power.
The most important thing is to ensure that no pins drive resistive loads. In sleep m odes
) is stopped, the input buffers of th e device will be disabled.
I/O
/2, the input buffer will use exces-
CC
JTAG Interface and
On-chip Debug System
where the I/O clock (clk
This ensures that no power is co nsumed b y the input logic w hen not needed . In som e
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 66 for
details on which pins are enabled. If the input buffer is enabl ed and the input signal is
left floating or have an analog signal level close to V
sive power.
If the On-chip debug system is enabled by the OCDEN Fuse and the chip enter Power
down or Power save sleep mode, the main clock source remains enabled. In these
sleep modes, this will contri bute significantly to the total current consumption. There are
three alternative ways to avoid this:
•Disable OCDEN Fuse.
•Disa ble JTAGE N F u se.
•Write one to the JTD bit in MCUCSR.
44
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
ATmega162/V
2513E–AVR–09/03
ATmega162/V
the logic level, power consumption will increa se. Note that the TDI p in for the next
device in the scan chain contains a pul l-up that avoids this problem. Writing the JTD bit
in the MCUCSR registe r to one or leaving the JTA G fuse un program med dis ables t he
JTAG interface.
2513E–AVR–09/03
45
System Control and
Reset
Resetting the AVRDuring Reset, all I/O Registers are set to their initial values, and the program starts exe-
cution from the Reset Vector. The i nstruction 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 21 shows the Reset Logic. Table 18 defines the electrical
parameters of the reset circui try.
The I/O ports of the AVR are immediately reset to their initial state when a reset source
goes active. Thi s 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 reac h a stable l evel before normal operation
starts. The Time-out period of the delay cou nter is defined by the user through the
CKSEL Fuses. The different selections for the delay period are presented in “Clock
Sources” on page 34.
Reset SourcesThe ATmega162 has five sources of reset:
•Power-on Reset. The MCU is reset when the supply v olt age is below the Power-on
Reset threshold (V
•External Reset. The MCU is reset when a low level is present on the RESET
longer than the minimum pulse length.
•Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and
the Watchdog is enabled.
•Brown-out Reset. The MCU is reset when the supply voltage V
Brown-out Reset threshol d (V
device is guara n teed to operate at maximum frequency for the V
V
. V
BOT
minimum V
must be set to the corresponding minimum voltage of the device (i .e.,
BOT
for ATmega162V is 1.8V).
BOT
•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 203 for details.
POT
).
pin for
is below the
) and the Brown-out Detector is enabled. The
BOT
CC
voltage down to
CC
46
ATmega162/V
2513E–AVR–09/03
Figure 21. Reset Logic
V
CC
BODLEVEL [ 2..0]
Pull-up Resistor
RESET
SPIKE
FILTER
Power-on
Reset Circuit
Brown-out
Reset Circuit
Reset Circuit
DATA BUS
MCU Control and Status
Register (MCUCSR)
JTRF
BORF
PORF
WDRF
EXTRF
ATmega162/V
JTAG Reset
Register
Watchdog
Timer
Watchdog
Oscillator
Clock
Generator
CKSEL[3:0]
SUT[1:0]
CK
COUNTER RESET
Delay Counters
TIMEOUT
Table 18. Reset Characteristics
SymbolParameterConditionMin.Typ.Max.Units
V
V
POT
RST
Power-on Reset
Threshold Voltage (rising)
Power-on Reset
Threshold Voltage
(1)
(falling)
RESET Pin Threshold
Voltage
TA = -40 - 85°C0.7 1.0 1.4V
TA = -40 - 85°C0.6 0.9 1.3V
= 3V0.1 V
V
CC
CC
0.9 V
CC
INTERNAL RESET
V
t
RST
Note:1. The Power- on Reset will not work unless the supply voltage has been below V
Minimum pulse width on
RESET Pin
VCC = 3V2.5µs
POT
(falling)
Power-on ResetA Power-on Reset (POR) pulse is generated by an On-chip det ection circuit. The detec-
tion level i s defined in Table 18. Th e POR is a ctivated w heneve r V
is below the
CC
detection level. The POR circuit can be used to trigger the Start-up Reset, as well as to
detect a failure in supply volt age.
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 i n RESET after V
activated again, without any dela y, when V
decreases below the detection level .
CC
rise. The RESET signal is
CC
47
2513E–AVR–09/03
Figure 22. MCU Start-up, RESET Tied to VCC.
V
V
CC
RESET
TIME-OUT
INTERNAL
RESET
POT
V
RST
t
TOUT
Figure 23. MCU Start-up, RESET
V
V
CC
RESET
TIME-OUT
INTERNAL
RESET
POT
Extended Externally
V
RST
t
TOUT
External ResetAn Externa l Reset is gene rated by a low level on the RES ET
than the minimum pulse width (see Table 18) 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 – V
counter starts the MCU after the Time-out period t
on its positive edge, th e delay
RST
has expired.
TOUT
Figure 24. External Reset During Operation
CC
pin. Reset pulses longer
48
ATmega162/V
2513E–AVR–09/03
ATmega162/V
Brown-out DetectionAT mega162 has an On-chip B rown -out Detect ion (BOD ) circuit for m onitoring the V
level during operation by comparing it to a fixed trigge r level. The trigger level for the
BOD can be selected by the BODLEVEL Fuses. The trigger level has a hysteresis to
ensure spike free Brown-out Detection. The hysteresis on the detection level should be
interpreted as V
BOT+
= V
BOT
+ V
HYST
/2 and V
BOT-
= V
BOT
- V
HYST
/2.
Table 19. BODLEVEL Fuse Coding
BODLEVEL Fuses [2:0]Min. V
111BOD Disabled
(2)
110
1012.52 .72.9
1004.14.34.5
(2)
011
010
000
Notes: 1. V
may be below nominal minimum operating voltage for some devices. For
BOT
devices where this is the case, the device is tested down to VCC = V
production test. This guarantees that a Brown-out Reset will occur befor e VCC drops
to a voltage where correct operation of the microcontroller is no longer guaranteed.
This test is performed using BODLEVEL = 110 for ATmega162V, BODLEVEL = 101
for ATmega162L, and BODLEVEL = 100 for ATmega162.
2. For ATmega162V. Otherwise reserved.
BOT
(1)
Typ. V
BOT
Max. V
1.71.82.0
2.12.32.5
Reserved001
BOT
duri ng the
BOT
Units
V
CC
Table 20. Brown-out Hysteresis
SymbolParameterMin.Typ.Max.Units
V
HYST
t
BOD
Brown-out Detector hysteresis50mV
Min Pulse Width on Brown-out Reset2µs
When the BOD is enabled and VCC decreases to a value below the trigger level ( V
Figure 25), the Brown-out Reset is immediat ely activated. When V
the trigger level (V
out period t
has expired.
TOUT
The BOD circuit will only detect a drop in V
for longer than t
BOD
in Figure 25), the delay cou nter starts the M CU after t he Time-
BOT+
if the voltage stays below the trigger level
CC
given in Table 18.
increases above
CC
BOT-
in
2513E–AVR–09/03
49
Figure 25. Brown-out Reset During Operation
V
CC
V
BOT-
V
BOT+
RESET
t
TIME-OUT
TOUT
INTERNAL
RESET
Watchdog ResetWhen the Watchdog times out, it will generate a short reset pulse of one CK cycle dura -
tion. On the falling edge of this puls e, the delay timer start s countin g the Time-out period
. Refer to page 51 for details on operation of the Watc hdog Timer .
t
TOUT
Figure 26. Watchdog Reset During Operation
CC
MCU Control and Status
Register – MCUCSR
CK
The MCU Control and Status Register provides information on which reset source
caused an MCU Reset.
Bit76543210
JTD–SM2JTRFWDRFBORFEXTRFPORFMCUCSR
Read/WriteR/WR/WRR/WR/WR/WR/WR/W
Initial Value000See Bit Descr iptio n
• Bit 4 – JTRF: JTAG Reset Flag
This bit is set if a res et is being caused by a logic one in th e JTAG R eset Regi ster
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 Fl ag
This bit is set if a Watchdog Reset occurs. The bi t is reset by a Pow er-on Reset, or by
writing a logic zero to the f lag.
50
ATmega162/V
2513E–AVR–09/03
ATmega162/V
• Bit 2 – BORF: Brown-out Reset Flag
This bit is set if a Brown-out Reset occurs. The bit is reset by a Powe r-on Reset, or by
writing a logic zero to the f lag.
• Bit 1 – EXTRF: External Reset Flag
This bit is set i f an E xternal R eset occ urs. T he bit is reset by a Power-on Reset, or by
writing a logic zero to the f lag.
• 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 re ad and
then Reset the MCUCSR as early as po ssible in the p rogram. If the regi ster is cleared
before another reset occurs, the source of the Reset can be found by examining the
Reset Flags.
Internal Voltage
Reference
Voltage Reference Enable
Signals and Start-up Time
ATmega162 features an internal bandgap reference. This reference is used for Brownout Detection, and it can be used as an input to the Analog Comparator.
The voltage reference has a star t-up time that may influence the way it should be used.
The start-up time is given i n Table 21. To s ave power, the r eference is n ot always tur ned
on. The reference is on during the follo wing situations:
1. When the BOD is enabled (by programming the BODLEVEL Fuses).
2. When the bandgap reference is connect ed to the Analog Compar ator (b y setting
the ACB G bit in ACSR).
Thus, when th e BO D is not en abled , afte r setti ng the ACB G bi t, the user m ust al ways
allow the reference to star t up befor e the output from the Analog Compar ator i s used. To
reduce power consumption in Power-down mode, the user can avoid the two conditions
above to ensure that the reference is turned of f before entering Power-down mode.
Table 21. Inter nal Voltage Reference Characteristics
SymbolParameterMin.Typ.Max.Units
V
t
BG
I
BG
Bandgap reference voltage1.051.101.15V
BG
Bandgap reference start-up time4070µs
Bandgap reference current
consumption
10µA
Wat c hdog TimerThe Watchdog Timer is clocked from a separat e On-chip Oscillator which runs at
1 MHz. This is the ty pical fre quency at V
values at other VCC levels. By controlling the Watchdog Timer prescaler, the Watchdog
Reset interval can be adjusted as shown in Table 23 on page 53. 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 ATmega162 resets and executes from the Reset Vector. For timing details on the Watchdog Reset, ref er to page 53.
= 5V. See characterization data for typical
CC
2513E–AVR–09/03
To prevent unintentional disabling of the Watchdog or unintentional change of time-out
period, 3 diffe rent safety leve ls are selecte d by the Fuses M 161C and WDT ON as
51
shown in Table 22. Safety level 0 corresponds to the setting in ATmega1 61. There is no
restriction on enabling the WDT in any of the safety levels. Refer to “Timed Sequences
for Changing the Configurati on of the Watchdog Timer” on page 55 for details.
Table 22. WDT Configuration as a Function of the Fuse Settings of M161C and
WDTON.
These bits are reserved bits in the ATmega162 and will always read as zero.
• Bit 4 – WDCE: Watchdog Change Enable
This bit must be set when the WDE bit is written to logic zero. Otherwise, the Watchdog
will not be disabled. Once written to one, hardware will clear this bit after four clock
cycles. Refer to the description of the WDE bit for a Watchdog disable procedure. In
Safety Levels 1 and 2, this b it must also be set when changi ng the prescaler bi ts. See
“Timed Sequences for Changing the Configuration of the Watchdog Timer” on page 55.
• Bit 3 – WDE: Watchdog Enabl e
When the WDE is written to l ogic one, the Watchdo g Timer i s enabled, and if the WDE is
written to logic zero, t he Watchdog Timer function is disabled. WDE can only be cleared
2513E–AVR–09/03
ATmega162/V
if the WDCE bit has logic level one. To disable an enabled Watchdog Timer, the following procedure must be followed:
1. In the same operation, write a logi c one t o WDCE and WDE. A logi c one must be
written to WDE even though it is set to one before the disable operation starts.
2. Within the next four clock cycles, write a logic 0 to WDE. This disables the
Watchdog.
In safety level 2, it is not possible t o disable the Watchdog Timer, even w ith the algorithm describe d abov e. See “Time d Seque nces for Cha nging the Configu ration of the
Watchdog Timer” on page 55.
The WDP2, WDP1, and WDP0 bits determine the Watchdog Timer prescaling when the
Watchdog Timer is enabled. The different prescaling values and their corresponding
Timeout Periods are shown in Table 23.
Table 23. Watchdog Timer Prescale Select
Number of WDT
WDP2WDP1WDP0
00016K (16,384)17 ms16 ms
00132K (32,768)34 ms33 ms
01065K (65,536)69 ms65 ms
011128K (131,072)0.14 s0.13 s
100256K (262,144)0.27 s0.26 s
101512K (524,288)0.55 s0.52 s
1101,024K (1,048,576)1.1 s1.0 s
1112,048K (2,097,152)2.2 s2.1 s
Oscillator Cycles
Typical Time-out
at VCC = 3.0V
Typical Time-out
at VCC = 5.0V
2513E–AVR–09/03
53
The following code example shows one assembly and one C function for turning off the
WDT. The example assumes that interrupts are controlled (e.g., by disabling interrupts
globally) so that no interrupt s wil l occur during execution of these functions.
Assembly Code Example
WDT_off:
; Reset WDT
WDR
; Write logical one to WDCE and WDE
in r16, WDTCR
ori r16, (1<<WD CE)|(1<<WDE)
out WDTCR, r16
; Turn off WDT
ldi r16, (0<<WD E)
out WDTCR, r16
ret
C Code Example
void WDT_off(void)
{
/* Reset WDT*/
_WDR()
/* Write logical one to WDCE and WDE */
WDTCR |= (1<<WDCE) | (1<<WDE);
/* Turn off WDT */
WDTCR = 0x00;
}
54
ATmega162/V
2513E–AVR–09/03
ATmega162/V
Timed Sequences for
Changing the
The sequence for changing c onfiguration differs slightly between the three safety levels.
Separate procedures are described for each level.
Configuration of the
Wat c hdog Timer
Safety Level 0This mode is compatible with the Watchdog operation found i n ATmega161. The Watch-
dog Timer is initially disabled, but can be enabled by writing the WDE bit to one without
any restriction. The Time-out period can be changed at any time without restriction. To
disable an enabled Watchdog Timer, the procedure described on page 52 (WDE bit
description) must be followed.
Safety Level 1In this mode, the Watchdog Timer is initially disabled, but can be enabled by writing the
WDE bit to one without any restricti on. A timed sequence is needed when changing the
Watchdog Time-out period or disablin g an enabled W atchdog Time r. To disable an
enabled Watchdog Timer, and/or changing the Watchdog Time-ou t, the f ollowing procedure must be followed:
1. In the same operation, write a logi c one t o WDCE and WDE. A logi c one must be
written to WDE regardless of the previous value of the WDE bit.
2. Within the next f our cloc k cycles , in the same ope ration, write the WDE and WDP
bits as desired, but with the WDCE bit cleared.
Safety Level 2In this mode, the Watchdog Timer is always enabled, and the WDE bit will always read
as one. A timed sequence is needed when changing the Watchdog Time-out period. To
change the Watchdog Time-out, the followi ng procedure must be followed:
1. In the same operation, write a logical one to WDCE and WDE. Even though the
WDE always is set, the WDE must be written to one to start the timed sequence.
2. Within the next four clock cycles, in the same operation, write the WDP bits as
desired, but wit h the WDCE bit cleared. The value written to the WDE bit is
irrelevant.
2513E–AVR–09/03
55
InterruptsThis section describes the specifics of the interrupt handl ing as performed in
ATmega162. For a general explanation of the AVR interrupt handling, refer to “Reset
and Interrupt Handling” on page 12. Table 24 shows the interru pt table when the com patibility fuse (M161C) is unprogrammed, whil e Table 25 shows the interrupt table when
M161C Fuse is programmed. All assembly code examples in this sec ti ons are using the
interrupt table when the M161C Fuse is unprogrammed.
Interrupt Vector s in
ATmega162
Table 24. Reset and Interrupt Vectors if M161C is unprogrammed
90x010TIMER3 COMPBTimer/Counter3 Compare Match B
100x012TIMER3 OVFTimer/Counter3 Overflow
110x014TIMER2 COMPTimer/Counter2 Compare Match
120x016TIMER2 OVFTimer/Counter2 Overflow
130x018TIMER1 CAPTTimer/Counter1 Capture Event
Address
(2)
SourceInterrupt Definition
(1)
RESETExternal Pin, Power-on Reset, Brown-out
Reset, Watchdog Reset, and JTAG AVR
Reset
56
140x01ATIMER1 COMPATimer/Counter1 Compare Match A
150x01CTIMER1 COMPBTimer/Counter1 Compare Match B
160x01ETIMER1 OVFTimer/Counter1 Overflow
170x020TIMER0 COMPTimer/Counter0 Compare Match
180x022TIMER0 OVFTimer/Counter0 Overflow
190x024SPI, STCSerial Transfer Complete
200x026USART0, RXCUSART0, Rx Complete
210x028USART1, RXCUSART1, Rx Complete
220x02AUSART0, UDREUSART0 Data Register Empty
230x02CUSART1, UDREUSART1 Data Register Empty
240x02EUSART0, TXCUSART0, Tx Complete
250x030USART1, TXCUSART1, Tx Complete
260x032EE_RD YEEPROM Ready
270x034ANA_COMPAnalog Comparator
280x036SPM_RDYStore Program Memory Ready
ATmega162/V
2513E–AVR–09/03
ATmega162/V
Notes: 1. When the BOOTRST Fuse is programmed, the device will jump to the Boot Loader
address at reset, see “Boot Loader Support – Read-While-Write Self-programming”
on page 216.
2. When the IVSEL bit in GICR is set, Interrupt Vectors will be moved to the start of the
Boot Flash section. The address of each Interr upt Vector will then be the address in
this table added to the start address of the Boot Flash section.
Table 25. Reset and Interrupt Vectors if M161C is programmed
Program
Vector No.
10x000
20x002INT0External Interrupt Request 0
30x004INT1External Interrupt Request 1
40x006INT2External Interrupt Request 2
50x008TIMER2 COMPTimer/Counter2 Compare Match
60x00ATIMER2 OVFTimer/Counter2 Overflow
70x00CTIMER1 CAPTTimer/Counter1 Capture Event
80x00ETIMER1 COMPATimer/Counter1 Compare Match A
90x010TIMER1 COMPBTimer/Counter1 Compare Match B
100x012TIMER1 OVFTimer/Counter1 Overflow
110x014TIMER0 COMPTimer/Counter0 Compare Match
120x016TIMER0 OVFTimer/Counter0 Overflow
130x018SPI, STCSerial Transfer Complete
140x01AUSART0, RXCUSART0, Rx Complete
150x01CUSART1, RXCUSART1, Rx Complete
160x01EUSART0, UDREUSART0 Data Register Empty
170x020USART1, UDREUSART1 Data Register Empty
Notes: 1. When the BOOTRST Fuse is programmed, the device will jump to the Boot Loader
address at reset, see “Boot Loader Support – Read-While-Write Self-programming”
on page 216.
2. When the IVSEL bit in GICR is set, Interrupt Vectors will be moved to the start of the
Boot Flash section. The address of each Interr upt Vector will then be the address in
this table added to the start address of the Boot Flash section.
57
Table 26 shows Reset and Interrupt Vectors placement for the various combinations of
BOOTRST and IVSEL settings. 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 al so the case if the Reset Vector is in the Application section while the
Interrupt Vectors are in t he Boot section or vice versa.
When the BOOTRST Fuse is unprogrammed, the boot section size set to 2K bytes and
the IVSEL bit in the GICR Register is set bef ore any interrupts are enable d, the most
typical and general prog ram setup for the Reset and Interrupt Vector Addresses is:
AddressLabelsCodeComments
0x000RESET:ldir16,high(RAMEND) ; Main program start
0x001outSPH,r16; Set Stack Pointer to top of RAM
0x002ldir16,low(RAMEND)
0x003outSPL,r16
0x004sei; Enable interrupts
0x005<instr> xxx
;
.org 0x1C02
0x1C02jmpEXT_INT0; IRQ0 Handler
0x1C04jmpEXT_INT1; IRQ1 Handler
.........;
0x1C36jmpSPM_RDY; Stor e Progr am Memory Rea dy Handle r
When the BOOTRST Fuse is programmed and the boot section size set to 2K bytes, the
most typical and general progra m setup for the Reset and Int errupt Vector Address es is:
0x036jmpSPM_RDY; Store Program Mem ory Rea dy Han dle r
;
.org 0x1C00
0x1C00RESET:ldir16,high(RAMEND) ; Main program start
0x1C01outSPH,r16; Set Stack Po inter to top of RAM
0x1C02ldir16,low(RAMEND)
0x1C03outSPL,r16
0x1C04sei; Enable interrupts
0x1C05<instr> xxx
2513E–AVR–09/03
59
When the BOOTRST Fuse is programmed, the boot section size set to 2K bytes and the
IVSEL bit in the GICR Register is set bef ore any interrupts are enabled, the most typical
and general program setup for the Reset and Interrupt Vector Addresses is:
0x1C36jmpSPM_RDY; Stor e Progr am Memory Rea dy Handle r
;
0x1C38RESET:ldir16,high(RAMEND) ; Main program start
0x1C39outSPH,r16; Set Stack Po inter to top of RAM
0x1C3Aldir16,low(RAMEND)
0x1C3BoutSPL,r16
0x1C3Csei; Enable interrupts
0x1C3D<instr> xxx
Moving Interrupts Between
Application and Boot Space
General Interrupt Control
Register – GICR
The Genera l Interru pt Contr ol Reg ister co ntrols t he place ment of th e Inte rrupt Vec tor
table.
When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the
Flash memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot Loader section of the Flash. The actual address of the start of the Boot
Flash section is determi ned by the B OOTSZ Fuse s. Re fer to the section “Bo ot Loa der
Support – Read-While-Write Self-programming” on page 216 for details. To avoi d unintentional changes of Interrupt Vector tables, a special write procedure must be followed
to change the IVSEL bit:
1. Write the Interrupt Vector Change Enable (IVCE) bit to one.
2. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE.
Interrupts will automatically be disabled while this sequence is executed. Interrupts are
disabled in the cycle IVCE is set, and they remain disabled until after the instruction following the write to IVSEL. If IVSEL is not written, interrupts remain disabled for four
cycles. The I-bit in the Status Register is unaffected by the automatic disabling.
Note:If Interrupt Vectors a re pla ced in the Bo ot Loa der se ction an d B oot Lo c k bit BLB 02 is pro-
grammed, interrupts are disabled while executing from the Application section. If
Interrupt Vectors are placed in the Application section and Boot Lock bit BLB12 is programed, interrupts are disabled while executing from the Boot Loader section. Refer to
the section “Boot Loader Support – Read-While-Write Self-programming” on page 216
for details on Boot Lock bits.
60
• Bit 0 – IVCE: Interrupt Vector Change Enable
The IVCE bit must be writte n to logic one to enab le change of the IV SEL bit. IVCE is
cleared by hardware four cycles after it is written or when IVSEL is written. Setting the
ATmega162/V
2513E–AVR–09/03
ATmega162/V
IVCE bit will disable interrupts, as explained in the IVSEL description above. See Code
Example below.
IntroductionAll AVR ports have true Read-Modify-Write functionality when used as general digital
I/O ports. This means that the direction of one port pin can be changed without unintentionally chang ing the direc tion of any ot her pin with the SBI and CBI instruc tions. The
same applies when changing drive value (if configured as output) or enabling/disabling
of pull-up resistors (if configured as input). Each output buffer has symmetrical drive
characteristics with both high sink and source cap abil ity. The pin dri ver is strong enough
to drive LED displays directly. All port pins have individually selectable pull-up resistors
with a supply-voltage invariant resistance. All I/O pins have protection diodes to both
and Ground as indicated in Figure 28. Refer to “Electrical Characterist ics” on page
V
CC
263 for a complete list of parameters.
Figure 28. I/O Pin Equivalent Schematic
R
pu
Pxn
C
pin
All registers and bit references in this section are written in general form. A lower case
“x” represents the numbering letter for the port, and a lower case “n” represents the bit
number. However, when using the register or bit defines in a program, the precise form
must be used. For example, PORTB3 for bit no. 3 in Port B, here documented generally
as PORTxn. The physical I/O Registers and bit locations are listed in “Register Description for I/O-Port s” on page 81.
Three I/O memory address locations are allocated for each port, one each for the D ata
Register – PORTx, Data Direction Regist er – DDRx, and the Port Input Pin s – PINx. The
Port Input Pins I/O location is read only, while the Data Register and the Data Direction
Register are read/writ e. In addition, the Pull-up Dis able – PUD bit in SFIOR disables the
pull-up function for all pins in all ports when set.
Using the I/O port as General Digital I/O is described in “Ports as General Digital I/O” on
page 63. Most p ort pins are multiplexed w ith alternate f unctions for the peripheral features on the device. How each alt ernate function interferes with the port pin is described
in “Alternate Port Func tions” on pag e 67. Refe r to the indivi dual modu le sec tions for a
full description of the alternate functions.
See figure
"General Digital I/O" for
Logic
details
62
Note that enabling the al ternate function of some of the port pins does not affect the use
of the other pins in the port as general digital I/O.
ATmega162/V
2513E–AVR–09/03
ATmega162/V
Ports as General Digital
I/O
The ports are bi-directional I/O ports with o ptional internal pull-up s. Figure 29 sh ows a
functional description of one I/O-port pin, here generically called Pxn.
Figure 29. General Digital I/O
Pxn
(1)
SLEEP
SYNCHRONIZER
DLQ
D
PINxn
Q
PUD
Q
D
DDxn
Q
CLR
RESET
Q
D
PORTxn
Q
CLR
RESET
Q
Q
WDx
RDx
WRx
RRx
RPx
DATA BUS
clk
I/O
PUD:PULLUP DISABLE
SLEEP:SLEEP CONTROL
clk
:I/O CLOCK
I/O
Note:1. WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clk
Configuring the PinEa ch p ort pin co nsists o f three regi ster b its: DDxn, P ORTx n, an d PIN xn. As s hown in
“Register Description for I/O-Ports” on page 8 1, the DDxn bits are ac cessed at the
DDRx I/O ad dress, the P ORTx n bits a t the PO RTx I/O address , an d the P INx n bi ts at
the PINx I/O address.
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written
logic one, Pxn is confi gured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin.
If PORTx n is w ritten logic one wh en th e pin is confi gured as an input pin, th e pul l-up
resistor is acti vated. To switch th e pull-up resis tor off , POR Txn h as to b e wr itten logic
zero or the pin has to be configured as an output pin. The port pins are tri-stated when a
reset condition becomes acti ve, even if no clocks are running.
If PORTxn is written logic one when the pin is configured as an output pin , the port pin is
driven high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero).
,
2513E–AVR–09/03
When swi tching be twee n tri-sta te ({DD xn, POR Txn} = 0b 00) an d output h igh ({D Dxn,
PORTxn} = 0b11), an intermediate state with either pull-up enabled ({DDxn, PORTxn} =
0b01) or output low ({DDxn, PORTxn} = 0b10 ) must occur. Normally, the pull-up
63
enabled state is fully acceptable, as a high-impedant environment wil l not notice the difference between a strong high driver and a pull-up. If this is not the case, the PUD bit in
the SFIOR Register can be set to disable all pull-ups in all ports.
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 intermediat e step.
Table 27 summarizes the control signa ls for the pin value.
Table 27. Port Pin Configurations
PUD
DDxnPORTxn
00XInputNoTri-state (Hi-Z)
010InputYes
011InputNoTri-state (Hi-Z)
10XOutputNoOutput Low (Sink)
11XOutputNoOutput High (Source)
(in SFIOR)I/OPull-upComment
Pxn will source current if ext. pulled
low.
Reading the Pin ValueIndependent of the setting of Data Direction bit DDxn, the port pin can be read through
the PINxn Register bit. As shown in Figure 29, the PI Nxn Register bit and the preceding
latch constitute 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
30 shows a t iming dia gram of th e syn chronizat ion w hen readi ng an extern ally a pplie d
pin value. The maximum and minimum propagation delays are denoted t
pd,max
and t
pd,min
respectively.
Figure 30. Synchronization when Reading an Externally Applied Pin Value
SYSTEM CLK
INSTRUCTIONS
XXXin r17, PINx
XXX
SYNC LATCH
PINxn
r17
0x000xFF
t
pd, max
t
pd, min
64
ATmega162/V
2513E–AVR–09/03
ATmega162/V
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 l ow. It i s clocked into the PI Nxn Registe r at the succeeding positive clock edge . As ind icated by the two arrows t
pd,max
and t
signal transition on the pin w ill be delayed between ½ and 1½ system clock period
depending upon the time of assertion .
When reading back a software assigned pin value , a nop inst ructi on must be insert ed as
indicated in Figure 31. The out instruction sets the “SYNC LATCH” signal at the positive
edge of the clock. In this case, the delay t
through the synchronizer is one syst em
pd
clock period.
Figure 31. Synchronization when Reading a Software Assigned Pin Value
SYSTEM CLK
pd,min
, a single
r16
INSTRUCTIONS
SYNC LATCH
PINxn
r17
0xFF
out PORTx, r16nopin r17, PINx
0x000xFF
t
pd
2513E–AVR–09/03
65
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 instruct ion
is included to be able to read back the value recently assigned to some of the pins.
Assembly Code Example
...
; Define pull-ups and set outputs high
; Define directions for port pins
/* Define pull-ups and set out puts 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 synchroni zation*/
_NOP();
/* Read port pins */
i = PINB;
...
(1)
(1)
Digital Input Enab le and Sleep
Modes
66
ATmega162/V
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.
As shown in Figure 29, the digital input signal can be clamped to ground at the input of
the Schmitt Trigger. The signal denoted S LEE P in th e figure, is se t 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 l eft fl oating, or
have an analog signal level close to V
CC
/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 various other alternate functions as described in “Alternate Port Functions” on page 67.
If a logic high level (“one”) is present on an Asynchronous External Interrupt pi n configured as “Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin” while the
external interru pt is not enab led, the corres pond ing Extern al Interru pt Flag will be set
when resuming from the above mentioned sleep modes, as the clamping in these sleep
modes produces the requested logic change.
2513E–AVR–09/03
ATmega162/V
x
Unconnected pinsIf some pins are unused, it is recommended to ensure that these pins have a defined
level. Even thoug h most o f th e di gital inpu ts ar e disa bled in the d eep s leep mod es as
described above, floating inputs should be avoided to reduce current consumption in all
other modes where the digital inputs are enabled (Reset, Active mode and Idle mode).
The simplest method to ensure a defined level of an unused pin, is to enable the internal
pull-up. In this case, the pull-up will be disabled during reset. If low power consumption
during reset is important, it is recommended to use an external pull-up or pull-down.
Connecting unused pins directly to V
cause excessive currents if the pin is accidentally configured as an output.
Alternate Port FunctionsMo st port pi ns have a lternate function s in add ition to being ge neral digi tal I/Os. Fi gure
32 shows how the port pin control signals from the simplified Figure 29 can be overridden by alternate functions . The overri ding si gnals may no t be present in all port pi ns, but
the figure serves as a generic d escription ap plicable to al l port pins in the A VR m icrocontroller family.
or GND is not recommended, since this may
CC
Figure 32. Alternate Port Funct ions
1
0
1
0
Pxn
1
0
1
0
(1)
PUOExn
PUOVxn
DDOExn
DDOVxn
PVOExn
PVOVxn
DIEOExn
DIEOVxn
SLEEP
SYNCHRONIZER
SET
DLQ
D
PINxn
Q
CLR
PUD
Q
D
DDxn
Q
CLR
RESET
D
Q
PORTxn
Q
CLR
RESET
Q
Q
CLR
WDx
RDx
WRx
RRx
RPx
clk
DATA BUS
I/O
2513E–AVR–09/03
DIxn
AIOxn
PUOExn: Pxn PULL-UP OVERRIDE ENABLE
PUOVxn: Pxn PULL-UP OVERRIDE VALUE
DDOExn: Pxn DATA DIRECTION OVERRIDE ENABLE
DDOVxn: Pxn DATA DIRECTION OVERRIDE VALUE
PVOExn: Pxn PORT VALUE OVERRIDE ENABLE
PVOVxn: Pxn PORT VALUE OVERRIDE VALUE
DIEOExn: Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE
DIEOVxn: Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE
SLEEP: SLEEP CONTROL
DIxn: DIGITAL INPUT PIN n ON PORTx
AIOxn: ANALOG INPUT/OUTPUT PIN n ON PORT
Note:1. WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clk
SLEEP, and PUD are common to all ports. All other signals are unique for each pin.
I/O
67
,
Table 28 su mmariz es the funct ion of the ove rriding signals. T he pin an d port indexe s
from Figure 32 are not shown in the succeeding tables. The overriding signals are generated internally in the modules having the alternate function.
Table 28. Generic Description of Over riding Signals for Alternate Functions.
Signal NameFull NameDescription
PUOEPull-up Override
Enable
PUOVPull-up Override
Value
If this signal is set, the pull-up enable is controlled by the
PUOV signal. If this signal is cleared, the pull-up is
enabled when {DDxn, PORTxn, PUD} = 0b010.
If PUOE is set, the pull-up is enabled/disabled when
PUOV is set/cleared, regardless of the setting of the
DDxn, PORTxn, and PUD Register bits.
DDOEData Direction
Override Enable
DDOVData Direction
Override Value
PVOEPort Value
Override Enable
PVOVPort Value
Override Value
DIEOEDigital Input
Enable Ov erride
Enable
DIEOVDigital Input
Enable Ov erride
Value
DIDigital InputThis is the Digital Input to alternate functions. In th e figur e ,
If this signal is set, the Output Driver Enable is controlled
by the DDOV signal. If this signal is cleared, the Output
driver is enabled by the DDxn Register bit.
If DDOE is set, the Output Driver is enabled/disabled
when DDO V is set/cle ared , r egar dless of th e se tti ng of t he
DDxn Register bit.
If this signal is set and the Output Driver is enabled, the
port value is controlled by the PVOV signal. If PVOE is
cleared, and the Output Driver i s enabled, the port V alue is
controlled by the PORTxn Register bit.
If PVOE is set, the port value is set to P VOV, regardless of
the setting of the PORTxn Register bit.
If this bit is set, the Digital Input Enable is controlled by the
DIEOV signal. If this signal is cleared, the Digital Input
Enable is determined by MCU state (Normal Mode, Sleep
Modes).
If DIEOE is set, the Digital Input is enab led/d isab l ed when
DIEOV is set/cleared, regardless of the MCU state
(Normal Mode, Sleep Modes).
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.
68
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.
ATmega162/V
AIOAnalog
Input/output
This is the Ana log In put/output to/from alternate functions.
The signal is connected directly to the pad, and can be
used bi-directionally.
When this bit is written to one, the pull-ups in the I/O ports are disabled even i f the DDxn
and PORTxn Registers are configured to enable the pull- ups ({DDxn, PORTxn} = 0b01).
See “Configuring the Pin” on page 63 for more details about this feature.
Alternate Functions of Port APort A has an alternate function as the address low byte and data lines for the External
Memory Interface and as Pin Change Interru pt.
Table 29. Port A Pins Alternate Functions
Port PinAlterna te Function
PA7
PA6
PA5
PA4
AD7 (External memory interface address and data bit 7)
PCINT7 (Pin Change INTerrupt 7)
AD6 (External memory interface address and data bit 6)
PCINT6 (Pin Change INTerrupt 6)
AD5 (External memory interface address and data bit 5)
PCINT5 (Pin Change INTerrupt 5)
AD4 (External memory interface address and data bit 4)
PCINT4 (Pin Change INTerrupt 4)
PA3
PA2
PA1
PA0
AD3 (External memory interface address and data bit 3)
PCINT3 (Pin Change INTerrupt 3)
AD2 (External memory interface address and data bit 2)
PCINT2 (Pin Change INTerrupt 2)
AD1 (External memory interface address and data bit 1)
PCINT1 (Pin Change INTerrupt 1)
AD0 (External memory interface address and data bit 0)
PCINT0 (Pin Change INTerrupt 0)
Table 30 and Table 31 relate the alternate funct ions of Port A to the ove rriding signals
shown in Figure 32 on page 67.
2513E–AVR–09/03
69
Table 30. Overriding Signals for Alternate Functions in PA7..PA4
SCK: Master Clock o utput, Sla ve Cloc k input p in for S PI channel . When the SP I is
enabled as a Slave, this pin is configured as an input regardless of the setting of DDB7.
When the SPI is e nabled as a Master, the dat a direction of thi s pin is co ntrolled 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 inp ut, Slave Data output pin for SPI channel. When the SPI is
enabled as a Mas ter, this pin is config ured as an inpu t regardless of the se tting 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.
2513E–AVR–09/03
• 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 e nabled as a Master, the dat a direction of thi s pin is co ntrolled 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.
/OC3B – Port B, Bit 4
•SS
: Slave Select input. When the SPI is enabled as a slave, this pin is configured as an
SS
input regardless of the setti ng of DDB4. As a Slave, t he SPI is activated when this pin is
driven low. Whe n the SPI is ena bled as a Master, t he da ta dire ction of this pin is controlled by DDB4. When the pin is forced by the SPI to be an in put, the pull-up can still be
controlled by the PORTB4 bit.
71
OC3B, Output Comp are Match B output: The PB4 pin can serve as an e xternal output
for the Timer/Coun ter3 Output C ompa re B . The p in h as to be conf igured a s an o utput
(DDB4 set (one)) to s erv e this f uncti on. The OC3B pi n is al so the out put pin for th e PWM
mode timer function.
• AIN1/TXD1 – 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 wit h the function
of the Analog Comparator.
TXD1, Transmit Data (Data output pin for USART1). When the USART1 Transmitter is
enabled, this pin is configured as an output regardless of the value of DDB3.
• AIN0/RXD1 – Port B, Bit 2
AIN0, Analog Comparator Positiv e Input. Configu re 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.
RXD1, Receive Data (Data input pin for USART1). When the USART1 Receiver is
enabled this pi n is config ured as an inp ut regardl ess of the val ue of DDB2. When the
USART1 forces this pin to be an input, the pull-up can still be controll ed by the PORTB2
bit.
• T1/OC2 – Port B, Bit 1
T1, Timer/Counter1 Count er Source.
OC2, Output Com pare Ma tch ou tput: Th e PB1 pin can serve as an ext ernal out put for
the Timer/Counter2 Compare Match. The PB1 pin has to be configured as an output
(DDB1 set (one)) to serve this function. The OC2 pin is also t he output pin for the PWM
mode timer function.
• T0/OC0 – Port B, Bit 0
T0, Timer/Counter0 counter source.
OC0, Output Com pare Ma tch ou tput: Th e PB0 pin can serve as an ext ernal out put for
the Timer/Counter0 Compare Match. The PB0 pin has to be configured as an output
(DDB0 set (one)) to serve this function. The OC0 pin is also t he output pin for the PWM
mode timer function.
, Divided System Cl ock: Th e div ided sy stem clock can be o utput on the PB0 pin.
clk
I/O
The divided system clock will be output if the CKOUT Fuse is programmed, regardless
of the PORTB0 and DDB0 settings. It will also be output during reset .
Table 33 and Table 34 relate the alternate funct ions of Port B to the ove rriding signals
shown in Figure 32 on page 67. SPI MSTR INPUT and SPI SLAVE OUTPUT constitute
the MISO signal, while M OSI is divided into SPI MSTR OUTPUT and SPI SLAVE
INPUT.
72
ATmega162/V
2513E–AVR–09/03
ATmega162/V
Table 33. Overriding Signals for Alternate Functions in PB7..PB4
A15, External memory interface address bit 15.
TDI, JTAG Test Data In: Se rial input data to b e shifted into the In struction Register or
Data Register (s can chains). When the JTAG interf ace is e nabl ed, thi s pin c an not be
used as an I/O pin.
PCINT15: The pin can also serve as a pin change interrupt.
• A14/TDO/PCINT14 – Port C, Bit 6
A14, External memory interface address bit 14.
TDO, JTAG Test Data Out: Serial out put data from Inst ruction Register or Data Regi s-
ter. When the JTAG interface is enabled, this pin can not be used as an I/O pin. In TAP
states that shift out data, the TD0 pin drives actively. In other states the pin i s pulled
high.
74
PCINT14: The pin can also serve as a pin change interrupt.
ATmega162/V
2513E–AVR–09/03
ATmega162/V
• A13/TMS/PCINT13 – Port C, Bit 5
A13, External memory interface address bit 13.
TMS, JTAG Test Mode Select: This p in is us ed f or navig ating t hrough t he TAP-c ontrol ler
state machine. When the JTAG interface is enabled, this pin can not be used as an I/ O
pin.
PCINT13: The pin can also serve as a pin change interrupt.
• A12/TCK/PCINT12 – Po rt C, Bit 4
A12, External memory interface address bit 12.
TCK, JTAG Test Clock: JTAG operation is synchronous to TCK. When the JTAG inter-
face is enabled, this pin can not be used as an I/O pin.
PCINT12: The pin can also serve as a pin change interrupt.
• A11/PCINT11 – Port C, Bit 3
A11, External memory interface address bit 11.
PCINT11: The pin can also serve as a pin change interrupt.
• A10/PCINT10 – Port C, Bit 2
A10, External memory interface address bit 10.
PCINT11: The pin can also serve as a pin change interrupt.
• A9/PCINT9 – Port C, Bit 1
A9, External memory interface address bit 9.
PCINT9: The pin can also serve as a pin change interrupt.
• A8/PCINT8 – Port C, Bit 0
A8, External memory interface address bit 8.
PCINT8: The pin can also serve as a pin change interrupt.
Table 36 and Table 37 relate the alternate functions of Port C to the overriding signals
shown in Figure 32 on page 67.
2513E–AVR–09/03
75
Table 36. Overriding Signals for Alternate Functions in PC7..PC4
is the external data memory write contr ol st robe.
WR
• TOSC2/OC1A – Port D, Bit 5
2513E–AVR–09/03
TOSC2, Timer Oscillator pin 2: When the AS2 bit in ASSR is set (one) to enable asynchronous clocking of Timer/Counter2, pin PD5 is disconnected from the port, and
becomes the inverting output of the Oscillat or amplifier. In this mode, a crystal Oscill ator
is connected to this pin, and the pin can not be used as an I/O pin.
OC1A, Output Compare Match A out put: The PD5 pi n can serve as an external o utput
for the Timer/Coun ter1 Output C ompa re A . The p in h as to be conf igured a s an o utput
(DDD5 set (one)) to serve this function. The OC1A pin is also the output pin for the
PWM mode timer function.
77
• TOSC1/XCK0/OC3A – P ort D, Bit 4
TOSC1, Timer Oscillator pin 1: When the AS2 bit in ASSR is set (one) to enable asynchronous clocking of Timer/Counter2, pin PD4 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.
XCK0, USART0 E xternal Clock: The Data Direction Reg ister (DDD4) c ontrols whether
the clock is o utput (DDD 4 s et (one)) or in pu t (DD D4 c leared (zero )). The XCK 0 pin is
active only when USART0 operates in Synchronous mode.
OC3A, Output Compare Match A out put: The PD4 pi n can serve as an external o utput
for the Timer/Coun ter1 Output C ompa re A . The p in h as to be conf igured a s an o utput
(DDD4 set (one)) to serve this function. The OC4A pin is also the output pin for the
PWM mode timer function.
• INT1/ICP3 – Port D, Bit 3
INT1, Exte rnal Interrupt Source 1: The PD3 pin can serve as an external interrupt
source.
ICP3, Inpu t Capture Pin: The PD3 pin can act as an Inp ut Capture pin for
Timer/Counter3.
• INT0/XCK1 – Port D, Bit 2
INT0, Exte rnal Interrupt Source 0: The PD2 pin can serve as an external interrupt
source.
XCK1, USART1 E xternal Clock: The Data Direction Reg ister (DDD2) c ontrols whether
the clock is o utput (DDD 2 s et (one)) or in pu t (DD D2 c leared (zero )). The XCK 1 pin is
active only when USART1 operates in Synchronous mode.
• TXD0 – Port D, Bit 1
TXD0, Transmit Data (Data output pin for USART0). When the USART0 Transmitter is
enabled, this pin is configured as an output regardless of the value of DDD1.
78
ATmega162/V
2513E–AVR–09/03
ATmega162/V
• RXD0 – Port D, Bit 0
RXD0, Receive Data (Data input pin for USART0). When the USART0 Receiver is
enabled this pin is configured as an input regardless of the value of DDD0. When
USART0 forces this pin t o be an input, the pull-up can still be co ntr olled by the PORTD0
bit.
Table 39 and Table 40 relate the alternate functions of Port D to the overriding signals
shown in Figure 32 on page 67.
Table 39. Overriding Signals for Alternate Functions PD7..PD4
Signal NamePD7/RDPD6/WRPD5/TOSC2/OC1APD4/TOSC1/XCK0/OC3A
OC1B, Output Comp are Match B output: The PE2 pin can serve as an e xternal output
for the Timer/Coun ter1 Output C ompa re B . The p in h as to be conf igured a s an o utput
(DDE0 set (one)) to s erv e this f uncti on. The OC1B pi n is al so the out put pin for th e PWM
mode timer function.
Table 42 relate the alter nate fu nctions of Port E to the o verr iding signal s shown in F igure
32 on page 67.
•ALE – Port E, Bit 1
ALE is the external data memory Address Latch Enable sig nal.
• ICP1/INT2 – Port E, Bit 0
ICP1, Inp ut Capture Pi n: The PE0 pin can act as an Input Capture pin for
Timer/Counter1.
INT2, External Interrupt Source 2: The PE0 pin can serve as an external interrupt
source.
Table 42. Overriding Signals for Alternate Functions PE2..PE0
External InterruptsTh e External Interrupts are triggered by the INT0, IN T1, INT2 pin, or a ny of the
PCINT15..0 pins. Observe that, if enabled, the interrupts will trigger even if the INT2..0
or PCINT15..0 pi ns are configured as outputs. Th is feature provides a way of g enerating
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 i n the
specification for the MCU Control Register – MCUCR and Extended MCU Control Register – EMCUCR. Whe n the external interrup t is enabled a nd is confi gured as level
triggered (only INT0/INT1), the interrup t will trigger as long as the p in is held low. The
pin change interrupt PCI1 will trigger if any enabled PCINT15. .8 pi n toggles. Pin change
interrupts PCI0 will trigger if any enabled PCINT7..0 pi n toggles. The PCMSK 1 and
PCMSK0 Registers control which pins contribute to the pin change interrupts. Note that
recognition of falling or ri sing edge i nterrup ts on INT0 and INT1 requi res th e presence of
an I/O clock, described in “Clock Systems and their Distribution” on page 33. Low level
interrupts on INT0/INT1, the edge interrupt on INT2, and Pin change interrupts on
PCINT15..0 are detected asynchr onously. This impl ies tha t these inter rupts ca n 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 f rom Power-down mode, the
changed level must be h eld for some ti me to wake up the MC U. Thi s makes the MC U
less sensitive to noise. The changed level is sampled twice by the Watchdog Oscillator
clock. The period of the Watch dog Oscil lator is 1 µs (nomi nal) at 5.0V and 25°C. Th e
frequency of th e Watchdog Oscillator is voltage dependent as shown in “Electrical Characteristics” on page 263. The MCU will wake up if t he 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 33. If the
level is sampled twice by the Watchdog Oscillator clock but disap pears before the end
of the start-up t ime, t he MC U wi ll still w ake up , but no in terrupt w ill be g enerat ed. The
required level must be held long enough for the MCU to complete the wake up to trigger
the level interrupt.
MCU Control Register –
MCUCR
The MCU Control Register contains control bits for interrupt sense control and general
MCU functions.
• Bit 3, 2 – ISC11, ISC10: Interrupt Sense Control 1 Bit 1 and Bit 0
The External Interrupt 1 is a ctivated by the external pin I NT1 if th e SREG I-bit and the
corresponding interrupt mask in the G ICR are set. The level and edges on the external
INT1 pin that activat e the interrupt are defined in Table 43. 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 wil l generate an i nterrupt. Shorter pulses a re not gua ranteed to generate an inter rupt. If low level interrupt is selected, the low l evel must be held
until the completion of the currently executing instruction to generate an interrupt.
2513E–AVR–09/03
83
Table 43. I nterrupt 1 Sense Control
ISC11ISC10Description
00The low level of INT1 generates an interrupt request.
01Any logical change on INT1 generates an interrupt request.
10The falling edge of INT1 generates an interrupt request.
11The rising edge of INT1 generates an interrupt request.
• Bit 1, 0 – ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0
The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the
corresponding interrupt mask are set. The level and edges on the external INT0 pin that
activate the interrupt are defined in Table 44. The value on the INT0 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 pu lses are not guaranteed to
generate an int errupt. If low lev el interrup t is sele cted, th e low lev el m ust be h eld unt il
the completion of the currently executing instruction to generate an interrupt.
Table 44. I nterrupt 0 Sense Control
ISC01ISC00Description
00The low level of INT0 generates an interrupt request.
01Any logical change on INT0 generates an interrupt request.
Extended MCU Control
Register – EMCUCR
10The falling edge of INT0 generates an interrupt request.
11The rising edge of INT0 generates an interrupt request.
The asynchronous External Inter rupt 2 is activated by the external pin INT2 if t he SREG
I-bit and the corresponding interrupt mask in GICR are set. If ISC 2 is cleared (zero), a
falling edge on INT2 a ctivates t he interrupt. If I SC2 is se t (one), a rising edge on INT2
activates the interrupt. Edges o n INT2 a re registere d asynchron ously. P ulses on INT2
wider than the minimum puls e widt h given in Table 45 will generate an interrupt. Shor ter
pulses are not guaranteed to generate an interrupt. When changing the ISC2 bit, an
interrupt can occur. Therefore, it is recommended to first disable INT2 by clearing its
Interrupt Enable bit in the GICR Regist er. Then, the ISC2 bit can be change d. Finally,
the INT2 Interrupt Flag should be cleared by writing a logical one to its Interrupt Flag bit
(INTF2) in the GIFR Register before the interrupt is re-enabled.
• Bit 7 – INT1: External Interrupt Request 1 Enable
When the INT1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one),
the external pin interrupt is enabled. The Interrupt Se nse Control1 bi ts 1/0 (ISC11 and
ISC10) in the MCU general Control Register (MCU CR) define whether the ext ernal
interrupt is acti vated on ri sing and/ or fal ling edge of the I NT1 pin or le vel sensed . Activ ity
on the pin wi ll cause an interrup t requ est even if I NT1 is configu red as a n out put. The
corresponding interrupt of External Interrupt Request 1 is executed from the INT1 Interrupt Vector.
• Bit 6 – INT0: External Interrupt Request 0 Enable
When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one),
the external pin interrupt is enabled. The Interrupt Se nse Control0 bi ts 1/0 (ISC01 and
ISC00) in the MCU general Control Register (MCU CR) define whether the ext ernal
interrupt is acti vated on ri sing and/ or fal ling edge of the I NT0 pin or le vel sensed . Activ ity
on the pin wi ll cause an interrup t requ est even if I NT0 is configu red as a n out put. The
corresponding interrupt of External Interrupt Request 0 is executed from the INT0 Interrupt Vector.
• Bit 5 – INT2: External Interrupt Request 2 Enable
When the INT2 bit is set (one) and the I-bit in the Status Register (SREG) is set (one),
the external pin interru pt is enabled. T he Interrupt Se nse Control2 bit (ISC2) in the
Extended MCU Control Register (EMCUCR) defines whether the external interrupt is
activated on risi ng or falling edge of the INT2 pin. Activity on the pin will cause an interrupt request even if INT2 is configured as an output. The corresponding interrupt of
External Interrupt Request 2 is executed from the INT2 Interrupt Vector.
• Bit 4 – PCIE1: Pin Change Interrupt Enable 1
When the PCIE1 bit i s set (one) and the I-bit in the Status Register (SREG) is set (one),
pin change interr upt 1 is enabled. Any chang e on any enabled PCINT1 5..8 pin will
cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI 1 Interrupt Ve ctor. PCINT15..8 pins ar e enabled individu ally by the
PCMSK1 Register.
• Bit 3 – PCIE0: Pin Change Interrupt Enable 0
When the PCIE0 bit i s set (one) and the I-bit in the Status Register (SREG) is set (one),
pin change interrupt 0 is enabled. Any change on any enabled PCINT7.. 0 pin will cause
an interrupt. The correspond ing interr upt o f Pin Change Interr upt Reque st is executed
from the PCI0 Interrupt Vector. PCINT7..0 pins are enabled individually by the PCMSK0
Register.
When an edge or logic change on the INT1 pi n triggers an interrupt request, INTF1
becomes set (one). If the I-bit in SREG and the INT1 bit i n GICR ar e set (one), the MCU
will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt
routine is execute d. Altern atively, t he fl ag can be cleared by writing a log ical on e to it.
This flag is always cleared when INT1 is configur ed as a level int errupt.
• Bit 6 – INTF0: External Interrupt Flag 0
When an edge or logic change on the INT0 pi n triggers an interrupt request, INTF0
becomes set (one). If the I-bit in SREG and the INT0 bit i n GICR ar e set (one), the MCU
will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt
routine is execute d. Altern atively, t he fl ag can be cleared by writing a log ical on e to it.
This flag is always cleared when INT0 is configur ed as a level int errupt.
• Bit 5 – INTF2: External Interrupt Flag 2
When an event on the INT2 pin triggers an interrupt request, INTF2 becomes set (one).
If the I-bit in SREG and the INT2 bit in GICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed.
Alternatively, the fl ag can be cleared by writing a logical one to it. Note that when entering some sleep modes wi th the IN T2 interrupt disabl ed, the input b uffer on this pin will
be disabled. This may cause a logic change in internal signals which will set the INTF2
flag. See “Digital Input Enable and Sleep Modes” on page 66 for more information.
• Bit 4 – PCIF1: Pin Change Interrupt Flag 1
When a logic change on any PCINT15..8 pin triggers an interrupt request, PCIF1
becomes set (one). If the I-bit in SREG and the PCIE1 bit in GICR are set (one), the
MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is execut ed. Alternatively, the flag can be cleared by w riting a logical one to
it.
• Bit 3 – PCIF0: Pin Change Interrupt Flag 0
When a logic change on any PCINT7..0 pin triggers an inte rrupt request, PCIF0
becomes set (one). If the I-bit in SREG and the PCIE0 bit in GICR are set (one), the
MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is execut ed. Alternatively, the flag can be cleared by w riting a logical one to
it.
• Bit 7..0 – PCINT15..8: Pin Change Enable Mask 15..8
Each PCINT15..8 bit selects whet her pin change i nterr upt is enabl ed on the corr espond ing I/O pin. If PCINT15..8 is set and the PCIE1 bit in GICR is set, pin change int errupt is
enabled on the corresponding I/O pin. If PCINT15..8 is cleared, pin change interrupt on
the corresponding I/O pin is disabled.
• Bit 7..0 – PCINT7..0: Pin Change Enable Mask 7..0
Each PCINT7..0 bit select s whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT7..0 is set and the PCIE0 bit in GICR is set, pin change interrupt is
enabled on the corresp onding I/O pin. If PC INT7..0 is cleared, pi n change interrupt on
the corresponding I/O pin is disabled.
The mapping between I/O pins and PCINT bi ts can be fo und in Figure 1 on pa ge 2. Not e
that the Pin Chan ge Mask Regi ster are located in Exten ded I/O. Thus, t he pin cha nge
interrupts are not support ed in ATmega161 compatibility mode.
2513E–AVR–09/03
87
8-bit Timer/Cou nter0
with PWM
Timer/Counter0 is a general purpose, single channel, 8-bit Timer/Counter module. The
main features are:
Singl e Channel Counter
•
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, Phase Cor rect Pulse Width Modulator (PWM)
• Frequency Generator
• External Event Counter
• 10-bit Clock Presc aler
• Overflow and Compare Match Interrupt Sources (TOV0 and OCF0)
OverviewA simplified block diagram of the 8-bit Timer/Counter is shown in Figure 33. For the
actual placement of I/O pins, refer to “Pinout A Tmega162” on page 2. CPU accessible
I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O
Register and bit locations are listed in the “8-bit Timer/Counter Regist er Description” on
page 99.
Figure 33. 8-bit Timer/Counter Block Diagram
TCCRn
count
clear
direction
BOTTOM
Timer/Counter
TCNTn
Control Logic
= 0
=
TOP
0xFF
clk
Tn
Clock Select
Edge
Detector
( From Prescaler )
DATA BUS
=
OCRn
Waveform
Generation
TOVn
(Int.Req.)
Tn
OCn
(Int.Req.)
OCn
RegistersThe Ti mer/Counter (TCNT0) and Output Compare Register (OCR0) are 8-bit registers.
Interrupt request (abbreviated t o Int.Req. in the figure) signals are all visible in the Timer
Interrupt Flag Register (TIFR). All interrupts are individually ma sked with the Ti mer
Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure since
these registers are shar ed by other timer units.
88
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock
source on the T0 pin. The Cloc k Select logic block c ontrol s which cl ock sou rce and edge
the Timer/Counter uses t o increment (or decrement) its value. The Timer/Counter is
ATmega162/V
2513E–AVR–09/03
ATmega162/V
inactive when no clock s ource is selected. The output from t he clock select logic is
referred to as the timer clock (clk
The double bu ffered Output Comp are Register (OCR 0) is compared with the
Timer/Counter value at all times. The result of the com pare can be used by the Waveform Generator to gene rate a PW M or vari able fr equency out put on the Out put Compare
pin (OC0). See “Output Compare Unit” on page 90. for details. The Compare Match
event will also set the Compare Flag (OCF0) which can be used to generate an output
compare interrupt requ est.
DefinitionsMany register and bi t r eferences in this section are written in general f orm. A lower case
“n” replaces the T imer/Counter number, i n this case 0. Howeve r, when using t he regi ste r
or bit defines in a program, the precise form must be used i.e., TCNT0 for accessing
Timer/Counter0 count er value and so on.
The definitions in Table 46 are also used extensively throughout the document.
Table 46. Def initions
BOTTOMThe counter reaches the BOTTOM when it becomes 0x00.
MAXThe counter reaches its MAXimum when it becomes 0x FF (dec imal 255).
TOPThe 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 val ue stored in the OCR0 Register. Th e
assignment is dependent on the mode of operation.
0).
T
Timer/Counter Clock
Sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock
source is selected by the Clock Select logic which is controlled by the Clock S elect
(CS02:0) bits located in the Timer/Counter Control Register (TCCR0). For details on
clock sources and pres caler, see “Timer/Counter0, Timer/Counter1, an d
Timer/Counter3 Prescalers” on page 103.
2513E–AVR–09/03
89
Counter UnitThe main part of the 8-bit Time r/Count er is the pr ogrammable bi-di recti onal count er unit .
Figure 34 shows a block diagram of the counter and its surro undings.
Figure 34. Counter Unit Block Diagram
TOVn
DATA BUS
count
TCNTnControl Logic
clear
direction
(Int.Req.)
clk
Tn
Clock Select
Edge
Detector
( From Prescaler )
Tn
bottom
top
Signal description (i nternal signals):
countIncrement or decrement TCNT0 by 1.
directionSelect between increment and decrement.
clearClear TCNT0 (set all bits to zero).
clk
Tn
Timer/Counter clock, referred to as clkT0 in the following.
topSignalize that TCNT0 has reached maximum value.
bottomSignalize that TCNT0 has reached minimum value (zero).
Depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock ( clk
0). clkT0 can be generated from an external or int ernal
T
clock sour ce, selecte d by the cloc k select bi ts (CS02: 0). When no clo ck sour ce is
selected (CS02:0 = 0) t he timer is stopped. However, t he TCNT0 valu e can be accessed
by the CPU, regardless o f whether clk
0 is present or not. A CPU write overrides (ha s
T
priority over) all counter clear or count operations.
The counting sequence is determined by the setting of the WGM01 and WGM00 bits
located in the Timer/Counter Control Register (TCCR0). There are close connections
between how the counter beh aves (counts) and ho w wavefo rms are g enerated on the
output Compare Output OC0. For more details about advanced counting sequences
and waveform generation, see “Modes of Operat ion” on page 93.
The Timer/Counter Overflow (TOV0) Flag is set according to the mode of operation
selected by the WGM01:0 bits. TOV0 can be used for generating a CPU interrupt.
Output Compare UnitThe 8-bit comparator continuousl y compares TCNT0 with the Output Compare Register
(OCR0). Whenever TCNT0 equals OCR0, the comparator signals a match. A match will
set the Output Compare Flag (OCF0) at the next timer clock cycle. If enabled (OCIE0 =
1 and Global Interrupt Flag in SREG is set), the Output Compare Flag generates an output compare interrupt. The OCF0 Flag is automatically cleared when the interrupt is
executed. Alternatively, the O CF0 Flag ca n be cl eared by softwa re by w riting a logi cal
one to its I/O bit location. The waveform generator uses the match signal to generate an
output according to operating m ode set by the WG M01:0 bits and Compare Output
mode (COM01:0) bits. The max and bottom signal s are us ed by the wavef orm generato r
for handling the special cases of the extreme values in some modes of operation (See
“Modes of Operation” on page 93.).
90
ATmega162/V
2513E–AVR–09/03
Figure 35 shows a block diagram of the output compare unit.
Figure 35. Output Compare Unit, Block Diagram
DATA BUS
ATmega162/V
top
bottom
FOCn
OCRn
=
(8-bit Comparator )
Waveform Generator
WGMn1:0
COMn1:0
TCNTn
OCFn (Int.Req.)
OCn
The OCR0 Regist er is doub le buff ered w hen using any of the Pulse W idth M odulation
(PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation ,
the double buffering is disabled. The double buffering synchronizes the update of the
OCR0 Compare Register to either t op or bottom of the countin g sequen ce. The syn chro nization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby
making the output glitch-free.
The OCR0 Register access may see m complex, but this is not case. When the doubl e
buffering is en abled, th e CPU has acc ess to the OCR0 Bu ffer Regist er, and if do uble
buffering is disabled the CPU will access the OCR0 directly.
Force Output CompareIn non-PWM waveform generat ion mo des, th e match output of the comparato r can be
forced by writing a one to the Force Ou tput Compare (FOC0 ) bit. Forcing Com pare
Match will not set th e OCF0 Flag or rel oad/clear the Time r, but the OC0 pi n 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 Blocking by
TCNT0 Write
All CPU write operations to the TCNT0 Register will block any Co mpare Match that
occur in the next timer clock cycle, even when the timer is stopped. This feature allows
OCR0 to be initialized to the same value as TCNT0 without triggering an interrupt when
the Timer/Counter clock is enabled.
91
2513E–AVR–09/03
Using the Output Compare
Unit
Since writing TCNT 0 in any m ode o f o peratio n will block al l com pare m atch es for o ne
timer clock cycle, there are risks involved when changing TC NT0 when using the output
compare channel, independently of w hether the Ti mer/Counter is running or n ot. 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 down-counting.
The setup of the OC0 should be perf ormed be fore set ting the Dat a Direct ion Regis ter fo r
the port pin to output. The easiest way of setting the OC0 value is to use the Force Output Compare (FOC 0) 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 i mmediately.
Compare Match Out put
Unit
The Compare Output mode (COM01 :0) bits have two functi ons. The Waveform Generator uses the COM01:0 bits for defining the Output Compare (OC0) state at the next
Compare Match. Also, the CO M01:0 bits control the OC0 pi n output so urce. Figu re 36
shows a simplified schemat ic of the logic affecte d by the CO M01:0 bi t setting. The I/O
Registers, I/O bits, and I/O pins in the figure 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. Whe n referring to the OC0 state, th e refe rence is f or the internal OC 0
Register, not the OC0 pin. If a System Reset occur, the OC0 Regist er is reset to “0”.
Figure 36. Compare Match Output Unit, Schematics
COMn1
COMn0
FOCn
Waveform
Generator
DQ
OCn
DQ
PORT
1
0
OCn
Pin
92
The general I/O port f unction is o verridden by the O utput Com pare (OC0) from the
waveform generator if either of the COM01:0 bits are set. However, the OC0 pin direction (input or output) is still controlled by the Data Direction Register (DDR) for the port
pin. The Data Direction Register bit for the OC0 pin (DDR_OC0) must be set as output
before the OC0 value is visible on the pin. The port override function is independent of
the Waveform Generation mode.
ATmega162/V
clk
DATA BUS
I/O
DQ
DDR
2513E–AVR–09/03
ATmega162/V
The design of the output compare pin logic allows initialization of the OC0 state before
the output is enabled. Note that some COM01:0 bit settings are reserved for certain
modes of operation. See “8-bit Timer/Counter Register Description” on page 99.
Compare Output Mode and
Waveform Generation
The Waveform Generator uses the COM01:0 bits differently in Normal, CTC, and PWM
modes. For all modes, setting the COM 01:0 = 0 tells the Waveform Generator tha t no
action on the OC 0 Register i s to be p erformed on the next Compa re Matc h. For Com pare Output actions in the non-PWM modes refer to Table 48 on page 100. For fast
PWM mode, refer to Table 49 on page 100, and for phase correct PW M refer to Ta ble
50 on page 100.
A change of the COM01:0 bits state will have effect at the first Compare Match after the
bits are writt en. For non-PWM modes, the action can be forced to have immediate effect
by using the FOC0 strobe bits.
Modes of OperationThe mode of operation, i.e., the behavior of the Timer/Counter and t he Output Compare
pins, is defined by the combination of the Waveform Generation mode (WGM01:0) and
Compare Out put mode (COM01:0 ) bits. Th e Compar e Outpu t mode bits do not affect
the counting sequen ce, while the Wav eform Generatio n mode bits do. Th e COM01:0
bits control whe ther the PWM output gene rated sho uld be invert ed or not (inver ted or
non-inverted PWM). For non-PWM modes the COM01:0 bits control whether the output
should be set, clea red, or to ggl ed at a Comp are Matc h (Se e “C ompa re M atch Out put
Unit” on page 92.).
For detailed timing information refer to Figure 40, Figure 41, Figure 42 and Figure 43 in
“Timer/Counter Timing Diagrams” on page 97.
Normal ModeThe simplest mo de of operation is the Normal mode (WGM 01:0 = 0). In this mod e 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 = 0 xFF) and then
restarts from the bottom (0x00 ). In normal operation the Time r/Counter Overflow F lag
(TOV0) will be set in the same timer clock cycle as the TCNT0 bec omes zero. The
TOV0 Flag in this case beh aves like a nin th bit, excep t that it is onl y set, not cleared.
However, combined with the timer overf low interrupt that automatically clears the TOV0
Flag, the timer resolution can be increased by so ftware. There are no special cases to
consider in the Normal mode, a new counter value can be written anytime.
Clear Timer on Compare
Match (CTC) Mode
2513E–AVR–09/03
The output compare unit can be used to generate interrupts at some given time. Using
the output compare to generate waveforms in Normal mode is not recommended, since
this will occupy too much of the CPU time.
In Clear Timer on Compare or CTC mode (WGM01:0 = 2), the OCR0 Regi ster i s used to
manipulate the counter resolution. In CTC mode the counter is cl eared to zero when the
counter value (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 simplifies the operation of counti ng external events.
The timing diagram for the CTC mode is shown in Figure 3 7. The counter value
(TCNT0) increases until a Comp are Match occ urs be tween TCNT0 and OCR0, and t hen
counter (TCNT0) is cleared.
93
Figure 37. CTC Mode, Timing Diagram
TCNTn
OCn Interrupt Flag Set
OCn
(Toggle)
Period
14
23
(COMn1:0 = 1)
An interrupt can be gene rated each time the co unte r val ue reac hes t he T OP va lue by
using the OCF0 Flag. If the interrupt is enabled, t he 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 the double buffering feature. If the new value writt en
to OCR0 is lower tha n the current val ue of TC NT0, the counter w ill mi ss the Co mpar e
Match. The co unter will then h ave to count to its maximum value (0xFF) an d 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 setti ng the Compare Output mode bits to toggl e
bitmode (COM01:0 = 1). The OC0 value wi ll not be visible on the port pin unless the
data direction for the pin is set to out put. The waveform generated will have a maximum
frequency of f
OC
0 = f
/2 when OCR0 is set to zero (0x00). The waveform frequency
clk_I/O
is defined by the following equati on:
f
clk_I/O
f
OCn
---------------------------------------------- -=
2 N1 OCRn+()⋅⋅
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
As for the Normal mode o f operation, the TOV0 Flag is set in the same time r clock cycle
that the counter counts from MAX to 0x00.
Fast PWM ModeThe fast Pulse Width Modulation or fast PW M mode (WGM01:0 = 3) provides a high fre-
quency PWM wave form g enerati on o ption . The fast PWM differs from the othe r PW M
option by its single-slope operation. The counter counts from BOTTOM to MAX then
restarts from BOTT OM. In no n-invertin g Compare Output mode , the Outpu t 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 m ode c an be twice as hi gh a s th e phas e correct PW M mod e th at use dua lslope operation. Th is high frequen cy make s the f ast PW M mo de wel l suited for power
regulation, recti fication , an d DA C app licat ions. High fr eque ncy al lows phy sically s mal l
sized external components (coils, capacitors), and therefore reduces total system cost.
In fast PWM mode, the counter is i ncremented until the counter value matches the MAX
value. The counter is then clear ed at t he fol lowing timer clock cycle. The timing dia gram
for the fast PWM mode is shown in Figure 38. The TCNT0 value is i n the timing diagram
shown as a histogram for illustrating the single-slope operation. The diagram includes
94
ATmega162/V
2513E–AVR–09/03
ATmega162/V
non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0
slopes represent com pare matches between OCR0 and TCNT0.
Figure 38. Fast PWM Mode, Timing Diagram
OCRn Interrupt Flag Set
OCRn Update ans
TOVn Interrupt Flag Set
TCNTn
OCn
OCn
Period
1
23
4567
(COMn1:0 = 2)
(COMn1:0 = 3)
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches MAX. If
the interrupt is enabled, the interrupt handler routine can be used for updating the compare value.
In fast PWM mode, the compare uni t allows generation of PWM waveforms on the OC0
pin. Setting the COM01:0 bits to two will produce a non-inverted PWM and an inverted
PWM output can be generated by setting the COM01:0 to three (See Table 49 on page
100). The actual OC0 val ue will only be visible on the port pin if the data direction for the
port pin is s et as o utput. T he PWM w aveform is ge nera ted by setting (or cl earing) the
OC0 Register at the Compare Match between OCR0 and TCNT0, and clearing (or setting) the OC0 Register at the timer clock cycle the counter is cleared (changes from
MAX to BOTTOM).
The PWM frequency for the output can be calculated by the following equation:
f
clk_I/O
f
OCnPWM
------------------=
N 256⋅
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
2513E–AVR–09/03
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 constan tly high or low output (depe nding on the polarity of the out put set by the COM01:0 bits.)
A frequency (with 50% duty cycle) wavef orm output in fast PWM mode can be achieved
by setting OC0 to toggle its logical level on each Compare Mat ch (COM01 :0 = 1). The
waveform generated will have a maxi mum freq uency of f
OC
0 = f
/2 when OCR0 is
clk_I/O
set to zero. This featu re is simi lar to the OC0 togg le in CTC m ode, except t he double
buffer feature of the output compare unit is enabled in the fast PWM mode.
95
Phase Correct PWM ModeThe phase correct PWM mode (WGM01:0 = 1) provides a high res olution phase correct
PWM waveform generat ion opt ion. The phase correct P WM mode is based on a du alslope operation. The cou nter counts repea tedly from BOTTO M to MAX and then fro m
MAX to BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC0)
is cleared on the Compare Match between TCNT0 and OCR0 while up-counting, and
set on the Compare Match while down-counting. In invert ing Output Compare mode, the
operation is inverted. The dual-sl ope operation has l ower maximum operati on frequen cy
than single slope operation. However, due to the symmetric feature of the dual-slope
PWM modes, these modes are preferred for motor control applications.
The PWM resol ution 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 reach es MAX, it change s the count d irection. T he TCN T0 value w ill
be equal to MAX for one timer clock cycle. The timing diagram for the phase correct
PWM mode is shown on Figure 39. 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 sma ll horizontal line marks on the TCNT0 slopes represent compare matches between OCR0 and TCNT0.
Figure 39. Phase Correct PWM Mode, Timing Diagram
OCn Interrupt Flag Set
OCRn Update
TOVn Interrupt Flag Set
TCNTn
OCn
OCn
Period
123
(COMn1:0 = 2)
(COMn1:0 = 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 compar e uni t allows g enera tion of PWM waveforms on
the OC0 pin. Setting the COM01:0 bits to two will produce a non-inverted PWM. An
inverted PWM output can be generated by setting the COM01:0 to three (See Table 50
on page 100). 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
96
ATmega162/V
2513E–AVR–09/03
ATmega162/V
between OCR0 and TCNT0 when 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
OCnPCPWM
The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
The extreme values for the OCR0 Register represent special cases when generati ng a
PWM waveform output in the phase correct PWM mode. If the OCR0 is set equal to
BOTTOM, the output will be continuously low and if set equal to MAX the output will be
continuously high for non-inverted PW M mo de. For inverted PWM the output w ill have
the opposite logic values.
At the very start of period 2 in Figure 39 OCn has a transition from high to low even
though there is no Compare Match. The point of this transition i s to guarantee symmetry
around BOTTOM. There are two cases that give a transition wit hout Compare Match.
•OCR0 changes its val ue from MAX, lik e i n Figure 39. When t he OCR0 va lue 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 correspond to the
result of an up-counting Compare Match.
•The timer starts counting from a value higher than the one in OCR0, and f or that
reason misses the Compare Match and hence the OCn change that would ha ve
happened on the way up.
------------------=
N 510⋅
Timer/Counter Timing
Diagrams
The Timer/Counter is a synchronous de sign and the timer clock (clkT0) is therefore
shown as a clock enable signal in the following figures. The figures include information
on when Interrupt Flags are set. Figure 40 contains timing data for basic Timer/Counter
operation. T he figure s hows the co unt s equen ce close to the MA X va lue in all modes
other than phase correct PWM mode.
Figure 40. Timer/Counter Timing Diagram, no Prescaling
clk
I/O
clk
Tn
(clk
/1)
I/O
TCNTnMAX - 1MAXBOTTOMBOTTOM + 1
TOVn
Figure 41 shows the same timing data, but with the prescaler enabled.
2513E–AVR–09/03
97
Figure 41. Timer/Counter Timing Diag ram, wi th Prescaler (f
clk
I/O
clk
Tn
(clk
/8)
I/O
clk_I/O
/8)
TCNTn
MAX - 1MAXBOTTOMBOTTOM + 1
TOVn
Figure 42 shows the setting of OCF0 in all modes except CTC mode.
Figure 42. Timer/Counter Timing Diagram, Setting of OCF0, with Prescaler (f
clk
I/O
clk
Tn
(clk
/8)
I/O
TCNTn
OCRn
OCFn
OCRn - 1OCRnOCRn + 1OCRn + 2
OCRn Value
clk_I/O
/8)
98
Figure 43 shows the setting of OCF0 and the clearing of TCNT0 in CTC mode.
Figure 43. Timer/Counter Timing Diagram, Clear Timer on Compare Match Mode, with
The FOC0 bit is only active when the WGM00 bit specifies a non -PW M mode. However,
for ensuring compatibil ity with f uture devices, this bit must be set t o zero when TCCR0 i s
written whe n ope rating in PW M m ode. W hen writi ng a logic al o ne to the FOC 0 bit, an
immediate Compare Match is forced on the Wavefor m Generation unit. The OC0 output
is changed according to its COM01:0 bits setti ng. Note that t he FOC0 bit is implement ed
as a strobe. Therefore it is the value presen t in the COM01 :0 bits that dete rmines the
effect of the forced compare.
A FOC0 strobe will not genera te any interrupt, nor will it clear th e tim er in C TC m ode
using OCR0 as TOP.
The FOC0 bit is always read as zero.
• Bit 6, 3 – WGM01:0: Wa veform Generation Mode
These bits contro l the counting sequence of the co unter, th e source for the max imum
(TOP) counter value, and what type of waveform generation to be used. Modes of operation supported by the Timer/Counter unit are: Normal mode, Clear Timer on Compare
match (CTC) mode, and two types of Pulse Wi dth Modulation (PWM) modes. See Table
47 and “Modes of Operation” on page 93.
Table 47. W aveform Generation Mode Bit Description
WGM01
Mode
Note:1. The CTC0 and PWM0 bit definition names are now obsolete. Use the WGM01:0 def-
initions. However, the functionality and location of these bits are compatible with
previous versions of the timer.
WGM00
(PWM0)
Timer/Counter Mode
of OperationTOP
(1)
Update of
OCR0 at
TOV0 Flag
Set on
• Bit 5:4 – COM01:0: Compare Match Output Mode
These bits co ntrol the outp ut compar e pin (OC0) beh avior. If on e or both of the
COM01:0 bits are set, the OC0 output overrides the normal port functionality of the I/O
pin it is connec ted to . Howev er, no te that the Da ta Di rection Regist er (DDR ) bit corresponding to the OC0 pin must be set in order to enable the output dri ver.
2513E–AVR–09/03
99
When OC0 is connected to the pin, the function of the COM01:0 bits depends on the
WGM01:0 bit setting. Table 48 shows the COM01:0 bit functionality wh en the WGM01:0
bits are set to a Normal or CTC mode (non-PWM).
Table 48. Compare Output Mode, non-PWM Mode
COM01COM00Description
00Normal port operation, OC0 disconnected.
01Toggle OC0 on Compare Match.
10Clear OC0 on Compare Match.
11Set OC0 on Compare Match.
Table 49 show s the COM 01:0 bit func tional ity when t he WGM01 :0 bits ar e set to fast
PWM mode.
Table 49. Compare Output Mode, fast PWM Mode
COM01COM00Description
00Normal port operation, OC0 disconnected.
01Reserved
10Clear OC0 on Compare Match, set OC0 at TOP.
11Set OC0 on Compare Match, clear OC0 at TOP.
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 94 for more details.
(1)
Table 50 shows the COM01:0 bit functionality when the WGM01:0 bits are set to phase
correct PWM mode.