Rainbow Electronics ATmega162V User Manual

Features

High-performance, Low-power AVR
Advanced RISC Architecture
– 131 Powerful Instructions – Most Single-clock Cycle Execution – 32 x 8 General Purpose Working Registers – Fully Static Operation – Up to 16 MIPS Throughput at 16 MHz – On-chip 2-cycle Multiplier
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
I/O and Packages
– 35 Programmable I/O Lines – 40-pin PDIP, 44-lead TQFP, and 44-pad MLF
Operating Voltages
– 1.8 - 5.5V for ATmega162V – 2.7 - 5.5V for ATmega162
Speed Grades
– 0 - 8 MHz for ATmega162V (see Figure 113 on page 265) – 0 - 16 MHz for ATmega162 (see Figure 114 on page 265)
®
8-bit Microcontroller
8-bit Microcontroller with 16K Bytes In-System Programmable Flash
ATmega162 ATmega162V
2513E–AVR–0 9/ 0 3

Pin Configurations Figure 1. Pinout ATmega162

(RXD1/AIN0) PB2
(TXD1/AIN1) PB3
(INT0/XCK1) PD2
(TOSC1/XCK0/OC3A) PD4
(INT0/XCK1) PD2
(TOSC1/XCK0/OC3A) PD4
(OC1A/TOSC2) PD5
(INT1/ICP3) PD3
(OC1A/TOSC2) PD5
(MOSI) PB5 (MISO) PB6
(SCK) PB7
RESET
(RXD0) PD0
(TXD0) PD1
(INT1/ICP3) PD3
(OC0/T0) PB0 (OC2/T1) PB1
(SS/OC3B) PB4
(MOSI) PB5 (MISO) PB6
(SCK) PB7
RESET
(RXD0) PD0
(TXD0) PD1
(WR) PD6
(RD) PD7
XTAL2 XTAL1
GND
44 42 40 38 36 34
1 2 3 4 5
VCC
6 7 8 9 10 11
12 14 16 18 20 22
PDIP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
PB4 (SS/OC3B)
PB3 (TXD1/AIN1)
PB2 (RXD1/AIN0)
43 41 39 37 35
13 15 17 19 21
40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21
TQFP/MLF
PB1 (OC2/T1)
PB0 (OC0/T0)
GND
VCC
PA0 (AD0/PCINT0)
VCC PA0 (AD0/PCINT0) PA1 (AD1/PCINT1) PA2 (AD2/PCINT2) PA3 (AD3/PCINT3) PA4 (AD4/PCINT4) PA5 (AD5/PCINT5) PA6 (AD6/PCINT6) PA7 (AD7/PCINT7) PE0 (ICP1/INT2) PE1 (ALE) PE2 (OC1B) PC7 (A15/TDI/PCINT15) PC6 (A14/TDO/PCINT14) PC5 (A13/TMS/PCINT13) PC4 (A12/TCK/PCINT12) PC3 (A11/PCINT11) PC2 (A10/PCINT10) PC1 (A9/PCINT9) PC0 (A8/PCINT8)
PA1 (AD1/PCINT1)
PA2 (AD2/PCINT2)
PA3 (AD3/PCINT3)
PA4 (AD4/PCINT4)
33
PA5 (AD5/PCINT5)
32
PA6 (AD6/PCINT6)
31
PA7 (AD7/PCINT7)
30
PE0 (ICP1/INT2)
29
GND
28
PE1 (ALE)
27
PE2 (OC1B)
26
PC7 (A15/TDI/PCINT15)
25
PC6 (A14/TDO/PCINT14)
24
PC5 (A13/TMS/PCINT13)
23
VCC
GND
XTAL2
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

Disclaimer Typical 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

Overview The 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 sys­tem designer to optimize power consumption versus processing speed.

Block Diagram Figure 2. Block Diagram

VCC
PA0 - PA7 PC0 - 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 pro­gramming, 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 con­tents 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 con­tinue 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-Cir­cuit 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 ck­ward 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 Vec­tors 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

VCC Digital supply voltage GND Ground 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 acti­vated 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

XTAL1 Input to the Inverting Oscillator amplifier and input to the int ernal clock operating circuit . XTAL2 Output from the Inverting Oscillator amplifier.

Reset input. A low level on this pin for longer than the minimum pulse length will gener­ate 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 defini­tions 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

Introduction This 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 Overview Figure 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 exe­cuted, 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 In­System 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 Pro­gram 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 con­stant 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-func­tions. 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 truc­tion Set” section for a detailed description.

Status Register The 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.
8
ATmega162/V
2513E–AVR–09/03
ATmega162/V
The AVR Status Register – SREG – is defined as:
Bit 76543210
ITHSVNZCSREG
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value00000000
• Bit 7 – I: Glob a l In te r ru p t En a bl e
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individ­ual 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 I­bit 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 Comple­ment 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 “Instruc­tion 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 R1 0x01 R2 0x02
R13 0x0D
General R14 0x0E Purpose R15 0x0F Working R16 0x10
Registers R17 0x11
… R26 0x1A X-register Low Byte R27 0x1B X-register High Byte R28 0x1C Y-register Low Byte R29 0x1D Y-reg ister High Byte R30 0x1E Z-register Low Byte R31 0x1F Z-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 phys­ically 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
15 XH XL 0
X - register 7 0 7 0
R27 (0x1B) R26 (0x1A)
15 YH YL 0
Y - register 7 0 7 0
R29 (0x1D) R28 (0x1C)
15 ZH ZL 0
Z - register 7 0 7 0
R31 (0x1F) R30 (0x1E)
In the different addressi ng mode s these ad dress registe rs have f unctions as f ixed di s­placement, autom atic increment, and aut omatic decreme nt (see the instruction set reference for details).

Stack Pointer The 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 Regis­ter 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 Inter­rupt 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 num­ber 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.
Bit 1514131211109 8
SP15 SP14 SP13 SP12 SP11 SP10 SP9 SP8 SPH
SP7 SP6 SP5 SP4 SP3 SP2 SP1 SP0 SPL
76543210
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W
R/W R/W R/W R/W R/W R/W R/W R/W
Initial 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 pelin­ing 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
T1 T2 T3 T4
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
T1 T2 T3 T4
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 er­rupts. 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 remem­bered 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 corre­sponding 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 disap­pears 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 exe­cute one more instruction before any pending interrupt is served.
Note that the Status Regi ster is not automatically stored when entering an interrupt rou­tine, 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 simulta­neously 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 Time The 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 mem­ory 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 – Read­While-Write Self-pro gramming” on page 216. “Memory Programming” on page 230 con­tains 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 Execu­tion 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 Memory Figure 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 non­compatible 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 loca­tions 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 instruc­tion set manual for one, two, and three wait -states.
The five dif ferent addressing modes for the data memory cover: Direct, Indirect with Dis­placement, 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 post­increment, 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 Times This 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
T1 T2 T3
clk
CPU
Address
Data
WR
Data
RD
Compute Address
Memory Access Instruction
Address valid
Write
Read
Next Instruction
17

EEPROM Data Memory The 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 Pro­gramming in SPI, JTAG, or Parallel Programming mode.

EEPROM Read/Write Access The 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, how­ever, 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 ol­lowed. 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

Bit 151413121110 9 8
–––––––EEAR8EEARH
EEAR7 EEAR6 EEAR5 EEAR4 EEAR3 EEAR2 EEAR1 EEAR0 EEARL
76543210
Read/Write R R R R R R R R/W
R/W R/W R/W R/W R/W R/W R/W R/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 writ­ten before the EEPROM may be accessed.
18
ATmega162/V
2513E–AVR–09/03
ATmega162/V

The EEPROM Data Register – EEDR

The EEPROM Control Regi ster – EECR

Bit 76543210
MSB LSB EEDR
Read/Write R/W R/W R /W R/W R/W R/W R/W R/W Initial Value00000000
• Bits 7..0 – EEDR7.0: EEPROM Data
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 oper­ation, the EEDR contains the data read out from the EEPROM at the address given by EEAR.
Bit 76543210
EERIE EEMWE EEWE EERE EECR
Read/Write R R R R R/W R/W R/W R/W Initial Valu e 0 0 0 0 0 0 X 0
• 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) 8448 8.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 inter­rupts 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 com­mand 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 Memory The 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 reg­isters 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)

Overview When 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 inter­face 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 activ­ity 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 Requirements Due 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 Keeper The 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.

Timing External 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 fea­ture, 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 exter­nal 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
(SRWn1 = 0 and SRWn0 =0)
T1 T2 T3
System Clock (CLK
DA7:0 (XMBK = 0)
DA7:0 (XMBK = 1)
CPU
ALE
A15:8
DA7:0
WR
RD
)
(1)
Address DataPrev. data XX
T4
AddressPrev. addr.
Write
DataAddress
DataPrev. data Address
Read
Note: 1 . SRWn1 = SRW11 (upper sector) or SRW01 (lower sector), SRWn0 = SRW10 (upper
sector) or SRW00 (lower sector). The ALE pulse in per iod T4 is only present if the next instruction accesses the RAM (internal or external).
26
ATmega162/V
2513E–AVR–09/03
ATmega162/V
Figure 14. External Data Memory Cycles with SRWn1 = 0 and SRWn0 = 1
System Clock (CLK
DA7:0 (XMBK = 0)
DA7:0 (XMBK = 1)
CPU
ALE
A15:8
DA7:0
WR
RD
T1 T2 T3
)
AddressPrev. addr.
Address DataPrev. data XX
DataAddress
DataPrev. data Address
T4
(1)
T5
Note: 1 . SRWn1 = SRW11 (upper sector) or SRW01 (lower sector), SRWn0 = SRW10 (upper
sector) or SRW00 (lower sector) The ALE pulse in per iod T5 is only present if the next instruction accesses the RAM (internal or external).
Figure 15. External Data Memory Cycles with SRWn1 = 1 and SRWn0 = 0
System Clock (CLK
CPU
)
T1 T2 T3
ALE
T4 T5
(1)
T6
Write
Read
A15:8
DA7:0
WR
DA7:0 (XMBK = 0)
DA7:0 (XMBK = 1)
Address DataPrev. data XX
RD
AddressPrev. addr.
Write
DataAddress
DataPrev. data Address
Read
Note: 1 . SRWn1 = SRW11 (upper sector) or SRW01 (lower sector), SRWn0 = SRW10 (upper
sector) or SRW00 (lower sector). The ALE pulse in per iod T6 is only present if the next instruction accesses the RAM (internal or external).
2513E–AVR–09/03
27

XMEM Register Description

Figure 16. External Data Memory Cycles with SRWn1 = 1 and SRWn0 = 1
System Clock (CLK
DA7:0 (XMBK = 0)
DA7:0 (XMBK = 1)
CPU
ALE
A15:8
DA7:0
WR
)
T1 T2 T3
AddressPrev. addr.
Address DataPrev. data XX
DataAddress
DataPrev. data Address
RD
T4 T5 T6
(1)
T7
Write
Read
Note: 1 . SRWn1 = SRW11 (upper sector) or SRW01 (lower sector), SRWn0 = SRW10 (upper
sector) or SRW00 (lower sector). The ALE pulse in per iod T7 is only present if the next instruction accesses the RAM (internal or external).

MCU Control Register – MCUCR

Extended MCU Control Register – EMCUCR

Bit 76543210
SRE SRW10
Read/Write R/W R/W R /W R/W R/W R/W R/W R/W Initial Value00000000
SE SM1 ISC11 ISC10 ISC01 ISC00 MCUCR
• Bit 7 – SRE: Exte r n a l S R A M /XMEM Enab le
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 over­rides 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 76543210
SM0 SRL2SRL1SRL0SRW01SRW00SRW11ISC2 EMCUCR
Read/Write R/W R/W R /W R/W R/W R/W R/W R/W Initial Value00000000
• 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
SRL2 SRL1 SRL0 Sector Lim its
000
001
010
011
100
101
110
111
Lower sector = N/A Upper sector = 0x1100 - 0xFFFF
Lower sector = 0x1100 - 0x1FFF Upper sector = 0x2000 - 0xFFFF
Lower sector = 0x1100 - 0x3FFF Upper sector = 0x4000 - 0xFFFF
Lower sector = 0x1100 - 0x5FFF Upper sector = 0x6000 - 0xFFFF
Lower sector = 0x1100 - 0x7FFF Upper sector = 0x8000 - 0xFFFF
Lower sector = 0x1100 - 0x9FFF Upper sector = 0xA000 - 0xFFFF
Lower sector = 0x1100 - 0xBFFF Upper sector = 0xC000 - 0xFFFF
Lower sector = 0x1100 - 0xDFFF Upper sector = 0xE000 - 0xFFFF
• 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
SRWn1 SRWn0 Wait-states
0 0 No wait-states 0 1 Wait one cycle during read/write strobe 1 0 Wait 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
29

Special Function IO Register – SFIOR

Bit 7654321 0
TSM XMBK XMM2 XMM1 XMM0 PUD PSR2 PSR310 SFIOR
Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Valu e 0 0 0 0 0 0 0 0
• Bit 6 – XMBK: External Memory Bus Keeper Enable
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
XMM2 XMM1 XMM0 # Bits for External Memory Address Released Port Pins
0008 (Full 60 KB space) None

Using all Locations of External Memory Small er than 64 KB

0017 PC7 0106 PC7 - PC6 0115 PC7 - PC5 1004 PC7 - PC4 1013 PC7 - PC3 1102 PC7 - PC2 111No Address high bits Full 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 exter­nal 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 loca­tion 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
Loading...
+ 293 hidden pages